前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >解决OpenCV滑动条变换轨迹而图像变化后不能归位的问题

解决OpenCV滑动条变换轨迹而图像变化后不能归位的问题

作者头像
荣仔_最靓的仔
发布2021-09-07 17:13:51
6810
发布2021-09-07 17:13:51
举报

今天使用 OpenCV 进行车道线检测时,为了快速找到合适的 Canny 算子高、低阈值以及 Sobel 算子 threshold 阈值,决定采用 OpenCV 中的 createTrackbar 和 getTrackbarPos 方法。结果一个问题的出现使我措手不及:调整阈值画车道线只能在前一时刻图像基础上变化,也就是只能使得识别出的车道线变多,不能变少,更不能恢复到没有识别出车道线的那张图像。 就像这样,变多的时候好好的,回不去了!!?

下面说一下解决办法:

这是最开始写的关键代码 :

代码语言:javascript
复制
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() 方法。

按照此思路变换后的关键代码是:

代码语言:javascript
复制
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)

这就达到了想要的结果(可复原):

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-07-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档