如何提取二值图像中最中心区域?原代码提取最大区域不符需求
提取二值图像中最中心的区域
要替换原有的“提取最大区域”逻辑,转而找到最靠近图像中心的轮廓,可以通过计算每个轮廓中心与图像中心的距离来实现,具体方案如下:
实现思路
- 确定图像的中心坐标
- 对每个轮廓计算其几何中心(优先用轮廓矩,极小轮廓用外接矩形中心替代)
- 计算每个轮廓中心到图像中心的欧氏距离
- 筛选出距离最小的轮廓,即为目标区域
修改后的完整代码
# Use the hue value to convert to binary thresh = 20 thresh, thresh_img = cv2.threshold(h, thresh, 255, cv2.THRESH_BINARY) cv2.imshow('thresh', thresh_img) cv2.waitKey(0) cv2.destroyAllWindows() # Finding Contours # Use a copy of the image since findContours alters the image contours, _ = cv2.findContours(thresh_img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # 计算图像中心 img_h, img_w = thresh_img.shape[:2] img_center = (img_w // 2, img_h // 2) # 遍历所有轮廓,找到最中心的那个 min_distance = float('inf') center_contour = None for cnt in contours: # 用轮廓矩计算轮廓中心 M = cv2.moments(cnt) if M["m00"] != 0: cX = int(M["m10"] / M["m00"]) cY = int(M["m01"] / M["m00"]) else: # 极小轮廓用外接矩形中心替代 x, y, w, h = cv2.boundingRect(cnt) cX = x + w // 2 cY = y + h // 2 # 计算欧氏距离 distance = ((cX - img_center[0])**2 + (cY - img_center[1])**2)**0.5 # 更新最小距离和对应轮廓 if distance < min_distance: min_distance = distance center_contour = cnt # 最终得到的最中心区域轮廓 c = center_contour
关键代码说明
- 图像中心计算:直接通过图像宽高取中点,
img_center = (img_w // 2, img_h // 2) - 轮廓中心计算:轮廓矩能更精准反映几何中心,若遇到极小轮廓导致矩为0的情况,用外接矩形中心作为备选方案
- 距离筛选:通过欧氏距离量化轮廓中心与图像中心的远近,最终保留距离最小的轮廓
内容的提问来源于stack exchange,提问作者Katie Price
相关产品推荐
相关产品推荐

