我正在尝试在图像上应用canny函数,这是完整的代码,但是仅当我将步骤放在函数中时,它才会显示错误,而将所有代码置于任何函数之外时,则不会显示错误。代码:
import cv2
import numpy as np
def canny(image):
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
canny = cv2.Canny(blur, 50, 150) #sick
return canny
sourceimage = cv2.imread('lane.jpg')
img = np.copy(sourceimage)
canny = canny(img)
cv2.imshow("result", canny)
cv2.waitKey(0)
这是我得到的错误:(python 3.6.8)
kream@KRIMZON:~/Desktop/finding-lanes-linux$ python3 lane.py
Traceback (most recent call last):
File "lane.py", line 12, in <module>
cannyer = canny(img)
File "lane.py", line 5, in canny
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
TypeError: Expected cv::UMat for argument 'src'
kream@KRIMZON:~/Desktop/finding-lanes-linux$
答案 0 :(得分:0)
当我只运行代码时,它也会抱怨Expected cv::UMat for argument 'src'
。 因为我的PC中没有lane.jpg
,所以cv2.imread
返回NoneType
,而np.copy
返回np.array(None, dtype=object)
。 cv2这样的变量,它将抱怨Expected cv::UMat for argument 'xxx'
。
是的,您应该检查图像是否存在并成功加载!
请注意,另一种不好的做法是:变量名称canny
与功能名称canny()
相同。因此,当您调用canny = canny(img)
时,函数canny()
对象将被变量canny
取代。如果您下次呼叫canny()
,它将失败,像这样:TypeError: 'numpy.ndarray' object is not callable
。
然后使用不同的名称。
>>> src = cv2.imread("noexist.png")
>>> img = np.copy(src)
>>>
>>> type(src)
<class 'NoneType'>
>>> cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
cv2.error: OpenCV(4.0.1) d:\build\opencv\opencv-4.0.1\modules\imgproc\src\color.cpp:181: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
>>>
>>> img
array(None, dtype=object)
>>> cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Expected cv::UMat for argument 'src'
>>>
>>> img()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'numpy.ndarray' object is not callable