python - 使用opencv在python中绘制等距线段
问题描述
给定一张图片,我用以下方式在里面画一条线:
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
推荐阅读
- java - 如何为具有 JSON 作为有效负载的请求正文编写wiremock存根定义
- javascript - 如何在数组中找到包含最大值的对象
- php - 在 php 问题中更新时未定义的索引 [请帮助]
- java - 仅定义对象时会发生什么?
- javascript - 在没有 React 的 TypeScript 中使用 JSX
- c# - 如何将附加的 where 子句“注入”到给定的 nHibernate linq 中?
- java - 使用 Stream.reduce 的求逆和不正确
- android - Android APK 未安装在设备中
- bash - 如何使用分隔符提取数据
- c# - 将自定义分析器通用添加到 Nest Elastic 搜索 6.2 中的所有字段