如何在 python 模块中使用 cv2 打开图像
How to open an image with cv2 in a python module
这是我的代码,它工作正常,它应该会显示图像,直到您按下按钮:
import cv2
def open_img():
template = cv2.imread('templates\img_test.jpg')
cv2.imshow('template', template)
cv2.waitKey(0)
cv2.destroyAllWindows()
open_img()
此脚本名为 'img_mod' 并存储在 'detection' 中。
现在我想从另一个脚本调用这个函数:
from detection import img_mod
img_mod.open_img()
这会产生以下错误:
Traceback (most recent call last):
File "D:/Projects/BJ/Sandbox.py", line 3, in <module>
img_mod.open_img()
File "D:\Projects\BJ\detection\img_mod.py", line 6, in open_img
cv2.imshow('template', template)
cv2.error: OpenCV(3.4.4) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
对我来说,这似乎是一个特定于 cv2 的错误。但我不知道,为什么这不起作用。
任何帮助将不胜感激。
错误消息与断言失败有关:size.width>0 && size.height>0
这意味着函数没有执行操作,因为不满足某些条件。
很可能您的图片 templates\img_test.jpg
无效或不存在。例如,尝试提供有效图像文件的完整路径。
这就是当 imread()
无法读取图像并且 returns None
并且 None
被传递给 imshow()
时发生的情况。
有几种可能性。最有可能的是您不在您认为的目录中,并且当前目录中没有 templates
文件夹。您可以通过将完整路径传递给 img_test.jpg
.
来解决这个问题
您的图片在
D:\Projects\BJ\detection\templates\img_test.jpg
但现在您正尝试从
加载它
D:\Projects\BJ\templates\img_test.jpg
因为您 运行 一个不同的 Python 文件。
这是我的代码,它工作正常,它应该会显示图像,直到您按下按钮:
import cv2
def open_img():
template = cv2.imread('templates\img_test.jpg')
cv2.imshow('template', template)
cv2.waitKey(0)
cv2.destroyAllWindows()
open_img()
此脚本名为 'img_mod' 并存储在 'detection' 中。 现在我想从另一个脚本调用这个函数:
from detection import img_mod
img_mod.open_img()
这会产生以下错误:
Traceback (most recent call last):
File "D:/Projects/BJ/Sandbox.py", line 3, in <module>
img_mod.open_img()
File "D:\Projects\BJ\detection\img_mod.py", line 6, in open_img
cv2.imshow('template', template)
cv2.error: OpenCV(3.4.4) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
对我来说,这似乎是一个特定于 cv2 的错误。但我不知道,为什么这不起作用。 任何帮助将不胜感激。
错误消息与断言失败有关:size.width>0 && size.height>0
这意味着函数没有执行操作,因为不满足某些条件。
很可能您的图片 templates\img_test.jpg
无效或不存在。例如,尝试提供有效图像文件的完整路径。
这就是当 imread()
无法读取图像并且 returns None
并且 None
被传递给 imshow()
时发生的情况。
有几种可能性。最有可能的是您不在您认为的目录中,并且当前目录中没有 templates
文件夹。您可以通过将完整路径传递给 img_test.jpg
.
您的图片在
D:\Projects\BJ\detection\templates\img_test.jpg
但现在您正尝试从
加载它D:\Projects\BJ\templates\img_test.jpg
因为您 运行 一个不同的 Python 文件。