如何用Python OpenCV计算白色区域到图像四边距离?轮廓法失效求方案
问题:计算图像白色区域到四边的距离
现有一张尺寸为2000*2000的图像,需计算图像中白色区域到上、下、左、右四个边界的距离。尝试使用OpenCV轮廓检测方法实现,但该方法在部分图像上无法正常工作,现有代码如下:
image = cv2.imread(image_full_path) ori_h, ori_w, _ = image.shape print("Original height, width-->", ori_h, ori_w) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # grayscale _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV) # threshold kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3)) dilated = cv2.dilate(thresh, kernel, iterations=13) # dilate contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # get contours idx = 0 # for each contour found, draw a rectangle around it on original image # print('length', len(contours)) for contour in contours: idx += 1 # get rectangle bounding contour [x, y, w, h] = cv2.boundingRect(contour) remaining_height_bottom = ori_h - (y + h) remaining_width_right_side = ori_w - (x + w) print("Upper Height, Right Width-->", y, x) print("Bottom Height, Left Width-->", remaining_height_bottom, remaining_width_right_side) print("Image Height, Image Width-->", h, w)
示例图像:
可行解决方案
放弃依赖轮廓检测的复杂流程,直接基于像素级检测白色区域的极值坐标,这种方法更稳定,不受阈值、膨胀操作的影响:
核心思路
- 读取图像并转为灰度图
- 定位所有白色像素(灰度值为255)的坐标
- 通过这些坐标的极值计算到四边的距离:
- 到上边界的距离 = 白色像素的最小y坐标
- 到下边界的距离 = 图像高度 - 白色像素的最大y坐标 - 1(像素坐标从0开始,需修正偏移)
- 到左边界的距离 = 白色像素的最小x坐标
- 到右边界的距离 = 图像宽度 - 白色像素的最大x坐标 - 1
实现代码
import cv2 import numpy as np image_full_path = "你的图像路径" image = cv2.imread(image_full_path) ori_h, ori_w, _ = image.shape # 转灰度图 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 找到所有白色像素的坐标 white_pixels = np.where(gray == 255) if len(white_pixels[0]) == 0: print("图像中无白色区域") else: min_y = np.min(white_pixels[0]) max_y = np.max(white_pixels[0]) min_x = np.min(white_pixels[1]) max_x = np.max(white_pixels[1]) # 计算到四边的距离 distance_top = min_y distance_bottom = ori_h - max_y - 1 distance_left = min_x distance_right = ori_w - max_x - 1 print(f"到上边界距离: {distance_top}") print(f"到下边界距离: {distance_bottom}") print(f"到左边界距离: {distance_left}") print(f"到右边界距离: {distance_right}")
说明
- 直接检测白色像素极值,避免了轮廓检测中阈值设置、膨胀迭代次数等参数带来的不确定性
- 若白色区域不是纯255灰度值,可调整判断条件为
gray > 240这类区间判断 - 代码逻辑简洁,计算效率高,无需复杂形态学操作
内容的提问来源于stack exchange,提问作者Chrish Mortain
相关产品推荐
相关产品推荐

