2013-04-22 239 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個像素。嘗試減少它。

相關問題