给定一个图像,我用下面的方法在里面画一条线。
def slope(x1,y1,x2,y2):
###finding slope
if x2!=x1:
return((y2-y1)/(x2-x1))
else:
return 'NA'
def draw_line(image,lineThickness, colors, points):
x1,y1, x2, y2=points
m=slope(x1,y1,x2,y2)
h,w=image.shape[:2]
if m!='NA':
px=0
py=-(x1-0)*m+y1
##ending point
qx=w
qy=-(x2-w)*m+y2
else:
### if slope is zero, draw a line with x=x1 and y=0 and y=height
px,py=x1,0
qx,qy=x1,h
cv2.line(image, (int(px), int(py)), (int(qx), int(qy)), colors, lineThickness)
return (px, py), (qx, qy)
这段代码(来自SA)确保给定一条线(由两个点定义),它覆盖了整个图像。
现在,我想在一张图像上绘制多条平行线,并通过一个参数来指定线与线之间的距离。
我目前的尝试是这样的。
#Utility to find if two segments intersect
def ccw(A,B,C):
Ax, Ay = A
Bx, By = B
Cx, Cy = C
return (Cy-Ay) * (Bx-Ax) > (By-Ay) * (Cx-Ax)
#Utility to find if two segments intersect
def intersect(A,B,C,D):
return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)
#Utility to find if a segment intersect a square
def intersect_square(A,B, s_size):
C = (1,1)
D = (1, s_size-1)
E = (s_size-1, +1)
F = (s_size-1, s_size-1)
return (ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)) or \
(ccw(A,E,F) != ccw(B,E,F) and ccw(A,B,E) != ccw(A,B,F)) or \
(ccw(A,C,E) != ccw(B,C,E) and ccw(A,B,C) != ccw(A,B,E)) or \
(ccw(A,D,F) != ccw(B,D,F) and ccw(A,B,D) != ccw(A,B,F))
#Utility to draw a white canvas
def draw_white_image(x_size,y_size):
img = np.zeros([x_size,y_size,3],dtype=np.uint8)
img.fill(255) # or img[:] = 255
return img
def draw_parallel_lines(img, thickness, colors, points, space):
#Draw the first line
draw_line(img, thickness, colors, points)
x1, y1, x2, y2 = points
flag = True
while(flag):
y1 += space
y2 += space
new_points = draw_line(img, thickness, colors, (x1,y1,x2,y2))
flag = intersect_square(new_points[0], new_points[1], h)
这段代码移动了我的初始点的y坐标 直到我生成的新线在方格外。很遗憾,这段代码给出了这样的结果。
线条不是等距的 我花了几个小时的时间在这上面,我现在还挺难过的。请帮助我
如果线段是由点定义的 (x1,y1)
和 (x2,y2)
,它有方向矢量。
(dx, dy) = (x2-x1, y2-y1)
归一化(单位长度)向量。
len = sqrt((x2-x1)^2 + (y2-y1)^2)
(udx, udy) = (dx / len, dy / len)
垂直向量:
(px, py) = (-udy, udx)
距离平行线的基点 dist
:
(x1', y1') = (x1 + px * dist, y1 + py * dist)
or
(x1', y1') = (x1 - udy * dist, y1 + udx * dist)
另一个终点。
(x2', y2') = (x1' + dx, y1' + dy)
为了得到另一个方向的平行线,要把符号否定掉。px,py