如何使用Python和OpenCV在图像中检测水平线并获取其y坐标?

4

我正在使用查找轮廓方法,然后使用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()

以下是我得到的输出图像

我原本希望它能够检测图像中的每一个黑色条纹,但它只检测了最底部的第一行。


你也可以考虑使用Houghlines - OpenCV有一个函数可以实现 - 类似于:cv2.Houghlines。Scipy也有一个实现。 - chase
1个回答

7

这是你可能一直在寻找的修改后的代码。我保留了大部分你的代码,并且使用了详细的语言,希望这个版本可以帮助你理解而无需进一步解释。

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

  • cnts[0] in your code refers only to first contour. I have introduced a parameter contnumber which you may have to loop over. My current code only executes for contour number 4
  • You may not have detected the lines as foreground, but the white areas, this is why I negated the images (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()
    
希望这能帮到您。

你能指导我如何使用openCV获取阴影方向吗?我已经尝试并得到了以下结果。[图像轮廓](http://i.imgur.com/hpQg8Ui.png)和[图像水平线](http://i.imgur.com/XqriyCV.png)我想检测相同图像的阴影方向和阴影线。 - Neel Kadia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接