首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用opencv绘制python中等距段

用opencv绘制python中等距段
EN

Stack Overflow用户
提问于 2020-05-27 07:09:24
回答 1查看 345关注 0票数 0

给出一幅图像,我用以下方式在里面画一条线:

代码语言:javascript
复制
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)确保给定一行(由两点定义),它覆盖整个图像。

现在,我想在一幅图像上画出多条平行线,其中的参数可以指定直线之间的距离。

我目前的尝试是:

代码语言:javascript
复制
#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坐标移动,直到我生成的新行位于正方形之外。遗憾的是,这段代码给出了这样的结果:

线条不是等距的。我花了几个小时在这件事上,现在我有点难过。请帮帮忙

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-27 09:37:39

如果线段由点(x1,y1)(x2,y2)定义,则具有方向矢量:

代码语言:javascript
复制
(dx, dy) = (x2-x1, y2-y1)

归一化(单位长度)向量:

代码语言:javascript
复制
len = sqrt((x2-x1)^2 + (y2-y1)^2)
(udx, udy) = (dx / len, dy / len)

垂直矢量:

代码语言:javascript
复制
(px, py) = (-udy, udx)  

距离dist的平行线基点

代码语言:javascript
复制
(x1', y1') = (x1 + px * dist, y1 + py * dist)
or
(x1', y1') = (x1 - udy * dist, y1 + udx * dist) 

另一个终点是:

代码语言:javascript
复制
(x2', y2') = (x1' + dx, y1' + dy)

若要获得另一方向的平行线,请否定px,py的符号

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62037335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档