在我使用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)
3条答案
按热度按时间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:Rather it returns None:
(returns
True
). Your code would then fail onimg.shape
line. So you could either check that the file path is correct before supplying to cv2.imread:or you could
assert img is not None
after doing theimread
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 errorTypeError: '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 aNone
onimread
.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.
xtfmy6hx2#
You can't expect
cv2.imshow()
to work insideflask
orapache
.apache
starts it generally switches user to a user and group calledwww
so it doesn't have the same environment (PATH
,HOME
DISPLAY
and other variables) as when you run something from your Terminal sitting in front of your screen.www
user even have the same Python modules installed if you added them to your own user.tty
where it could applycv2.waitKey()
to tell if you had pressed a key - to quit, for example.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 itsshape
anddtype
afterwards.sqyvllje3#
我也遇到了同样的问题。解决办法是“清理”路径。
我在文件路径中使用了空格和“+”,通过将它们替换为“_”,cv2.imread()现在可以正确读取这些文件。