如何逐行统计图像中绿色与白色像素的数量及占比?
逐行统计图像中绿色与白色像素的数量及占比实现方案
修改思路
原代码实现了整幅图像的绿色、白色像素统计,要实现逐行统计,只需遍历图像掩码的每一行,对每行单独进行像素计数与占比计算即可。核心是针对每行的掩码数据单独处理,同时可以选择输出该行内的占比或占总像素的占比。
完整实现代码
import cv2 import numpy as np from PIL import Image # 读取图像并获取尺寸信息 img_s = Image.open('img_15.png') width, height = img_s.size total_pixels = width * height # 加载图像并转换为HSV色彩空间(用于精准识别绿色) img = cv2.imread('img_15.png') hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # 定义绿色的HSV阈值范围,生成绿色区域掩码 lower_green = (40, 100, 100) upper_green = (100, 255, 255) mask = cv2.inRange(hsv, lower_green, upper_green) # 逐行统计并输出结果 print(f"图像总像素数: {total_pixels}") print("="*60) for row_idx in range(height): # 提取当前行的掩码数据 current_row = mask[row_idx, :] # 统计当前行绿色像素数量(掩码中非零值对应绿色区域) green_count = np.count_nonzero(current_row) # 计算当前行白色像素数量 white_count = width - green_count # 计算占比:该行内占比 + 占总像素占比 green_row_ratio = (green_count / width) * 100 green_total_ratio = (green_count / total_pixels) * 100 white_row_ratio = (white_count / width) * 100 white_total_ratio = (white_count / total_pixels) * 100 # 格式化输出该行统计结果 print(f"第 {row_idx+1} 行统计:") print(f" 绿色像素数: {green_count} | 占该行比例: {green_row_ratio:.2f}% | 占总像素比例: {green_total_ratio:.2f}%") print(f" 白色像素数: {white_count} | 占该行比例: {white_row_ratio:.2f}% | 占总像素比例: {white_total_ratio:.2f}%") print("-"*60) # 保存生成的绿色掩码图像 cv2.imwrite('img_15_mask.png', mask) # 显示掩码窗口(按任意键关闭) cv2.imshow('mask', mask) cv2.waitKey(0) cv2.destroyAllWindows()
关键说明
- HSV色彩空间:相比RGB,HSV能更精准地筛选绿色,避免光照等因素干扰
- 逐行遍历:通过
range(height)遍历每一行索引,提取对应行的掩码数据进行统计 - 双维度占比:同时输出该行内的像素占比和占整幅图像总像素的占比,满足不同统计需求
- 输出格式化:用分隔线和清晰的字段标注,让统计结果更易读
内容的提问来源于stack exchange,提问作者FRECEENA FRANCIS
相关产品推荐
相关产品推荐

