计算图像红色区域占比结果偏低的问题排查
问题分析与错误点说明
我有一组含红色区域的图像,想要提取文件夹中每张图像的红色区域占比,使用下方代码实现后返回的占比数值远低于预期。即使将target_color设置为画图工具获取的图像中红色值,且设置了较大的color_range,结果依然偏低。请问存在哪些明显的错误导致该问题?
代码示例
import cv2 import os import csv import numpy as np # Define the target color and color range (in RGB format) target_color = (245,480,176) color_range = 50 # Define the folder containing the images folder = "Data/pictures/renamed/" # Define the path to the output CSV file output_file = "Data/pictures/area.csv" # Open the CSV file for writing with open(output_file, 'w', newline='') as csvfile: writer = csv.writer(csvfile) # Write the header row writer.writerow(["Filename", "Percentage"]) # Loop over every file in the folder for filename in os.listdir(folder): # Make sure the file is an image if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png"): # Construct the full path to the image filepath = os.path.join(folder, filename) # Load the image img = cv2.imread(filepath) # Calculate the percentage of the image that is within the color range of the target color lower_bound = np.clip(np.array(target_color) - color_range, 0, 255) upper_bound = np.clip(np.array(target_color) + color_range, 0, 255) mask = cv2.inRange(img, lower_bound, upper_bound) num_pixels = img.shape[0] * img.shape[1] target_pixels = cv2.countNonZero(mask) percentage = (target_pixels / num_pixels) * 100 # Write the filename and percentage to the CSV file writer.writerow([filename, percentage])
明显的错误点
- OpenCV颜色通道顺序错误:
cv2.imread()读取的图像是BGR格式,但你定义的target_color标注为RGB格式,直接用RGB值去匹配BGR图像,完全对应不上红色区域。比如红色的RGB是(255,0,0),对应BGR应该是(0,0,255),用RGB范围检测BGR图像自然找不到正确区域。 - 无效的颜色值:
target_color中的第二个值是480,超出了像素颜色值0-255的合法范围,即使通过np.clip强制转为255,也和你从画图工具获取的真实颜色值不符,直接导致颜色范围计算完全错误。 - 颜色范围逻辑基于错误通道:因为通道顺序错误,你计算的
lower_bound和upper_bound都是针对RGB通道的范围,套用到BGR图像上生成的mask根本无法匹配目标红色区域,统计到的像素数量自然远低于实际值。
修复建议
- 将
target_color转换为BGR格式:比如画图工具取的RGB是(R,G,B),改成(B,G,R)传入。 - 修正
target_color中的数值:确保每个分量都在0-255之间,比如把480改成正确的数值(比如48)。 - 可选优化:处理红色这类易受光照影响的颜色时,转为HSV色彩空间进行范围匹配鲁棒性更强,比RGB/BGR更适合。
内容的提问来源于stack exchange,提问作者Eric Nilsen
相关产品推荐
相关产品推荐

