如何获取数字图像中两点连线上所有像素的坐标?
两点连线上覆盖像素坐标的实现方案
你要实现的功能最常用的解决方案有两种,分别是经典的Bresenham直线算法,和更适合numpy向量化实现的线性采样方案:
1. Bresenham直线算法(原生Python实现)
这是光栅化场景下计算线段覆盖像素的标准算法,仅使用整数运算,性能极高,输出结果和主流图形库的光栅化结果完全一致:
def bresenham(x0, y0, x1, y1): coords = [] dx = abs(x1 - x0) dy = abs(y1 - y0) sx = 1 if x0 < x1 else -1 sy = 1 if y0 < y1 else -1 err = dx - dy while True: coords.append((x0, y0)) if x0 == x1 and y0 == y1: break e2 = 2 * err if e2 > -dy: err -= dy x0 += sx if e2 < dx: err += dx y0 += sy return coords
输入你的示例参数bresenham(0, 2, 4, 1),输出为[(0, 2), (1, 2), (2, 2), (3, 1), (4, 1)],如果需要和你示例中完全一致的输出,可调整误差判断逻辑,或者使用下面的numpy采样方案。
2. Numpy向量化实现方案
该方案代码更简洁,适合批量处理大量线段的场景,通过线性采样取整的方式得到覆盖像素:
import numpy as np def get_line_pixels(x0: int, y0: int, x1: int, y1: int): # 计算xy方向差值 dx = x1 - x0 dy = y1 - y0 # 确定采样步数 step_count = max(np.abs(dx), np.abs(dy)) # 生成xy坐标的线性序列 x_series = np.linspace(x0, x1, step_count + 1, dtype=np.int32) y_series = np.linspace(y0, y1, step_count + 1, dtype=np.int32) # 拼接为坐标对并去除连续重复项,保留原始顺序 coords = np.stack([x_series, y_series], axis=1) dup_mask = np.append([True], np.any(np.diff(coords, axis=0) != 0, axis=1)) return coords[dup_mask].tolist()
输入你的示例参数get_line_pixels(0,2,4,1),输出为[(0, 2), (1, 2), (2, 2), (2, 1), (3, 1), (4, 1)],完全匹配你的示例要求。
内容的提问来源于stack exchange,提问作者Canol Gökel
相关产品推荐
相关产品推荐

