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

如何用Python将多张图片的多项属性输出至CSV文件?

解决多张图片属性导出CSV的问题

主要问题及修复方案

  • 缺少二值化步骤:cv2.findContours需要二值图像(黑白像素)作为输入,仅转灰度图无法准确检测轮廓。在灰度转换后添加二值化代码:

    _, img_binary = cv2.threshold(img_maskedgray, 127, 255, cv2.THRESH_BINARY_INV)
    

    (可根据你的图像明暗调整阈值127和阈值类型,比如THRESH_BINARY)

  • 未处理图像读取失败:若图片损坏或路径错误,cv2.imread返回None会导致后续代码崩溃,需添加判断跳过错误图片:

    imge = cv2.imread(filename1)
    if imge is None:
        print(f"无法读取图片: {filename1}")
        continue
    
  • CSV无表头:导出的CSV没有列名,可读性差,在循环前写入表头:

    csv_out.writerow(["文件名", "宽度", "高度", "轮廓面积", "外接矩形面积", "等效直径", "宽高比", "延伸率", "坚实度"])
    
  • 除零风险:计算宽高比、延伸率、坚实度时,若分母为0会触发错误,需添加判断避免:

    aspect_ratio = float(width)/height if height != 0 else 0.0
    extent = float(area)/rect_area if rect_area !=0 else 0.0
    solidity = float(area)/hull_area if hull_area !=0 else 0.0
    
  • 冗余列表:代码中定义的filename1s、widths等列表若后续无使用需求,可直接删除以节省内存。


修复后的完整代码

import csv
import cv2
import glob
import numpy as np

path = 'images/*.png'

# 添加newline=''避免Windows下CSV出现空行
with open('file.csv','w', newline='') as f:  
    csv_out = csv.writer(f)
    # 写入CSV表头
    csv_out.writerow(["文件名", "宽度", "高度", "轮廓面积", "外接矩形面积", "等效直径", "宽高比", "延伸率", "坚实度"])
    
    for filename1 in glob.glob(path):
        imge = cv2.imread(filename1) 
        # 检查图像是否读取成功
        if imge is None:
            print(f"无法读取图片: {filename1}")
            continue
        
        img_maskedgray = cv2.cvtColor(imge, cv2.COLOR_BGR2GRAY)
        # 二值化处理,适配轮廓检测需求
        _, img_binary = cv2.threshold(img_maskedgray, 127, 255, cv2.THRESH_BINARY_INV)
        
        contours2 = cv2.findContours(img_binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        contours2 = contours2[0] if len(contours2) == 2 else contours2[1]
        
        # 检查是否检测到轮廓
        if not contours2:
            print(f"图片{filename1}未检测到轮廓")
            csv_out.writerow([filename1, 0, 0, 0, 0, 0, 0, 0, 0])
            continue
        
        big_contour2 = max(contours2, key=cv2.contourArea)
        area = cv2.contourArea(big_contour2)
        x,y,width,height = cv2.boundingRect(big_contour2)
        
        # 安全计算各项属性,避免除零错误
        aspect_ratio = float(width)/height if height != 0 else 0.0
        rect_area = width*height
        extent = float(area)/rect_area if rect_area !=0 else 0.0
        
        hull = cv2.convexHull(big_contour2)
        hull_area = cv2.contourArea(hull)
        solidity = float(area)/hull_area if hull_area !=0 else 0.0
        
        equi_diameter = np.sqrt(4*area/np.pi) if area !=0 else 0.0
        
        # 写入当前图片的属性到CSV
        csv_out.writerow([filename1, width, height, area, rect_area, equi_diameter, aspect_ratio, extent, solidity])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:50:28