PyQt4中有没有什么函数可以帮助我确定一个点是否在QPolygon的边界上?例如:
from PyQt4 import QtGui
from PyQt4.QtCore import Qt, QPoint as QP
polygon = QtGui.QPolygon([QP(0, 1), QP(3,7), QP(4, 6), QP(4,3), QP(2,1), QP(0,1])如果我向函数传递QP(1,3)、QP(4,5)、QP(3,2)或QP(1,1),则该函数应返回true。
发布于 2014-09-04 22:53:24
这确实是一个困难的问题。我尝试了很多QPolygon的方法,比如intersected,united,subtracted,但都没有成功。
例如,我认为这可能会起作用:复制多边形,将点添加到副本中,然后检查结果是否为空。如果该点位于多边形的周长上,则原始和副本应具有相同的形状,因此结果应为空。
def on_perimeter(poly, point):
poly2 = poly + QtGui.QPolygon() # copy the polygon
poly2.add(point)
return poly.subtracted(poly2).isEmpty()然而,多边形似乎是按照给出的点的顺序“绘制”的,因此,如果你只是添加点,这将导致一些其他形状。例如,考虑形成正方形的点(0,0) (0,2) (2.2) (2,0),您想要检查(0,1)。如果你只是在最后加上点,这将把(2,0)和(0,1)连接起来,把(0,1)和(0,0)连接起来,因为多边形必须是一个闭合的形状。这会给出一些其他的形状。因此,你必须在正确的位置插入点才能得到相同的形状。对于这个例子,它应该就在(0,0)之后。所以我想,好吧,让我们尝试上面所有可能的排列,只会有一个配置(以及它的旋转和反转产生的变换),这样减法的结果就是空的。
import itertools
def on_perimeter(poly, point):
points = [point] # the points of the new polygon
for ii in range(0, poly.size()):
points += [poly.point(ii)]
permuts = list(itertools.permutations(points)) # all possible permutations
checks = 0
for permut in permuts:
checks += int(poly.subtracted(QtGui.QPolygon(list(permut))).isEmpty())
return checks但不知何故,这也不起作用。尝试你的例子,对于QP(4,5)和QP(3,2),对于QP(1,1) checks = 20和对于QP(1,3) checks = 0,得到的值是checks = 10。我所期望的是获得所有点的checks = 12 (因为它们都位于边界上)。因为poly2是由6点组成的,所以你可以旋转点6次,并且在你颠倒顺序后做同样的事情,所以让<>d30>中包含的12不同的配置导致相同的形状。此外,如果执行相反的减法(即QtGui.QPolygon(list(permut)).subtracted(poly).isEmpty()),我将获得每个点的True,甚至不是位于多边形内而是位于多边形外部的点也是如此。
我在上面的函数中使用united和intersected而不是isEmpty来做类似的事情:
tmp = QtGui.QPolygon(list(permut))
checks += int(poly.intersected(tmp) == poly.united(tmp))这里也是一样,只有当点实际上位于边界上时,它才应该评估为True。但这将返回我在上面示例中检查的几乎每个点的False。
我没有看过QPolygon方法的源代码(如果有的话),但似乎发生了一些奇怪的事情。
所以我建议你写一个自己的方法,如果点位于多边形中的一条线上,它会对多边形中的所有直线求值。
def on_perimeter(poly, point):
lines = []
for ii in range(1, poly.size()):
p1 = poly.point(ii-1)
p2 = poly.point(ii)
lines += [ ( (p1.x(), p1.y()), (p2.x(), p2.y()) ) ]
lines += [ ( (poly.last.x(), poly.last.y()), (poly.first.x(), poly.first.y()) ) ]
for line in lines:
dx = line[1][0] - line[0][0]
dy = line[1][1] - line[0][1]
if abs(dx) > abs(dy) and dx*dy != 0 or dx == 0 and dy == 0: # abs(slope) < 1 and != 0 thus no point with integer coordinates can lie on this line
continue
if dx == 0:
if point.x() == line[0][0] and (point.y()-line[[0][1])*abs(dy)/dy > 0 and (line[1][1]-point.y())*abs(dy)/dy > 0:
return True
if dy == 0:
if point.y() == line[0][1] and (point.x()-line[[0][0])*abs(dx)/dx > 0 and (line[1][0]-point.x())*abs(dx)/dx > 0:
return True
dx2 = point.x() - line[0][0]
dy2 = point.y() - line[0][1]
if dx*dx2 < 0 or dy*dy2 < 0:
continue
if abs(dx) % abs(dx2) == 0 and abs(dy) % abs(dy2) == 0:
return True
return False这看起来有点繁重,但仅使用整数执行所有计算是很重要的,因为由于浮点精度的原因,您可能会得到错误的结果(QPolygon只接受整型点)。虽然还没有经过测试,但它应该可以工作。
https://stackoverflow.com/questions/25491786
复制相似问题