Python 使用opencv测量两个元素之间的距离

Python 使用opencv测量两个元素之间的距离,python,opencv,Python,Opencv,我有从车里拍的视频。我的程序是测量前轮和路面白线之间的距离。此脚本对于左侧视频和右侧视频运行良好 但有时它测量的是前轮和右侧白线之间的错误距离 thresh = 150 distance_of_wood_plank = 80 pixel_of_wood_plank = 150 origin_width = 0 origin_height = 0 wheel_x = 0; wheel_y = 0 #xpoint and ypoint of wheel df = pandas.DataFrame(

我有从车里拍的视频。我的程序是测量前轮和路面白线之间的距离。此脚本对于左侧视频和右侧视频运行良好

但有时它测量的是前轮和右侧白线之间的错误距离

thresh = 150
distance_of_wood_plank = 80
pixel_of_wood_plank = 150
origin_width = 0
origin_height = 0
wheel_x = 0; wheel_y = 0 #xpoint and ypoint of wheel

df = pandas.DataFrame(columns=["Frame_No", "Distance", "TimeStrap"])
cap = cv2.VideoCapture(args.video)
frame_count = 0;
while(cap.isOpened()): #Reading input video by VideoCapture of Opencv
    try:
        frame_count += 1
        ret, source = cap.read() # get frame from video
        origin_height, origin_width, channels = source.shape

        timestamps = [cap.get(cv2.CAP_PROP_POS_MSEC)]
        milisecond = int(timestamps[0]) / 1000
        current_time = str(datetime.timedelta(seconds = milisecond))
        cv2.waitKey(1)
        grayImage = cv2.cvtColor(source, cv2.COLOR_RGB2GRAY) # get gray image
        crop_y = int(origin_height / 3 * 2) - 30
        crop_img = grayImage[crop_y:crop_y + 100, 0:0 + origin_width] # get interest area
        blur_image = cv2.blur(crop_img,(3,3))
        ret, th_wheel = cv2.threshold(blur_image, 10, 255, cv2.THRESH_BINARY) #get only wheel
        ret, th_line = cv2.threshold(blur_image, 150, 255, cv2.THRESH_BINARY) #get only white line
        contours, hierarchy = cv2.findContours(th_wheel, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:]
        # get xpoint and ypoint of wheel
        for cnt in contours:
            x, y, w, h = cv2.boundingRect(cnt)
            if (x < origin_width/ 4):
                continue
            elif (w < 10):
                continue
            elif (w > 80):
                continue
            elif (x > origin_width / 4 * 3):
                continue
            wheel_x = int(x)
            wheel_y = int(y + h / 2 - 8)
        pixel_count = 0 # count of pixel between wheel and white line
        # get distance between wheel and white line
        if (wheel_x > origin_width/2):
            wheel_x -= 7
            for i in range(wheel_x, 0, -1):
                pixel_count += 1
                suit_point = th_line[wheel_y,i]
                if (suit_point == 255):
                    break
                if (i == 1):
                    pixel_count = 0
            pixel_count -= 4
            cv2.line(source, (wheel_x - pixel_count, wheel_y + crop_y), (wheel_x, wheel_y + crop_y), (255, 0, 0), 2)
        else :
            wheel_x += 7
            for i in range(wheel_x , origin_width):
                pixel_count += 1
                suit_point = th_line[wheel_y,i]
                if (suit_point == 255):
                    break
                if (i == origin_width - 1):
                    pixel_count = 0
            pixel_count += 4
            cv2.line(source, (wheel_x, wheel_y + crop_y), (wheel_x + pixel_count, wheel_y + crop_y), (255, 0, 0), 2)
        distance_Cm = int(pixel_count * 80 / pixel_of_wood_plank)
        str_distance = ""
        if distance_Cm > 10:
            str_distance = str(distance_Cm) + "Cm"
        else:
            str_distance = "No white line"

        cv2.putText(source, str_distance, (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2, cv2.LINE_AA)

        df = df.append({'Frame_No': frame_count,'Distance': str_distance ,'TimeStrap': current_time}, ignore_index = True)

        df.to_csv("result.csv")
        cv2.imshow("Distance_window", source)
        cv2.waitKey(1)
    except:
        pass
thresh=150
木材与木板之间的距离=80
木材板材的像素=150
原点宽度=0
原点高度=0
轮_x=0;车轮y=0#车轮的X点和y点
数据帧(列=[“帧号”、“距离”、“时间陷阱”])
cap=cv2.VideoCapture(args.video)
帧计数=0;
while(cap.isOpened()):#通过Opencv的视频捕获读取输入视频
尝试:
帧计数+=1
ret,source=cap.read()#从视频中获取帧
原点高度,原点宽度,通道=source.shape
时间戳=[cap.get(cv2.cap\u PROP\u POS\u MSEC)]
毫秒=int(时间戳[0])/1000
当前时间=str(datetime.timedelta(秒=毫秒))
cv2.等待键(1)
grayImage=cv2.CVT颜色(源,cv2.COLOR_RGB2GRAY)#获取灰度图像
裁剪y=int(原点高度/3*2)-30
裁剪图像=灰度图像[裁剪y:裁剪y+100,0:0+原点宽度]#获取感兴趣区域
模糊图像=cv2.模糊(裁剪图像,(3,3))
ret,th_wheel=cv2.threshold(模糊图像,10255,cv2.THRESH_二进制)#仅获取wheel
ret,th_line=cv2.threshold(模糊图像,150255,cv2.THRESH_二进制)#仅获取白线
轮廓,层次=cv2.findContours(th_车轮,cv2.RETR_列表,cv2.CHAIN_近似简单)[2:]
#获取轮子的xpoint和ypoint
对于轮廓中的cnt:
x、 y,w,h=cv2.boundingRect(cnt)
如果(x<原点\宽度/4):
持续
elif(w<10):
持续
elif(w>80):
持续
elif(x>原点宽度/4*3):
持续
车轮x=int(x)
车轮y=int(y+h/2-8)
像素计数=0#滚轮和白线之间的像素计数
#获取车轮和白线之间的距离
如果(车轮>原点>宽度/2):
车轮x-=7
对于范围内的i(车轮x,0,-1):
像素计数+=1
适配点=第一线[轮y,i]
如果(拟合点=255):
打破
如果(i==1):
像素计数=0
像素计数-=4
cv2.行(源,(轮x-像素数,轮y+裁剪y),(轮x,轮y+裁剪y),(255,0,0),2)
其他:
车轮x+=7
对于范围内的i(车轮x,原点x宽度):
像素计数+=1
适配点=第一线[轮y,i]
如果(拟合点=255):
打破
如果(i==原点\宽度-1):
像素计数=0
像素计数+=4
cv2.行(源,(轮x,轮y+裁剪y),(轮x+像素计数,轮y+裁剪y),(255,0,0),2)
距离\u Cm=int(像素数*80/像素木板)
str_distance=“”
如果距离_Cm>10:
距离=距离+厘米
其他:
str_distance=“无白线”
cv2.putText(源,str_距离,(50250),cv2.FONT_HERSHEY_单纯形,1,(255,0,0),2,cv2.LINE_AA)
追加({'Frame\u No':Frame\u count,'Distance':str\u Distance,'TimeStrap':current\u time},ignore\u index=True)
df.to_csv(“result.csv”)
cv2.imshow(“距离窗口”,来源)
cv2.等待键(1)
除:
通过

以下是视频链接-

您在测量轮胎和白线之间的距离方面做得非常好。你需要考虑的是你的样品中有多少噪音。除非你停下卡车,下车,用卷尺测量轮胎到线路的距离,否则你永远不会知道它到底有多远。你还需要考虑到(除非你弄坏了卡车),轮胎与白线之间的距离在每个帧之间不会超过几像素。

最好的解决方案是卡尔曼滤波器,但这相当复杂。我使用了一个更简单的解决方案。为了找到线的位置,我平均了最后四个值以减少噪音

将numpy作为np、cv2导入
thresh=150
木材与木板之间的距离=80
木材板材的像素=150
原点宽度=0
原点高度=0
轮_x=0;车轮y=0#车轮的X点和y点
cap=cv2.VideoCapture('/home/stephen/Desktop/20180301 1100 VW Right.mp4')
帧计数=0;
vid_writer=cv2.VideoWriter('/home/stephen/Desktop/writer.avi',cv2.VideoWriter_fourcc('M','J','P','G'),30,(480360))
职位=[]
输入数学
定义距离(a,b):返回数学sqrt((a[0]-b[0])**2+(a[1]-b[1])**2)
while(cap.isOpened()):#通过Opencv的视频捕获读取输入视频
帧计数+=1
ret,source=cap.read()#从视频中获取帧
原点高度,原点宽度,通道=source.shape
grayImage=cv2.CVT颜色(源,cv2.COLOR_RGB2GRAY)#获取灰度图像
裁剪y=int(原点高度/3*2)-30
裁剪图像=灰度图像[裁剪y:裁剪y+100,0:0+原点宽度]#获取感兴趣区域
模糊图像=cv2.模糊(裁剪图像,(3,3))
ret,th_wheel=cv2.threshold(模糊图像,10255,cv2.THRESH_二进制)#仅获取wheel
ret,th_line=cv2.threshold(模糊图像,150255,cv2.THRESH_二进制)#仅获取白线
轮廓,层次=cv2.findContours(th_车轮,cv2.RETR_列表,cv2.CHAIN_近似简单)[2:]
#获取轮子的xpoint和ypoint
对于轮廓中的cnt:
x、 y,w,h=cv2.boundingRect(cnt)
如果(x<原点\宽度/4):
持续
elif(w<10):
持续
elif(w>80):
持续
elif(x>原点宽度/4*3):
持续
车轮x=int(x)
车轮y=int(y+h/2-8)
皮克斯
import numpy as np, cv2

thresh = 150
distance_of_wood_plank = 80
pixel_of_wood_plank = 150
origin_width = 0
origin_height = 0
wheel_x = 0; wheel_y = 0 #xpoint and ypoint of wheel

cap = cv2.VideoCapture('/home/stephen/Desktop/20180301 1100 VW Right.mp4')
frame_count = 0;
vid_writer = cv2.VideoWriter('/home/stephen/Desktop/writer.avi', cv2.VideoWriter_fourcc('M','J','P','G'), 30, (480,360))

positions = []

import math
def distance(a,b): return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)

while(cap.isOpened()): #Reading input video by VideoCapture of Opencv
    frame_count += 1
    ret, source = cap.read() # get frame from video
    origin_height, origin_width, channels = source.shape
    grayImage = cv2.cvtColor(source, cv2.COLOR_RGB2GRAY) # get gray image
    crop_y = int(origin_height / 3 * 2) - 30
    crop_img = grayImage[crop_y:crop_y + 100, 0:0 + origin_width] # get interest area
    blur_image = cv2.blur(crop_img,(3,3))
    ret, th_wheel = cv2.threshold(blur_image, 10, 255, cv2.THRESH_BINARY) #get only wheel
    ret, th_line = cv2.threshold(blur_image, 150, 255, cv2.THRESH_BINARY) #get only white line
    contours, hierarchy = cv2.findContours(th_wheel, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:]
    # get xpoint and ypoint of wheel
    for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)
        if (x < origin_width/ 4):
            continue
        elif (w < 10):
            continue
        elif (w > 80):
            continue
        elif (x > origin_width / 4 * 3):
            continue
        wheel_x = int(x)
        wheel_y = int(y + h / 2 - 8)
    pixel_count = 0 # count of pixel between wheel and white line
    # get distance between wheel and white line
    if (wheel_x > origin_width/2):
        wheel_x -= 7
        for i in range(wheel_x, 0, -1):
            pixel_count += 1
            suit_point = th_line[wheel_y,i]
            if (suit_point == 255):
                break
            if (i == 1):
                pixel_count = 0
        pixel_count -= 4
    else :
        wheel_x += 7
        for i in range(wheel_x , origin_width):
            pixel_count += 1
            suit_point = th_line[wheel_y,i]
            if (suit_point == 255):
                break
            if (i == origin_width - 1):
                pixel_count = 0
        pixel_count += 4
        a,b = (wheel_x - pixel_count, wheel_y + crop_y), (wheel_x, wheel_y + crop_y)
        if distance(a,b)>10: positions.append((wheel_x + pixel_count, wheel_y + crop_y))

    if len(positions)>10:
        radius = 2
        for position in positions[-10:]:
            radius += 2
            center = tuple(np.array(position, int))
            color = 255,255,0
            cv2.circle(source, center, radius, color, -1)
        x,y = zip(*positions[-4:])
        xa, ya = np.average(x), np.average(y)
        center = int(xa), int(ya)
        cv2.circle(source, center, 20, (0,0,255), 10)

    cv2.imshow("Distance_window", source)
    vid_writer.write(cv2.resize(source, (480,360)))
    k = cv2.waitKey(1)
    if k == 27: break

cv2.destroyAllWindows()