[英]Scipy: UnicodeDecodeError while loading image file
def image_to_laplacian(filename):
with open(filename, 'r', encoding="latin-1") as f:
s = f.read()
img = sc.misc.imread(f)
image_to_laplacian('images/bw_3x3.png')
Produces: 产生:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte UnicodeDecodeError:'utf-8'编解码器无法解码位置0的字节0x89:无效的起始字节
"images/bw_3x3.png" is a 3x3 image I produced in Pinta. “ images / bw_3x3.png”是我在Pinta中制作的3x3图像。 I tried opening a cat.jpg I got from Google Images, but I got the same error. 我尝试打开从Google图片获得的cat.jpg,但遇到了同样的错误。
I also tried to use "encoding="latin-1"
as an argument to open, based on something I read on SO; I was able to open the file, but I'm read failed with the exception 我还尝试使用"encoding="latin-1"
作为打开的参数,这是基于我在SO上读取的内容;我能够打开该文件,但由于异常而读取失败
OSError: cannot identify image file <_io.TextIOWrapper name='images/bw_3x3.png' mode='r' encoding='latin-1'> OSError:无法识别图像文件<_io.TextIOWrapper name ='images / bw_3x3.png'mode ='r'encoding ='latin-1'>
The line that is causing the error is 导致错误的行是
s = f.read()
In 'r' mode this tries to read the data as a string, but it's a image file, so it will fail. 在“ r”模式下,它尝试以字符串形式读取数据,但是它是图像文件,因此将失败。 You can use 'rb' instead. 您可以改用“ rb”。 Definitely remove the encoding=latin
because that's only relevant for text files. 一定要删除encoding=latin
因为这仅与文本文件有关。
Also, note that according to the documentation : 另外,请注意,根据文档 :
name : str or file object 名称:str或文件对象
The file name or file object to be read. 要读取的文件名或文件对象。
So you can dispense with opening a file and just give it a filepath as a string. 因此,您可以省去打开文件的过程,而只需给它一个文件路径作为字符串即可。 The following should work: 以下应该工作:
img = sc.misc.imread(filename)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.