ubuntu CV2.imread()Python图像未加载且未显示错误

htrmnn0y  于 2022-12-11  发布在  Python
关注(0)|答案(3)|浏览(252)

在我使用Apache 2在Ubuntu上托管的python flask程序中,我写的程序通常能够使用imread来压缩和处理图像。2现在的代码是不能访问图像,即使文件路径是正确的,它是一个现有的文件,不会返回任何错误信息。这似乎发生在任何类型的图像不依赖于文件的类型和代码有时返回一个none类型是不可下标的,如果这是有关这个问题。提前感谢您的帮助!代码:

img = cv2.imread(file_path)
height, width, _ = img.shape
roi = img[0: height, 0: width]
_, compressedimage = cv2.imencode(".jpg", roi, [1, 90])
file_bytes = io.BytesIO(compressedimage)
5q4ezhmt

5q4ezhmt1#

code sometimes returns a none type
It looks to me like the file path you are supplying might be incorrect. I am saying this because cv2.imread does not throw an error for a non-existent file path:

img = cv2.imread("/non/existent/image.jpeg")

Rather it returns None:

img is None

(returns True ). Your code would then fail on img.shape line. So you could either check that the file path is correct before supplying to cv2.imread:

assert os.path.isfile(file_path)

or you could assert img is not None after doing the imread and before going further.
EDIT:
I see that you are claiming that you have checked that the file path is correct and the file exists. But then you are yourself saying
the code sometimes returns a none type is not subscript able
This is because of img[0: height, 0: width] where you are trying to index/subscript None.
You can check that if you type None[0] , you get the same error TypeError: 'NoneType' object is not subscriptable . So I still feel that the image path is not correct or it is not a valid image file (has some other extension than the ones listed here). In both cases you get a None on imread .
Since the code snippet you've provided is a part of a larger app, the problem could be somewhere else such that sometime the file path is valid and sometime it is not? I am only guessing at this point.

xtfmy6hx

xtfmy6hx2#

You can't expect cv2.imshow() to work inside flask or apache .

  • When apache starts it generally switches user to a user and group called www so it doesn't have the same environment ( PATH , HOMEDISPLAY and other variables) as when you run something from your Terminal sitting in front of your screen.
  • Nor does the www user even have the same Python modules installed if you added them to your own user.
  • It also doesn't have a tty where it could apply cv2.waitKey() to tell if you had pressed a key - to quit, for example.
  • It also doesn't have permission to draw on your screen - or even know who you are or which one of the potentially many attached screens/sessions you are sitting at.

Maybe consider looking at the logging module to debug/monitor your script and log the image path and its file size prior to cv2.imread() and its shape and dtype afterwards.

sqyvllje

sqyvllje3#

我也遇到了同样的问题。解决办法是“清理”路径。
我在文件路径中使用了空格和“+”,通过将它们替换为“_”,cv2.imread()现在可以正确读取这些文件。

相关问题