如何使用python和opencv检测图像中的水平线并获取其y坐标? [英] How to detect horizontal lines in an image and obtain its y-coordinates using python and opencv?

查看:986
本文介绍了如何使用python和opencv检测图像中的水平线并获取其y坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用寻找轮廓"方法,然后通过使用fitline函数逼近一条线. 下面是代码:

I am using the find contours method and then approximating a line by using fitline function. below is the code:

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()

以下是我作为输出获得的图像

我希望它能够检测到图像中的每个黑色条纹,而只能检测到底部的第一行

I was expecting it to detect each of the black stripes in the image whereas it is detecting only the first line from the bottom

推荐答案

此修改后的代码可能就是您想要的.我已经离开了您的大部分行,并且它很冗长,但这可以帮助您理解它而无需进一步解释.

This modified code is what you may have been looking for. I have left most of your lines and it is pretty verbose, but this might help you understand it without further explanation.

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

I think that you got trapped in two different of problems:

    您代码中的
  • cnts [0]仅指第一个轮廓.我介绍了一个参数contnumber,您可能需要循环遍历.我当前的代码仅在轮廓编号4上执行
  • 您可能没有将线条检测为前景,但是白色区域,这就是为什么我对图像取反(阈值=(255阈值))的原因

  • 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()

希望有帮助.

这篇关于如何使用python和opencv检测图像中的水平线并获取其y坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆