You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修复Pandas存储分割图像RGB均值到Excel时文件名重复覆盖的问题

问题原因
  • 文件名全部相同:遍历图像的循环内,每次都给整个转置后的DataFrame的name列赋值为当前文件的文件名,之前所有行的文件名会被统一覆盖为当前遍历到的文件名,最终所有行的文件名都等于最后一个文件的名称。
  • 首行数值不匹配:DataFrame拼接、转置、均值计算、Excel写入全放在了循环内部,每遍历一张图就会修改全部已有数据、重复计算均值、覆盖写入Excel,累加过程中数据逻辑混乱,导致首行数值和第一张图的计算结果不符。
修复方案

将单张图像数据收集、全局数据处理、Excel写入三个逻辑拆分:循环内仅做单张图像的RGB均值计算和数据暂存,所有图像遍历完成后再统一生成DataFrame、计算全局均值、写入Excel。同时增加文件夹存在性判断,避免路径不存在导致的写入报错。

修复后完整代码
import cv2 as cv
import glob
import numpy as np
from skimage import io
import pandas as pd
from colormath.color_objects import sRGBColor, xyYColor, LabColor, XYZColor
from colormath.color_conversions import convert_color
import xlsxwriter
import os


# 图像分割逻辑保持不变
path = "C:/Users/User/Desktop/Color/Fontane/36/*.jpg"
img_number = 1

for file in glob.glob(path):
    print(file)
    img = cv.imread(file)
    scale_percent = 60
    width = int(img.shape[1] * scale_percent / 100)
    height = int(img.shape[0] * scale_percent / 100)
    dim = (width, height)
    imgr = cv.resize(img, dim, interpolation=cv.INTER_AREA)

    hsv = cv.cvtColor(imgr, cv.COLOR_BGR2HSV)
    blur0 = cv.medianBlur(hsv, 11)

    low_yellow = np.array([17, 25, 210])
    high_yellow = np.array([30, 255, 255])

    mask = cv.inRange(blur0, low_yellow, high_yellow)
    res = cv.bitwise_and(imgr, imgr, mask=mask)

    fname = os.path.splitext(os.path.basename(file))[0]
    # 自动创建分割结果存储文件夹,避免路径不存在报错
    os.makedirs('C:/Users/User/Desktop/Color/Fontane/36/SEG/', exist_ok=True)
    cv.imwrite(f'C:/Users/User/Desktop/Color/Fontane/36/SEG/{fname}.jpg',res)

# 重构RGB计算与Excel写入逻辑
path1 = "C:/Users/User/Desktop/Color/Fontane/36/SEG/*.jpg"
# 用列表暂存单张图像计算结果,拼接效率更高
result_list = []

for file in glob.glob(path1):
    image = io.imread(file)
    # 计算当前图像非黑区域的平均RGB值
    avg_rgb = image[np.all(image != 0, axis=2)].mean(axis=0)
    r, g, b = avg_rgb[0], avg_rgb[1], avg_rgb[2]
    fname = os.path.splitext(os.path.basename(file))[0]
    # 单张结果存入列表,互不干扰
    result_list.append({
        'R': r,
        'G': g,
        'B': b,
        'Filename': fname
    })

# 所有图像遍历完成后统一生成DataFrame
df = pd.DataFrame(result_list)
# 计算全局均值行
mean_row = df[['R', 'G', 'B']].mean()
mean_row['Filename'] = 'Mean'
df = pd.concat([df, pd.DataFrame([mean_row])], ignore_index=True)
# 保留1位小数
df = df.round(decimals=1)

# 统一写入Excel,仅执行一次避免覆盖
os.makedirs('C:/Users/User/Desktop/Color/Fontane/RGB/', exist_ok=True)
writer = pd.ExcelWriter("C:/Users/User/Desktop/Color/Fontane/RGB/36.xlsx", engine='xlsxwriter')
df.to_excel(writer, sheet_name='RGB', index=False)
writer.save()

内容的提问来源于stack exchange,提问作者Thijs Brokking

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 18:36:05