python-opencv直线检测+直线拟合+计算直线间距离

python-opencv直线检测+直线拟合+计算偏移量

计算边界直线与x坐标轴的距离=首先canny边缘检测——>直线检测——>直线拟合——>计算与x坐标轴的距离。

直接上代码:

import cv2 #opencv读取的格式是BGR
import numpy as np 

vc = cv2.VideoCapture('D:/Desktop/duizhong/fangzhen.mp4')

if vc.isOpened(): #判断能否读取
    open, frame = vc.read()
else:
    open = False
while open:
    ret, frame = vc.read()
    if frame is None:#读取为空
        break
    if ret == True:#读取不为空


#边缘检测
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        blur = cv2.blur(gray, (3, 3))#矩阵维度3*3
        aussian = cv2.GaussianBlur(frame, (5, 5), 1) 
        v1=cv2.Canny(blur,80,150)#minval、maxval的值
        #值小时检测更仔细
        cv2.imshow("canny",v1)

#直线检测
        roi = frame[150:400,300:700]
        gray1 = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
        blur1 = cv2.blur(gray1, (3, 3))#矩阵维度3*3
        v2=cv2.Canny(blur1,80,150)#minval、maxval的值
        minLineLength = 5
        maxLineGap =10
        lines = cv2.HoughLinesP(v2, 1, np.pi/180, 10, minLineLength, maxLineGap) 

        while lines is None:
            break
        else:
        	
            for line in lines:

                x1,y1,x2,y2 = line[0]
                loc=[]
                cv2.line(roi,(x1,y1), (x2,y2), (0,255,0),2)
                loc.append([x1,y1])
                loc.append([x2,y2])
                loc= np.array(loc)
                #print(line[0])
                #print(lines)
                output =cv2.fitLine(loc,cv2.DIST_L2,0,0.01,0.01)
                k = output[1] / output[0]
                c = output[3] - k * output[2]+150#因为在roi窗口坐标系与原坐标系相差150
                s=frame.shape
                a=s[0]//2
                #print(c)
                dx=c-a#偏移量
                print(dx)
            cv2.imshow("line",frame)

#轮廓检侧
        blur1 = cv2.blur(gray1, (3, 3))#矩阵维度3*3
        ret, thresh = cv2.threshold(blur1, 127, 255, cv2.THRESH_BINARY)
        contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
        res = cv2.drawContours(roi, contours, -1, (0, 0, 255), 2)#-1表示绘制所有,改数选择绘制的图像、2线条宽度
       
        #cv2.imshow('res',res)

#中心线也就是坐标轴x轴
        s=frame.shape
        a=s[0]//2
        b=s[1]
        cv2.line(frame,(0,a),(b,a),(0, 0, 255),2) 
        cv2.imshow("line",frame) 


        if cv2.waitKey(10) & 0xFF == 27:
           break
vc.release()
cv2.destroyAllWindows()

视频:

python-opencv直线检测+直线拟合+计算直线间距离

 

你可能感兴趣的:(python,opencv)