python 轮廓 获取环形区域

发布于:2025-02-10 ⋅ 阅读:(36) ⋅ 点赞:(0)

目录

效果图:

代码:


效果图:

代码:

import cv2
import numpy as np

# 读取图像
image = cv2.imread(r'E:\project\jijia\tools_jijia\img_tools\ground_mask.jpg', cv2.IMREAD_GRAYSCALE)
# 二值化图像
# 二值化图像
_, binary = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)

# 检测轮廓
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 创建一个空白图像来绘制轮廓
contour_image = np.zeros_like(image)

# 绘制原始轮廓
cv2.drawContours(contour_image, contours, -1, (255, 255, 255), 1)

# 创建一个核,用于腐蚀操作。核的大小为 21x21,以获得20个像素的腐蚀效果
kernel = np.ones((21, 21), np.uint8)

# 对二值图像进行腐蚀操作
eroded_image = cv2.erode(binary, kernel, iterations=1)

# 再次检测腐蚀后的轮廓
eroded_contours, _ = cv2.findContours(eroded_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 创建一个空白图像来绘制腐蚀后的轮廓
eroded_contour_image = np.zeros_like(image)

# 绘制腐蚀后的轮廓
cv2.drawContours(eroded_contour_image, eroded_contours, -1, (255, 255, 255), 1)

# 将两个轮廓之间的区域涂成白色
filled_image = np.zeros_like(image)
cv2.drawContours(filled_image, contours, -1, (255, 255, 255), thickness=cv2.FILLED)
cv2.drawContours(filled_image, eroded_contours, -1, (0, 0, 0), thickness=cv2.FILLED)  # 填充内部区域为黑色

# 显示结果
cv2.imshow('Original Contours', contour_image)
cv2.imshow('Eroded Contours', eroded_contour_image)
cv2.imshow('Filled Contours', filled_image)
cv2.waitKey(0)
cv2.destroyAllWindows()


网站公告

今日签到

点亮在社区的每一天
去签到