[英]Error when drawing lines in OpenCV Python
So what I am trying to do is use hough transformations to find lines on an image and then draw the lines into the image. 所以我想做的是使用霍夫变换在图像上找到线,然后将线绘制到图像中。
But I am getting an error that says: 但我收到一条错误消息:
Traceback (most recent call last):
File "houghLines.py", line 31, in <module>
main() File "houghLines.py", line 13, in main
a = hough(image)
File "houghLines.py", line 29, in hough
(0,0,255))
TypeError: only length-1 arrays can be converted to Python scalars
This is my code: 这是我的代码:
import cv2
import os
import math
def main():
directory = os.path.dirname(__file__)
picLoc = os.path.join(directory, "../video-image/1m50s.png")
image = cv2.imread(picLoc)
print "sending image to houghLines.py"
a = hough(image)
cv2.imshow("", a)
cv2.waitKey(0)
cv2.destroyAllChildren()
def hough(image):
canny = cv2.Canny(image, 50, 200)
color_image = cv2.cvtColor(canny, cv2.COLOR_GRAY2BGR)
houghLines = cv2.HoughLinesP(canny, 1, math.pi/180, 50)
for x in range(len(houghLines)):
print x
pt1 = (houghLines[x][0], houghLines[x][1])
pt2 = (houghLines[x][2], houghLines[x][3])
cv2.line(color_image, pt1, pt2, (0,0,255), 3)
return color_image
main()
This problem occurs because cv2.line()
expects pt1
and pt2
to be tuples consisting of only a single element for each x
and y
coordinate. 发生此问题的原因是cv2.line()
期望pt1
和pt2
是元组,每个元组的x
和y
坐标只包含一个元素。 If you print pt1
in your example, you will quickly see that this is not the case. 如果在示例中print pt1
,您将很快发现情况并非如此。
cv2.HoughLinesP()
returns a numpy array with only one element. cv2.HoughLinesP()
返回仅包含一个元素的numpy数组。 This element contains lists of four points which are the start and end points of your lines. 该元素包含四个点的列表,它们是行的起点和终点。 Knowing this, a correct implementation follows: 知道这一点,正确的实现如下:
for line in houghLines[0]:
pt1 = tuple(line[:2])
print pt1
pt2 = tuple(line[-2:])
cv2.line(color_image, pt1, pt2, (0,0,255), 3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.