[英]How to open an image with cv2 in a python module
So this is the code I have and it works fine, as it should, it displays an image until you press a button:所以这是我拥有的代码并且它工作正常,它应该显示一个图像,直到你按下一个按钮:
import cv2
def open_img():
template = cv2.imread('templates\\img_test.jpg')
cv2.imshow('template', template)
cv2.waitKey(0)
cv2.destroyAllWindows()
open_img()
This script is called 'img_mod' and is stored in 'detection'.该脚本称为“img_mod”并存储在“检测”中。 Now I would like to call this function from another script:
现在我想从另一个脚本调用这个函数:
from detection import img_mod
img_mod.open_img()
this creates the following error:这会产生以下错误:
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'
To me it seems like a cv2 specifit error.对我来说,这似乎是一个 cv2 特定错误。 But I have no idea, why this doesn't work.
但我不知道,为什么这不起作用。 Any help would be appreciated.
任何帮助,将不胜感激。
The error message is related to an assertion failure: size.width>0 && size.height>0
错误消息与断言失败有关:
size.width>0 && size.height>0
It means the function is not carrying out the action because some conditions are not met.这意味着由于某些条件不满足,函数没有执行操作。
It is likely your image templates\\\\img_test.jpg
is invalid or does not exist.您的图像
templates\\\\img_test.jpg
可能无效或不存在。 Try, for example, give a full path to a valid image file.例如,尝试提供有效图像文件的完整路径。
This is what happens when imread()
fails to read an image and returns None
, and the None
gets passed along to imshow()
.这就是
imread()
无法读取图像并返回None
时发生的情况,并且None
被传递给imshow()
。
There are a few possibilities.有几种可能性。 The mostly likely is that you're not in the directory you think you are, and there's not a
templates
folder in the current directory.最有可能的是您不在您认为的目录中,并且当前目录中没有
templates
文件夹。 You can deal with that by passing a full path to img_test.jpg
.您可以通过将完整路径传递给
img_test.jpg
来解决img_test.jpg
。
Your image is in你的图片在
D:\Projects\BJ\detection\templates\img_test.jpg
but now you're trying to load it from但现在你正试图从
D:\Projects\BJ\templates\img_test.jpg
because you run a different Python file.因为你运行了一个不同的 Python 文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.