[英]Optimizing quadrilateral construction from coordinates
这是要解决的问题:
给定四个顶点,在每个坐标之间找到四个边,使它们形成四边形。
由于四边形中的任何一条边都不能与其他任何边相交,因此我只从两个随机顶点中选取一条边,然后检查该边是否与其余两个顶点相交。
这是它的粗略实现:
import random
import numpy as np
# Line segment intersection algorithm - created by Bryce Boe
# Source - http://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/
# edge AB and CD won't intersect if this returns false
def intersect(A, B, C, D):
return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)
def ccw(A, B, C):
return (C.y-A.y)*(B.x-A.x) > (B.y-A.y)*(C.x-A.x)
class Coord:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "(%s,%s)" % (self.x, self.y)
# Choose an edge from two random vertices (and another edge from the two remaining vertices)
# Choose another set of two vertices until the two edges created don't intersect
def draw_quad(coords):
if len(coords) != 4:
raise AttributeError
line_intersects = True
while line_intersects:
a, b = random.sample(coords, 2)
c, d = [x for x in coords if x != a and x != b]
line_intersects = not intersect(a, b, c, d)
return [Coord(a, c), Coord(c, b), Coord(b, d), Coord(d, a)]
但是,此解决方案有33%的机会选择不通过intersect(a, b, c, d)
顶点(给定任何坐标,您有2个结点将导致不相交的边,而1个结点将导致不相交的边) ,这需要循环的其他迭代。
我确实有另一个解决方案,该解决方案使用极坐标来查找两对相邻的顶点(通过避开给定顶点中最远的顶点),但是该解决方案实际上速度较慢,因为它需要更多的计算量。
有没有其他更快,可以确保在第一次迭代中成功的解决方案?
我提出了另一种算法:
每一次这样的检查都是微不足道的。 没有随机,没有相交。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.