大家好,请帮帮我。
我有 Flask Rest API,它接收多部分/表单数据作为图像,我想使用 opencv 来处理它。
我的问题是我无法使用 cv2.imdecode 读取图像。
这个函数不返回任何内容,所以出了什么问题。
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()
期望解码 JPEG 编码或 PNG 编码的图像。这样的图像将以:
- JPEG 签名
ff d8 ff
或 - PNG 签名
89 50 4e 47 0d 0a 1a 0a
你的没有。所以它可能只是原始的、未编码的像素,您可能只需要:
img = np.array(imgBuffer).reshape((height,width))
另一个线索是您的字节
缓冲区的大小。如果其大小与灰度图像的高度 x 宽度相匹配(如果是彩色图像,则为 3 倍),则意味着您的图像只是像素数据,而您会期望 JPEG/PNG 编码的图像会小得多,因为它经过了压缩。
关于python - 我无法使用 opencv 从字节读取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68110032/