[英]I can't read image with open-cv from bytes
Hey guys help me please.嘿伙计们请帮助我。
I have flask rest api that receive multipart/form-data as image and I want to use opencv to process it .我有flask rest api,它接收multipart/form-data 作为图像,我想使用opencv 来处理它。
My problem is I can't read image with cv2.imdecode.我的问题是我无法使用 cv2.imdecode 读取图像。
This function is return none so what's wrong.这个函数是 return none 所以有什么问题。
imgFile = request.files['image']
imgBuffer = imgFile.read() # <class 'bytes'>
#b'\xc3\xbf\xc3\x98\xc3\xbf\xc3\xa0\x00\x10'
img = np.frombuffer(imgBuffer, dtype='uint8') # <class 'numpy.ndarray'>
#[195 191 195 152 195 191 195 160 0 16]
img = cv2.imdecode(img, cv2.IMREAD_COLOR) # <class 'NoneType'>
cv2.imdecode()
expects to decode a JPEG-encoded or PNG-encoded image. cv2.imdecode()
期望解码 JPEG 编码或 PNG 编码的图像。 Such an image would start with:这样的图像将从以下内容开始:
ff d8 ff
or ff d8 ff
或89 50 4e 47 0d 0a 1a 0a
89 50 4e 47 0d 0a 1a 0a
Yours does not.你的没有。 So it is probably just the raw, unencoded pixels and you probably just need:
所以它可能只是原始的、未编码的像素,你可能只需要:
img = np.array(imgBuffer).reshape((height,width))
Another clue is the size of your bytes
buffer.另一个线索是
bytes
缓冲区的大小。 If its size matches the height x width of your greyscale image (or 3x that if colour) it means your image is just pixel data, whereas you would expect a JPEG/PNG encoded image to be much smaller because it's compressed.如果它的大小与您的灰度图像的高度 x 宽度匹配(或 3x,如果是彩色),则意味着您的图像只是像素数据,而您希望 JPEG/PNG 编码的图像要小得多,因为它是压缩的。
Try making the following changes to your code.尝试对您的代码进行以下更改。
imgFile = request.files['image']
imgBuffer = imgFile.read() # <class 'bytes'>
#b'\xc3\xbf\xc3\x98\xc3\xbf\xc3\xa0\x00\x10'
my_img = cv2.imread(imgFile, 0)
my_img.imshow(my_img)
#stream = io.StringIO(imgBuffer.decode("UTF8"), newline=None)
#img = np.frombuffer(stream, dtype='uint8') # <class 'numpy.ndarray'>
#[195 191 195 152 195 191 195 160 0 16]
#img = cv2.imdecode(img, cv2.IMREAD_COLOR) # <class 'NoneType'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.