我想对棋盘图像执行概率霍夫线变换,但遇到错误。关于此错误的怪异现象是,仅当我为OpenCV函数HoughLinesP()的参数指定关键字时才会发生。
首先,检查我的代码行和收到的错误消息:
#-*- coding:utf-8-*-
import matplotlib.pyplot as plt
import cv2
from skimage import io
import numpy as np
# Load image file
fpath = 'D:/Users/'
image = io.imread(fpath + 'checkerboard.JPG')
image_original = image.copy()
edges = cv2.Canny(image, 50, 200, apertureSize=3)
gray = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
minLineLength = 100
maxLineGap = 0
# Perform the probabilistic Hough transform
lines = cv2.HoughLinesP(image=edges, rho=1, theta=np.pi/180, threshold=100, minLineLength=minLineLength, maxLineGap=maxLineGap)
for i in range(len(lines)):
for x1, y1, x2, y2 in lines[i]:
cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 3)
plt.figure(figsize=(10, 5), dpi=150)
plt.subplot(1, 2, 1)
plt.imshow(image_original, cmap='gray', vmin=0, vmax=255)
plt.subplot(1, 2, 2)
plt.imshow(image, cmap='gray', vmin=0, vmax=255)
plt.show()
Traceback (most recent call last):
File "D:\Users\sihohan\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-2-c2c4eb0ac4e8>", line 1, in <module>
runfile('D:/Users/2_prob_hough.py', wdir='D:/Users')
File "C:\Program Files\JetBrains\PyCharm 2019.2.2\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "C:\Program Files\JetBrains\PyCharm 2019.2.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "D:/Users/2_prob_hough.py", line 20, in <module>
for i in range(len(lines)):
TypeError: object of type 'NoneType' has no len()
如上所述,如果我不为HoughLinesP()的参数指定关键字,则我的代码可以正常工作:
# Perform the probabilistic Hough transform
lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength, maxLineGap)
这可能是什么原因?
谢谢。
(以下是maxLineGap = 0、10和20的输出图像)
checkerboard_maxLineGap_0
checkerboard_maxLineGap_10
checkerboard_maxLineGap_20
最佳答案
OpenCV houghLinesP parameters指出cv2.HoughLinesP
包含冗余参数lines
。所以你的minLineLength在
# Perform the probabilistic Hough transform
lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength, maxLineGap)
用作
lines
参数。因此,将maxLineGap
设置为零,就可以将minLineLength
用作ojit_code来产生更多结果。