|
发表于 2023-8-18 20:00:51
|
显示全部楼层
要提取二值化结果中连续的白色区域,可以使用OpenCV的连通组件标记函数 connectedComponentsWithStats 来实现。在原代码的基础上,需要添加以下代码:
- import cv2
- # 连通组件标记
- num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary, connectivity=8)
- # 提取连续的白色区域
- white_regions = []
- for i in range(1, num_labels):
- # 过滤掉面积小于阈值的区域
- if stats[i, cv2.CC_STAT_AREA] >= min_area:
- # 获取区域的边界框坐标
- x, y, w, h = stats[i, cv2.CC_STAT_LEFT], stats[i, cv2.CC_STAT_TOP], stats[i, cv2.CC_STAT_WIDTH], stats[i, cv2.CC_STAT_HEIGHT]
- white_regions.append((x, y, w, h))
- # 在原图上绘制提取的连续白色区域
- image_with_regions = image.copy()
- for region in white_regions:
- x, y, w, h = region
- cv2.rectangle(image_with_regions, (x, y), (x+w, y+h), (0, 255, 0), 2)
- # 保存带有连续白色区域的图像
- cv2.imwrite(output_path, image_with_regions)
复制代码
需要注意的是,代码中的 min_area 是一个面积阈值,用于过滤掉面积小于该阈值的区域。可以根据实际需求进行调整。另外,需要确保已经安装了OpenCV库。 |
|