今天使用 OpenCV 进行车道线检测时,为了快速找到合适的 Canny 算子高、低阈值以及 Sobel 算子?threshold 阈值,决定采用?OpenCV 中的?createTrackbar 和 getTrackbarPos 方法。结果一个问题的出现使我措手不及:调整阈值画车道线只能在前一时刻图像基础上变化,也就是只能使得识别出的车道线变多,不能变少,更不能恢复到没有识别出车道线的那张图像。  
 就像这样,变多的时候好好的,回不去了!!? :
    
 ?下面说一下解决办法:  
  
这是最开始写的关键代码 :  
imgpath = "图片路径"
img = cv.imread(imgpath)
img_crop = img[500:, :]
img_blur = cv.GaussianBlur(img_crop, (11, 11), 0)
img_sobel = my_sobel(img_blur)
def my_hough():
    min = cv.getTrackbarPos('min', 'hough image')
    max = cv.getTrackbarPos('max', 'hough image')
    threshold = cv.getTrackbarPos('hough', 'hough image')
    img_canny = cv.Canny(img_sobel, min, max)
    lines = cv.HoughLines(img_canny, 1, np.pi / 180, threshold)
    for line in lines:
        rho, theta = line[0]
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a * rho
        y0 = b * rho
        x1 = int(x0 + 1000 * (-b))
        y1 = int(y0 + 1000 * (a))
        x2 = int(x0 - 1000 * (-b))
        y2 = int(y0 - 1000 * (a))
        cv.line(img_crop, (x1, y1), (x2, y2), (0, 0, 255), 2)
    cv.imshow('hough image', img_crop)  
这是因为滑动条滑动导致阈值变换,处理的图片一直都是在上一时刻停留那个位置的阈值处理出的图片基础上运行的,简单来讲,就是一种叠加作用,然后当变换阈值使得识别出车道线变少,也就看不出来了。  
解决办法是创建一个新图像,这个图像用于获得处理前的图像,相当于是复制处理前的那个图像,用的是关于图像复制的?.copy() 方法。  
按照此思路变换后的关键代码是:  
imgpath = "图片路径"
img = cv.imread(imgpath)
img_crop = img[500:, :]
img_blur = cv.GaussianBlur(img_crop, (11, 11), 0)
img_sobel = my_sobel(img_blur)
def my_hough():
    min = cv.getTrackbarPos('min', 'hough image')
    max = cv.getTrackbarPos('max', 'hough image')
    threshold = cv.getTrackbarPos('hough', 'hough image')
    dst = img_crop.copy()                 # 加这一句
    img_canny = cv.Canny(img_sobel, min, max)
    lines = cv.HoughLines(img_canny, 1, np.pi / 180, threshold)
    for line in lines:
        rho, theta = line[0]
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a * rho
        y0 = b * rho
        x1 = int(x0 + 1000 * (-b))
        y1 = int(y0 + 1000 * (a))
        x2 = int(x0 - 1000 * (-b))
        y2 = int(y0 - 1000 * (a))
        dst = cv.line(dst, (x1, y1), (x2, y2), (0, 0, 255), 2)
    cv.imshow('hough image', dst)  
这就达到了想要的结果(可复原):  
 ?  
?  
? 
                
        
    
 
 |