gpt4 book ai didi

python - 如何使用 python 和 opencv 检测图像中的水平线并获取其 y 坐标?

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:15 24 4
gpt4 key购买 nike

我正在使用查找轮廓方法,然后使用 fitline 函数近似一条线。下面是代码:

img = cv2.imread('lines.jpg')
imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,dst = cv2.threshold(imgray,127,255,0)
im2,cnts, hierarchy =cv2.findContours(dst,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
rows,cols = img.shape[:2]
[vx,vy,x,y] = cv2.fitLine(cnts[0], cv2.DIST_L2,0,0.01,0.01)
lefty = int((-x*vy/vx) + y)
righty = int(((cols-x)*vy/vx)+y)
cv2.line(img,(cols-1,righty),(0,lefty),(0,255,0),2)
print img.shape[:2]
cv2.imshow('image1',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Following is the image I am getting as output

我期待它检测图像中的每个黑色条纹,但它只检测从底部开始的第一行

最佳答案

这段修改后的代码可能正是您一直在寻找的。我留下了你的大部分台词,它非常冗长,但这可能有助于你理解它而无需进一步解释。

我认为您陷入了两个不同的问题:

  • cnts[0] 在您的代码中仅指第一个轮廓。我引入了一个参数 contnumber,您可能需要循环它。我当前的代码只针对 4 号轮廓执行
  • 您可能没有检测到线条作为前景,但是白色区域,这就是我否定图像的原因 (thresh = (255-thresh))

    import numpy as np
    import cv2

    im = cv2.imread('lines.jpg')
    rows,cols = im.shape[:2]
    imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    ret,thresh = cv2.threshold(imgray,125,255,0)
    thresh = (255-thresh)
    thresh2=thresh.copy()
    im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

    cv2.imshow('image1',im)
    cv2.imshow('image3',thresh2)
    #cv2.drawContours(im, contours, -1, (0,255,0), 3) #draw all contours
    contnumber=4
    cv2.drawContours(im, contours, contnumber, (0,255,0), 3) #draw only contour contnumber
    cv2.imshow('contours', im)

    [vx,vy,x,y] = cv2.fitLine(contours[contnumber], cv2.DIST_L2,0,0.01,0.01)
    lefty = int((-x*vy/vx) + y)
    righty = int(((cols-x)*vy/vx)+y)
    cv2.line(im,(cols-1,righty),(0,lefty),(0,255,255),2)

    cv2.imshow('result', im)

    cv2.waitKey(0)
    cv2.destroyAllWindows()

希望对您有所帮助。

关于python - 如何使用 python 和 opencv 检测图像中的水平线并获取其 y 坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36210615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com