参数'src'应为cv::UMat

2024-04-25 02:00:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将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$

Tags: 函数代码pyimageimportimg错误np
1条回答
网友
1楼 · 发布于 2024-04-25 02:00:40

当我运行代码时,它也会抱怨Expected cv::UMat for argument 'src'因为在我的电脑中没有lane.jpg,所以cv2.imread返回NoneType,并且np.copy返回np.array(None, dtype=object)如果您只是将这样的变量传递给cv2,它就会抱怨Expected cv::UMat for argument 'xxx'

enter image description here

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


注意,另一个不好的做法是:变量名canny与函数名canny()相同。所以当您调用canny = canny(img)时,函数canny()对象被变量canny替换。如果下次调用canny(),它将像这样失败:TypeError: 'numpy.ndarray' object is not callableenter image description here

然后用不同的名字。


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

相关问题 更多 >