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

在使用OpenCV进行车道线检测时,通过createTrackbar和getTrackbarPos设置Canny和Hough算子阈值,发现图像处理存在叠加效果,导致无法恢复原始状态。解决方法是在处理前复制原始图像,每次操作都在复制的图像上进行,从而实现可逆的阈值调整。通过添加`img_crop.copy()`来创建新图像,成功解决了问题。
摘要由CSDN通过智能技术生成

今天使用 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)

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荣仔!最靓的仔!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值