使用CV2循环读取文件夹内图片时出现UnicodeDecodeError错误如何解决
错误原因
- 参数传递错误:
cv2.imread()返回值为图片像素矩阵的numpy数组,而image.load_img()要求传入的第一个参数为图片的本地路径字符串,你误将numpy数组作为路径传入,解析时自然触发编码错误。 - 逻辑分支缺陷:无论
cv2.imread()是否读取成功,你都会执行后续的image.load_img()逻辑,遇到无效文件时直接报错。 - 遍历无过滤:
os.listdir()会返回目标文件夹下的所有子目录、非图片文件,未做过滤会触发无效读取。
修复方案
你之前的排查方向完全偏离,问题和编码、rb模式读取没有任何关系,调整参数传递逻辑+增加过滤规则即可解决,修复后的可运行代码如下:
import os import cv2 from tensorflow.keras.preprocessing import image # 按需调整import来源 folder_angry = 'C:/Users/User/Desktop/test' all_vald_img = [] # 可自行补充需要支持的图片后缀 valid_img_suffix = {"jpg", "jpeg", "png", "bmp", "webp"} for filename_valid in os.listdir(folder_angry): # 先拼接完整的文件路径 full_img_path = os.path.join(folder_angry, filename_valid) # 过滤子目录、非图片文件 if not os.path.isfile(full_img_path): continue file_suffix = filename_valid.split(".")[-1].lower() if file_suffix not in valid_img_suffix: continue # 读取cv2格式图片存入列表 img_valid = cv2.imread(full_img_path) if img_valid is not None: all_vald_img.append(img_valid) # 传入路径字符串而非numpy数组 true_image = image.load_img(full_img_path) img = image.load_img(full_img_path, color_mode="grayscale", target_size=(48, 48)) # 此处补充你自己的业务处理逻辑
你之前逐张指定路径可以正常运行,就是因为逐张操作时你给image.load_img()传入的是正确的路径字符串,循环时传参错误才导致报错。
内容的提问来源于stack exchange,提问作者zzripbong
相关产品推荐
相关产品推荐

