[英]Using OpenCV imread and imwrite with Python Path objects gives SystemError: <built-in function imread> returned NULL without setting an error
Passing a Python Path object to OpenCV's imread
or imwrite
results in an undefined error:将 Python 路径 object 传递给 OpenCV 的imread
或imwrite
会导致未定义的错误:
from pathlib import Path
import cv2
img_path = Path("test.png")
img = cv2.imread(img_path)
Results in:结果是:
Traceback (most recent call last):
File ".\secondary_image_generation.py", line 36, in <module>
img = cv2.imread(img_path)
SystemError: <built-in function imread> returned NULL without setting an error
Why is this and how can I avoid it?为什么会这样,我该如何避免?
OpenCV library sources are written in C++ and the Python bindings are primarily auto-generated and don't do much more than wrap the C++ functions. OpenCV 库源代码是在 C++ 中编写的,而 Python 绑定主要是自动生成的,除了包装 C++ 函数外没有做更多的事情。 The C++ functions expect string type filenames so that is what you have to provide to the Python functions as well. C++ 函数需要字符串类型的文件名,因此这也是您必须提供给 Python 函数的内容。
Doing the following resolves the problem by resolving the full path and converting it to a string:执行以下操作可通过解析完整路径并将其转换为字符串来解决问题:
img_path = Path("test.png")
img = cv2.imread(str(img_path.resolve()))
This is still an open feature request for the current version of OpenCV.这仍然是当前版本 OpenCV 的开放功能请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.