2013-04-22 198 views
3

这次我试着从Solem's blog的另一个例子。它是一个通过使用霍夫变换来检测图像中的线和圆的模块。 下面是代码(houghlines.py):python TypeError:'NoneType'对象没有属性'__getitem__'

execfile('houghlines.py') 

以下错误出现:

import numpy as np 
import cv2 

""" 
Script using OpenCV's Hough transforms for reading images of 
simple dials. 
""" 

# load grayscale image 
im = cv2.imread("house2.jpg") 
gray_im = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) 

# create version to draw on and blurred version 
draw_im = cv2.cvtColor(gray_im, cv2.COLOR_GRAY2BGR) 
blur = cv2.GaussianBlur(gray_im, (0,0), 5) 

m,n = gray_im.shape 

# Hough transform for circles 
circles = cv2.HoughCircles(gray_im, cv2.cv.CV_HOUGH_GRADIENT, 2, 10, np.array([]), 20, 60, m/10)[0] 

# Hough transform for lines (regular and probabilistic) 
edges = cv2.Canny(blur, 20, 60) 
lines = cv2.HoughLines(edges, 2, np.pi/90, 40)[0] 
plines = cv2.HoughLinesP(edges, 1, np.pi/180, 20, np.array([]), 10)[0] 

# draw 
for c in circles[:3]: 
# green for circles (only draw the 3 strongest) 
cv2.circle(draw_im, (c[0],c[1]), c[2], (0,255,0), 2) 

for (rho, theta) in lines[:5]: 
# blue for infinite lines (only draw the 5 strongest) 
x0 = np.cos(theta)*rho 
y0 = np.sin(theta)*rho 
pt1 = (int(x0 + (m+n)*(-np.sin(theta))), int(y0 + (m+n)*np.cos(theta))) 
pt2 = (int(x0 - (m+n)*(-np.sin(theta))), int(y0 - (m+n)*np.cos(theta))) 
cv2.line(draw_im, pt1, pt2, (255,0,0), 2) 

for l in plines: 
# red for line segments 
cv2.line(draw_im, (l[0],l[1]), (l[2],l[3]), (0,0,255), 2) 

cv2.imshow("circles",draw_im) 
cv2.waitKey() 

# save the resulting image 
cv2.imwrite("res.jpg",draw_im) 

当我在蟒蛇执行文件

File "houghlines.py", line 24, in <module> 
    lines = cv2.HoughLines(edges, 2, np.pi/90, 40)[0] 
TypeError: 'NoneType' object has no attribute '__getitem__' 

你们是否有什么想法如何解决它?
在此先感谢。

+0

'Houghlines'函数返回'None'。 – 2013-04-22 09:48:13

+0

@segfolt:是的,但[文档](http://docs.opencv.org/modules/imgproc/doc/feature_detection.html#houghlines)似乎并没有表明这是正常的行为.. – 2013-04-22 09:49:02

+1

嗯 - 什么如果你尝试'cv2.HoughLines(边缘,2,np.pi/90,40,无)',会发生? – 2013-04-22 09:54:58

回答

3

有时HoughLines和HoughLinesP不返回任何值。我认为这意味着“不行”。我真的很惊讶,文档中的例子没有解释它。也许这是一个错误。

在任何情况下,您都可以通过简单的if result != None:停止代码失败,或将其替换为(HoughLinesP(... args ...) or [[]])之类的默认列表。这并不能解决你的线路没有被检测到的事实,但它允许你在这种情况下做一些事情,而不是失败。

+0

我不会说它是一个错误,但只是缺少一个检查语句。我刚刚检查了git仓库中Hough行的'cpp'示例,并且有一个检查。在那里(在C++中)一个线条矢量在堆栈上初始化并传递给Hough线函数。之后,检查是否包含任何内容。我将提交一个问题和补丁。 – rbaleksandar 2016-06-02 09:06:35

0

我也在处理这个错误。当功能cv2.HoughCircles未检测到任何圆圈时,它将返回无。所以,我有两个办法来解决它,如下所示:

  • 使用试/异常包围你的代码块
try: 
    ... 
except Exception as e: 
    print 'There is no circles to be detected!' 
  • 使用的if/else避免操作无对象
if circles is not None: 
    ... 
else: 
    print 'There is no circles to be detected!' 
2

这是因为您通过的最后一个参数lines = cv2.HoughLines(edges, 2, np.pi/90, 40)[0]中的阈值。它表示最小长度被视为一条线,在你的情况下是40个像素。尝试减少它。

相关问题