cv2.imwrite()无法将采集的图像保存到指定文件夹怎么办?
问题分析与解决方案
你的问题出在OpenCV的cv2.imwrite对非ASCII字符路径(比如阿姆哈拉语文件夹名)的兼容性问题,旧版本OpenCV无法正确解析这类路径,导致图片保存失败但不抛出编译错误。
解决办法
方法1:升级OpenCV到最新版本
OpenCV 4.5.0及以上版本修复了非ASCII路径的写入问题,直接执行升级命令:
pip install --upgrade opencv-python
方法2:用PIL库替代保存(无需升级OpenCV)
如果暂时不想升级,可以用PIL库保存图片,它对非ASCII路径支持更友好。修改代码如下:
import cv2 import os import uuid import time from PIL import Image import numpy as np for label in labels: cap = cv2.VideoCapture(0) print('Collecting images for {}'.format(label)) time.sleep(5) # 确保文件夹存在(避免创建时的编码问题) os.makedirs(os.path.join(IMAGES_PATH, label), exist_ok=True) for imgnum in range(number_imgs): print('Collecting image {}'.format(imgnum)) ret, frame = cap.read() if not ret: print("Failed to capture frame") continue imgname = os.path.join(IMAGES_PATH, label, f"{label}.{str(uuid.uuid1())}.jpg") # 把cv2的BGR格式转成PIL的RGB格式 frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) img = Image.fromarray(frame_rgb) img.save(imgname) cv2.imshow('frame', frame) time.sleep(2) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
方法3:用cv2.imencode绕开路径解析
先把图片编码成字节流,再用Python内置文件操作写入,绕开OpenCV的路径解析限制:
import cv2 import os import uuid import time for label in labels: cap = cv2.VideoCapture(0) print('Collecting images for {}'.format(label)) time.sleep(5) os.makedirs(os.path.join(IMAGES_PATH, label), exist_ok=True) for imgnum in range(number_imgs): print('Collecting image {}'.format(imgnum)) ret, frame = cap.read() if not ret: print("Failed to capture frame") continue imgname = os.path.join(IMAGES_PATH, label, f"{label}.{str(uuid.uuid1())}.jpg") # 编码成JPG字节流 success, img_bytes = cv2.imencode('.jpg', frame) if success: # 写入文件 with open(imgname, 'wb') as f: f.write(img_bytes) cv2.imshow('frame', frame) time.sleep(2) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
额外检查点
- 确认
IMAGES_PATH和标签文件夹的权限:确保当前用户有写入该路径的权限 - 打印
imgname后,手动在文件管理器中打开该路径,确认路径是否真的存在(编码问题可能导致路径看起来正确但实际无效)
内容的提问来源于stack exchange,提问作者zelalem adugnaw
相关产品推荐
相关产品推荐

