python TypeError: 'NoneType' 对象没有属性 '__getitem__' [英] python TypeError: 'NoneType' object has no attribute '__getitem__'

查看:119
本文介绍了python TypeError: 'NoneType' 对象没有属性 '__getitem__'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这次我正在尝试 Solem 的博客中的另一个例子.它是一个使用霍夫变换检测图像中的直线和圆的模块.这是代码(houghlines.py):

This time I am trying another example from Solem's blog. It's a module that detects lines and circles in an image by using the Hough transform. Here is the code (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)

当我在 python 中执行文件时:

When I execute the file in python by:

execfile('houghlines.py')

出现以下错误:

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

你们知道如何解决它吗?
提前致谢.

Do you guys have any idea how to solve it?
Thanks in advance.

推荐答案

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

It is because of the threshold value in lines = cv2.HoughLines(edges, 2, np.pi/90, 40)[0], the last argument you passed. It indicates minimum length to be considered as a line, 40 pixels in your case. Try decreasing it.

这篇关于python TypeError: 'NoneType' 对象没有属性 '__getitem__'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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