统计黑色背景图像中的白色区域数量
要统计黑色背景图像中的白色区域数量,可以采用以下步骤:
二值化图像
二值化图像,将白色区域转换为 1,黑色区域转换为 0。
使用 cv2.connectedponentswithstats()
使用 cv2.connectedponentswithstats() 函数搜索图像中的连通区域。
遍历连通区域
遍历连通区域并计数面积大于一定阈值的区域。
具体代码实现:
import cv2import numpy as np# 读取图像img = cv2.imread("black_background_image.jpg")# 二值化图像gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)_, bin_img = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)# 使用 cv2.connectedComponentsWithStats()ret, labels, stats, _ = cv2.connectedComponentsWithStats(bin_img, connectivity=8)# 设置面积阈值area_threshold = 100# 计数白色区域数量count = 0for stat in stats: if stat[2] – stat[0] > area_threshold: count += 1# 显示结果print("白色区域数量:", count)
以上就是如何统计黑色背景图像中的白色区域数量?的详细内容,更多请关注范的资源库其它相关文章!
转载请注明:范的资源库 » 如何统计黑色背景图像中的白色区域数量?