python opencv 路线检测

树莓派python opencv 路线检测

  • 效果
  • 代码
    • 图像处理
    • 自定义选区
    • 直线检测
    • 输出斜率
    • 画延长线
    • 保存视频
  • 下载地址

效果

处理前
python opencv 路线检测_第1张图片
处理后,标注路线 斜率
python opencv 路线检测_第2张图片

代码

图像处理

    # 
	equ = cv2.equalizeHist(gray)
	# 
	gaussian = cv2.GaussianBlur(gray, (3, 3), 0, 0, cv2.BORDER_DEFAULT)
	# 
	median = cv2.medianBlur(gaussian, 5)
	# 
	sobel = cv2.Sobel(median, cv2.CV_8U, 1, 0, ksize = 3)
	# 
	ret, binary = cv2.threshold(sobel, 30,255, cv2.THRESH_BINARY)
	# 
	element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 1))
	element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 1))
	# 
	erosion = cv2.erode(binary, element1, iterations = 1)
	# 
	dilation = cv2.dilate(erosion, element2, iterations = 1)

自定义选区

pts=np.array([[160,80],[160,0],[0,0],[0,80],[80,40]])
        cv2.fillPoly(img, [pts], (0, 0, 0)) 

直线检测

    lines = cv2.HoughLinesP(gray, 1, np.pi/180, 40,40,30)
    try:
        for x1, y1, x2, y2 in lines[0]:
            x1,y1,x2,y2 = Extend_line(x1,y1,x2,y2,160,120,0)
            cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 1)
            num = angle(x1, y1, x2, y2)
            cv2.putText(image, str(num), (0, 30), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 2)

输出斜率

    #
    a = x1-x2
    b = abs(y1-y2)
    c = math.sqrt(a**2+b**2)

    #
    A=math.degrees(math.acos((a*a-b*b-c*c)/(-2*b*c)))

    if(y1>y2):
        return round(-A,2)
        
    return round(A,2)

画延长线

def Extend_line(x1, y1, x2, y2, x, y, flag):
    if flag == 1:
        if y1 == y2:
            return 0, y1, x, y2
        else:
            k = (y2 - y1) / (x2 - x1)
            b = (x1*y2-x2*y1)/(x1-x2)
            x3 = 0
            y3 = b
            x4 = x
            y4 = int(k * x4+b)
        return x3, y3, x4, y4
    else:
        if x1 == x2:
            return x1, 0, x2, y
        else:
            k = (y2 - y1) / (x2 - x1)
            b = (x1 * y2 - x2 * y1) / (x1 - x2)
            y3 = 0
            x3 = int(-1*b/k)
            y4 = y
            x4 = int((y4-b)/k)
            return x3, y3, x4, y4

保存视频

	#
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    fps = cap.get(cv2.CAP_PROP_FPS)
    size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    out = cv2.VideoWriter('outVideo.mp4', fourcc, fps, size)

下载地址

CSDN下载
Q 919825501

你可能感兴趣的:(Python,树莓派,opencv)