【问题标题】:Scipy: UnicodeDecodeError while loading image fileScipy:加载图像文件时出现UnicodeDecodeError
【发布时间】:2016-08-12 04:38:24
【问题描述】:
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')

生产:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

“images/bw_3x3.png”是我在 Pinta 中制作的 3x3 图像。我尝试打开从 Google 图片获得的 cat.jpg,但出现了同样的错误。

我还尝试使用"encoding="latin-1" 作为打开的参数,基于我在 SO 上阅读的内容;我能够打开文件,但我 读取失败并出现异常

OSError: 无法识别图像文件 <_io.textiowrapper name="images/bw_3x3.png" mode="r" encoding="latin-1">

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    导致错误的行是

    s = f.read()
    

    在 'r' 模式下,它会尝试将数据读取为字符串,但它是图像文件,因此会失败。您可以改用“rb”。绝对删除encoding=latin,因为这仅与文本文件相关。

    另外,请注意根据the documentation

    name : str 或文件对象

    要读取的文件名或文件对象。

    因此,您无需打开文件,只需给它一个文件路径作为字符串。以下应该有效:

    img = sc.misc.imread(filename)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-07
      • 2012-05-21
      • 1970-01-01
      • 2021-01-21
      • 1970-01-01
      • 2023-03-24
      • 2012-09-19
      • 2018-12-26
      相关资源
      最近更新 更多