将JPG加载到神经网络中:UnicodeDecodeError

问题描述 投票:2回答:2

有人可以说明我的代码有什么问题,究竟是什么导致了这个错误?我是Python初学者,我想将一些JPG加载到这个网络中。大多数情况下,我一直试图通过试验和错误以及本网站的故障排除来解决问题。这东西伤害了我的大脑所以请帮助一个新手。

先感谢您!

达伦

错误:

Traceback (most recent call last):
File "gan3.py", line 30, in <module>
content = open(os.path.join(path, filename)).read()
File "/Users/darren/miniconda3/lib/python3.7/codecs.py", line 322, in 
decode (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: 
invalid start byte

代码:

def loadImages(path):
    # return array of images
    imagesList = listdir(path)
    loadedImages = []
    for image in imagesList:
        img = PImage.open(path + image)
        loadedImages.append(img)
    return loadedImages
path = "input_data"
for filename in os.listdir(path):
    content = open(os.path.join(path, filename)).read()
    with open(path, 'rb') as f:
      text = f.read()

干杯啦!

python
2个回答
1
投票

默认情况下,open以文本模式打开文件。当您从中读取数据时,Python会自动尝试将您的数据转换为字符串,但这不是UTF-8编码的文本。

如果是图像,则必须以二进制模式打开它:

content = open(os.path.join(path, filename), mode='rb').read()

1
投票

您可以使用PIL库打开图像文件:

from PIL import Image
#<----code---->
content = Image.open(os.path.join(path, filename))
© www.soinside.com 2019 - 2024. All rights reserved.