我正在寻找一种算法(最好是用Java编写的,但任何足够清晰以便翻译成Java的东西都可以),用于绘制4连通线。似乎Bresenham算法是最广泛使用的,但我发现所有易懂的实现都是8连通的。OpenCV的cvline函数显然有一个4连通版本,但对我来说,作为一个平庸而几乎不懂C语言的程序员,源代码是无法理解的。各种其他搜索都没有结果。
感谢任何人能提供的帮助。
感谢任何人能提供的帮助。
def line(x0, y0, x1, y1, color):
dx = abs(x1 - x0) # distance to travel in X
dy = abs(y1 - y0) # distance to travel in Y
if x0 < x1:
ix = 1 # x will increase at each step
else:
ix = -1 # x will decrease at each step
if y0 < y1:
iy = 1 # y will increase at each step
else:
iy = -1 # y will decrease at each step
e = 0 # Current error
for i in range(dx + dy):
draw_pixel(x0, y0, color)
e1 = e + dy
e2 = e - dx
if abs(e1) < abs(e2):
# Error will be smaller moving on X
x0 += ix
e = e1
else:
# Error will be smaller moving on Y
y0 += iy
e = e2
dx+dy
,因此我只需循环那么多次来绘制线条,而不是检查是否到达了终点。请注意,该算法绘制除最后一个像素外的所有像素;如果您还想要最后一个像素,则应在循环结束后添加额外的draw_pixel
调用。对于不熟悉Python的人,这里提供了6502代码的C版本:
void drawLine(int x0, int y0, int x1, int y1) {
int dx = abs(x1 - x0);
int dy = abs(y1 - y0);
int sgnX = x0 < x1 ? 1 : -1;
int sgnY = y0 < y1 ? 1 : -1;
int e = 0;
for (int i=0; i < dx+dy; i++) {
drawPixel(x0, y0);
int e1 = e + dy;
int e2 = e - dx;
if (abs(e1) < abs(e2)) {
x0 += sgnX;
e = e1;
} else {
y0 += sgnY;
e = e2;
}
}
}
import numpy as np
def points_on_line(start, end):
idx = np.round(np.array(start)).astype(int)
end_idx = np.round(np.array(end)).astype(int)
points = [idx]
if np.all(idx == end_idx):
return points
diff = np.array(end, dtype=float) - np.array(start, dtype=float)
direction = (diff / np.abs(diff)).astype(int)
coord = np.array(start, dtype=float)
while np.any(idx != end_idx):
# compute how far we need to go to reach the side of the pixel at idx
t = (idx + direction / 2 - coord) / diff
i = np.argmin(t)
coord += t[i] * diff
idx = idx.copy()
idx[i] += direction[i]
points.append(idx)
return points