省流:opencv python和numpy版本不匹配,numpy 2.0版本容易出问题,应该降级为1.*的版本,我这里安装的是1.26.4。
github也有遇到问题的:Cannot Import cv2 when using python3 with numpy 2.0。
详细情景:用opencv操作图片时,报错:
Overload resolution failed:
- src2 is not a numpy array, neither a scalar
- Expected Ptrcv::UMat for argument 'src2'
在网上找的解决方案有提到可能是因为图片需要的是RGB,但是传入了RBG(可能记反了),但是这个方法并没有解决。
我根据copilot的提示debug:
if img is None:
print("Failed to load image")
else:
print("Image loaded successfully")
print("is instance of img: ", isinstance(img, np.ndarray))
输出结果是:
Image loaded successfully
is instance of img: False
这就非常奇怪了,照理说opencv读进来的图片就是numpy格式的,而且debug时也显示了img变量就是numpyt的ndarray。
同时,我想要确认是不是数据类型的问题,就print出img的dtype,结果报错:
packages/numpy/core/numerictypes.py", line 417, in issubdtype arg1 = dtype(arg1).type TypeError。
但是,debug中显示了一个报错提示了我问题的方向,让我意识到了是版本问题,最后我检索到了一篇opencv的github中的issue,链接为:Cannot Import cv2 when using python3 with numpy 2.0 · Issue #25772 · opencv/opencv · GitHub
我通过conda list,查看到自己的版本跟链接中的描述一致:
numpy 2.0.0
opencv-python 4.10.0.84
使用他的解决办法,成功解决问题:
pip3 install --upgrade numpy==1.26.4
如果感兴趣,关于numpy2.0版本的讨论如下链接,大体意思就是2.0的各种接口调整较大,与先前版本的适配性不太好: