用opencv在python中绘制等距线段
给定一个图像,我用以下方式在其内部绘制一条线:用opencv在python中绘制等距线段,python,geometry,python-imaging-library,drawing,line,Python,Geometry,Python Imaging Library,Drawing,Line,给定一个图像,我用以下方式在其内部绘制一条线: 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)
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)
归一化(单位长度)向量:
垂直向量:
(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的符号取反,我看到两个正方形用等距线填充。所以你的方法有时确实有效?@MBo在一张图像中,线条是等距的。我希望每一张图片的距离都是一样的,好像你已经展示了5张图片,两张看起来不错。好的,如果您的
draw_line
函数出错,它将不会从顶部/底部边缘开始绘制线条raw_line应该在特定区域(图像)中绘制线条。直线由两个点(输入中四个坐标的元组)定义查看通过矩形窗口进行的直线剪裁
——例如,Liang Barski algo。你的答案错了。我可以编辑你的答案来添加最后的代码段吗?也许其他人会需要它。无论如何,非常感谢,“距离平行线的基点”部分是我无法理解的,您为我节省了很多时间!是的,添加实现将非常有用。
(x2', y2') = (x1' + dx, y1' + dy)