Python PIL无法识别io.BytesIO对象的图像文件

Python PIL无法识别io.BytesIO对象的图像文件,python,pillow,bytesio,Python,Pillow,Bytesio,我正在使用PIL的枕叉,并不断收到错误信息 OSError:无法识别图像文件 尝试打开图像时。我在Python3.4中使用virtualenv,没有安装PIL 我试图在其他人遇到同样问题的基础上找到解决方案,但是,这些解决方案对我不起作用。这是我的密码: from PIL import Image import io # This portion is part of my test code byteImg = Image.open("some/location/to/a/file/in/m

我正在使用PIL的枕叉,并不断收到错误信息

OSError:无法识别图像文件

尝试打开图像时。我在Python3.4中使用virtualenv,没有安装PIL

我试图在其他人遇到同样问题的基础上找到解决方案,但是,这些解决方案对我不起作用。这是我的密码:

from PIL import Image
import io

# This portion is part of my test code
byteImg = Image.open("some/location/to/a/file/in/my/directories.png").tobytes()

# Non test code
dataBytesIO = io.BytesIO(byteImg)
Image.open(dataBytesIO) # <- Error here
作为解决方案不起作用(尝试过了),因为我不是通过流保存图像,我只是用数据实例化BytesIO,因此(如果我没记错的话)seek应该已经是0了。

(这个解决方案是作者自己提出的。我刚把它移到这里。)

解决方案:

# This portion is part of my test code
byteImgIO = io.BytesIO()
byteImg = Image.open("some/location/to/a/file/in/my/directories.png")
byteImg.save(byteImgIO, "PNG")
byteImgIO.seek(0)
byteImg = byteImgIO.read()


# Non test code
dataBytesIO = io.BytesIO(byteImg)
Image.open(dataBytesIO)

问题在于
Image.tobytes()
返回字节对象的方式。它似乎是无效数据,“编码”不能是除原始数据以外的任何数据,因为几乎每个字节都以
\xff\
的格式出现,因此它似乎仍然输出错误的数据。但是,通过BytesIO保存字节,并使用
.read()
函数读取整个图像,可以获得正确的字节,以便在以后需要时实际使用。

在某些情况下,处理原始图像文件(如CR2)时也会发生相同的错误。例如:

当您尝试运行时:

byteImg = Image.open("RAW_CANON_G10.CR2")
您将得到以下错误:

OSError: cannot identify image file 'RAW_CANON_G10.CR2'
因此,您需要首先使用rawkit转换图像,下面是一个示例:

from io import BytesIO
from PIL import Image, ImageFile
import numpy
from rawkit import raw
def convert_cr2_to_jpg(raw_image):
    raw_image_process = raw.Raw(raw_image)
    buffered_image = numpy.array(raw_image_process.to_buffer())
    if raw_image_process.metadata.orientation == 0:
        jpg_image_height = raw_image_process.metadata.height
        jpg_image_width = raw_image_process.metadata.width
    else:
        jpg_image_height = raw_image_process.metadata.width
        jpg_image_width = raw_image_process.metadata.height
    jpg_image = Image.frombytes('RGB', (jpg_image_width, jpg_image_height), buffered_image)
    return jpg_image

byteImg = convert_cr2_to_jpg("RAW_CANON_G10.CR2")

如果在GitHub()上的mateusz michalik读取Dicom文件时,问题可能是由Dicom压缩引起的,则代码贷记。 确保gdcm和pydicom都已安装

GDCM通常是更难安装的。轻松安装的最新方法是

conda install -U conda-forge gdcm
image=image.open(io.BytesIO(解码)) #文件“C:\Users\14088\anaconda3\envs\tensorflow\lib\site packages\PIL\Image.py”,第2968行,处于打开状态 #“无法识别图像文件%r”%(如果文件名为,则为文件名) #PIL.UnidentifiedImageError:无法识别图像文件

=== 我固定为工作: message=request.get_json(force=True)

encoded=message['image']
# https://stackoverflow.com/questions/26070547/decoding-base64-from-post-to-use-in-pil
#image_data=re.sub(“^data:image/+;base64”,“消息['image']))
image_data=re.sub(“^data:image/+;base64”,“已编码”)
#删除额外的“data:image/…'base64”非常重要
#如果未删除“data:image/…'base64”,则以下行将生成错误消息:
#文件“C:\Work\SVU\950\u SVU\u DL\u TF\sec07\u TF\u Flask06\u 09\32\u KerasFlask06\u VisualD3\32\u predict\u app.py”,预测中第69行
#image=image.open(io.BytesIO(解码))
#文件“C:\Users\14088\anaconda3\envs\tensorflow\lib\site packages\PIL\Image.py”,第2968行,处于打开状态
#“无法识别图像文件%r”%(如果文件名为,则为文件名)
#PIL.UnidentifiedImageError:无法识别图像文件
#image=image.open(BytesIO(base64.b64解码(image_数据)))
decoded=base64.b64解码(图像数据)
image=image.open(io.BytesIO(解码))
#返回json.dumps({'result':'success'}),200,{'ContentType':'application/json'}
#打印('@app.route=>image:')
#打印()
已处理的_图像=预处理_图像(图像,目标_大小=(224224))
prediction=model.predict(已处理的图像).tolist()
#打印('预测:',预测)
答复={
“预测”:{
“狗”:预测[0][0],
“cat”:预测[0][1]
}
}
打印('响应:',响应)
返回jsonify(响应)

我建议将解决方案从帖子中移到自己的答案中。只是为了格式化sake@FracturedRetina我同意。请将答案移动到一个separe帖子,这样社区就可以对它进行投票,这样你就可以赢得声誉,Elan M。我无意中加载了PDF而不是PNG。
conda install -U conda-forge gdcm
encoded = message['image']
# https://stackoverflow.com/questions/26070547/decoding-base64-from-post-to-use-in-pil
#image_data = re.sub('^data:image/.+;base64,', '', message['image'])
image_data = re.sub('^data:image/.+;base64,', '', encoded)
# Remove extra "data:image/...'base64" is Very important
# If "data:image/...'base64" is not remove, the following line generate an error message: 
# File "C:\Work\SVU\950_SVU_DL_TF\sec07_TF_Flask06_09\32_KerasFlask06_VisualD3\32_predict_app.py", line 69, in predict
# image = Image.open(io.BytesIO(decoded))
# File "C:\Users\14088\anaconda3\envs\tensorflow\lib\site-packages\PIL\Image.py", line 2968, in open
# "cannot identify image file %r" % (filename if filename else fp)
# PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x000002B733BB11C8>
# image = Image.open(BytesIO(base64.b64decode(image_data)))
decoded = base64.b64decode(image_data)
image = Image.open(io.BytesIO(decoded))
# return json.dumps({'result': 'success'}), 200, {'ContentType': 'application/json'}
#print('@app.route => image:')
#print()
processed_image = preprocess_image(image, target_size=(224, 224))

prediction = model.predict(processed_image).tolist()
#print('prediction:', prediction)
response = {
    'prediction': {
        'dog': prediction[0][0],
        'cat': prediction[0][1]
    }
}
print('response:', response)
return jsonify(response)