如何查找二值图像每列首个与末个白色像素并计算点间距离
二值图像每列首尾白色像素检测及距离计算
以下是基于OpenCV和NumPy的落地实现方案,直接解决你的需求:
核心逻辑
- 将二值图像转为NumPy数组,便于批量操作像素坐标
- 定位所有白色像素的行、列索引,按列分组提取首尾行位置
- 计算同一列首尾像素的垂直距离(行索引差值)
完整代码示例
import cv2 import numpy as np # 读取二值图像(确保是单通道灰度图,白色为255,黑色为0) img = cv2.imread("binary_image.png", cv2.IMREAD_GRAYSCALE) if img is None: raise ValueError("无法读取图像,请检查路径是否正确") # 获取图像尺寸 height, width = img.shape # 定位所有白色像素的行、列索引 white_rows, white_cols = np.where(img == 255) # 初始化距离数组,存储每列的首尾距离 column_distances = np.zeros(width, dtype=int) # 遍历每一列计算距离 for col in range(width): # 筛选当前列的所有白色像素行索引 current_col_rows = white_rows[white_cols == col] if len(current_col_rows) > 0: first_row = np.min(current_col_rows) # 最上方白色像素行 last_row = np.max(current_col_rows) # 最下方白色像素行 column_distances[col] = last_row - first_row else: column_distances[col] = 0 # 无白色像素的列距离设为0 # 示例:打印前10列的计算结果 print("前10列首尾白色像素距离:", column_distances[:10])
适配与优化说明
- 反色图像适配:如果你的二值图像是白色为0、黑色为255的反色格式,将代码中的
img == 255改为img == 0即可 - 大图像性能优化:若图像尺寸极大,可改用批量分组替代循环,提升处理速度:
# 优化版:避免循环,用NumPy批量分组处理 unique_cols, col_indices = np.unique(white_cols, return_inverse=True) grouped_rows = np.split(white_rows, np.cumsum(np.bincount(col_indices))[:-1]) column_distances = np.zeros(width, dtype=int) for col, rows in zip(unique_cols, grouped_rows): column_distances[col] = np.max(rows) - np.min(rows) - 空列自定义处理:代码中默认无白色像素的列距离为0,可根据需求改为
None或其他标记值
内容的提问来源于stack exchange,提问作者Fianlto
相关产品推荐
相关产品推荐

