我正在尝试将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$

最佳答案

当我只运行代码时,它也会抱怨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'

python - 参数 &#39;src&#39;的预期cv::UMat-LMLPHP

是的,您应该检查图像是否存在并成功加载!

请注意,另一种不好的做法是:您的变量名canny与您的函数名canny() 相同。因此,当您调用canny = canny(img)时,函数canny()对象将被变量canny代替。如果您下次调用canny(),它将失败:TypeError: 'numpy.ndarray' object is not callable
python - 参数 &#39;src&#39;的预期cv::UMat-LMLPHP

然后使用其他名称。

>>> 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

关于python - 参数 'src'的预期cv::UMat,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55191842/

10-11 07:37