You need to enable JavaScript to run this app. 如何解决python-opencv循环分类保存图片到不同文件夹的异常问题
优惠活动
大模型
产品
解决方案
定价
更多

如何解决python-opencv循环分类保存图片到不同文件夹的异常问题

问题根因
  • 图片存储逻辑错误:首个读取图片的循环中,img变量会被每次新读取的图片覆盖,循环结束后仅保留最后一张图片的内容。后续cv2.imwrite传入的img[index]实际是取最后一张图片的第index行像素数组,而非对应序号的完整图片,直接导致保存内容异常、格式无法识别。
  • 索引未绑定:读取图片时未将所有图片按顺序存入列表,无法和相关性数组的索引一一对应,分类时匹配不到正确的原图片。
  • 缺少文件夹创建逻辑:如果目标分类文件夹不存在,cv2.imwrite会直接写入失败。
  • 变量未定义:代码中用于判断的rounded_value数组没有提前定义,你实际计算得到的相关性数组是r,需要先完成四舍五入处理再用于阈值判断。
修复方案
  1. 读取图片时将所有图片、对应文件名按顺序存入列表,保证和相关性数组的索引一一匹配
  2. 提前判断并创建三个分类的目标文件夹,避免写入失败
  3. 修正保存时传入的图片参数,使用对应索引的完整图片
  4. 补全rounded_value的计算逻辑,直接基于计算得到的相关性数组做判断
修复后完整代码
import os
import cv2

# 提前创建目标文件夹
os.makedirs('./uniform_luminance', exist_ok=True)
os.makedirs('./ambiguous_luminance', exist_ok=True)
os.makedirs('./non_uniform_luminance', exist_ok=True)

folder = "你的图片文件夹路径" # 替换为你的图片文件夹实际路径
img_list = []
filename_list = []

# 读取所有图片并存入列表,保证索引和后续相关性数组对应
for filename in os.listdir(folder):
    if filename.endswith('.jpg'):
        img = cv2.imread(os.path.join(folder, filename))
        if img is not None:
            img_list.append(img)
            filename_list.append(filename)
            # 你的灰度转换、相关性计算逻辑可以放在这里,保证correlation_matrices的索引和img_list对应
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 计算相关性数组r(你的原有逻辑,保证r的长度和img_list一致)
r = []
for correlation in range(len(correlation_matrices)):
    symmetry = correlation_matrices[correlation][0,1]
    r.append(symmetry)

# 补全rounded_value计算
rounded_value = [round(x, 2) for x in r]

threshold1 = 0.45
threshold2 = 0.35

# 分类保存
for index in range(len(r)):
    current_img = img_list[index]
    if rounded_value[index] >= threshold1:
        print('Normal Image')
        cv2.imwrite(f'./uniform_luminance/Normal_{index}.jpg', current_img)
    elif threshold2 <= rounded_value[index] < threshold1:
        print('Ambiguous Image')
        cv2.imwrite(f'./ambiguous_luminance/Ambiguous_{index}.jpg', current_img)
    else:
        print('Abnormal Image')
        cv2.imwrite(f'./non_uniform_luminance/Abnormal_{index}.jpg', current_img)

内容的提问来源于stack exchange,提问作者Kimwaga Makono

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 17:45:00