判断一个点是否在矩形内部(Python类定义)

有一个point,其坐标为(xp, yp);有一个四边形**(适用矩形或凸四边形;凹四边形不怎么适用我的要求,没测试)**,其四个角点的坐标依次为(xa, ya, xb, yb, xc, yc, xd, yd)。注意此处的“依次”,可逆时针,也可顺时针,一定要保证是依次;否则,增加排序函数。
定义一个类——isPointInQuadrangle,其函数cross_product用来求由3个点组成的两个向量的叉积,函数compute_para用来获取4个参数。

class isPointInQuadrangle(object):

    def __int__(self):
        self.__isInQuadrangleFlag = False

    def cross_product(self, xp, yp, x1, y1, x2, y2):
        return (x2 - x1) * (yp - y1)-(y2 - y1) * (xp - x1)

    def compute_para(self, xp, yp, xa, ya, xb, yb, xc, yc, xd, yd):
        cross_product_ab = isPointInQuadrangle().cross_product(xp, yp, xa, ya, xb, yb)
        cross_product_bc = isPointInQuadrangle().cross_product(xp, yp, xb, yb, xc, yc)
        cross_product_cd = isPointInQuadrangle().cross_product(xp, yp, xc, yc, xd, yd)
        cross_product_da = isPointInQuadrangle().cross_product(xp, yp, xd, yd, xa, ya)
        return cross_product_ab,cross_product_bc,cross_product_cd,cross_product_da

    def is_in_rect(self, aa, bb, cc, dd):
        if (aa > 0 and bb > 0 and cc > 0 and dd > 0) or (aa < 0 and bb < 0 and cc < 0 and dd < 0):
            print("This point is in the Quadrangle.")
            self.__isInQuadrangleFlag= True
        else:
            print("This point is not in the Quadrangle.")
            self.__isInQuadrangleFlag = False

        return self.__isInQuadrangleFlag

if __name__ == '__main__':
    aa, bb, cc, dd = isPointInQuadrangle().compute_para(600, 550, 508, 451, 730, 470, 718, 615, 495, 596)
    print(isPointInQuadrangle().is_in_rect(aa, bb, cc, dd))

输出结果:

This point is in the Quadrangle.
True

#原理请参考下方链接。
#编辑时间仓促,有不妥之处请留言。
运行本程序前,请确保输入的点是按照顺序排列的。
本程序的四边形角点坐标需要按照逆时针或者顺时针排列。本程序未考虑角点坐标排序问题,请读者自行补充。

参考:1.已知四边形的四个点,求一个点是否在四边形之内的解决方法
2.如何判断一个点在矩形内

你可能感兴趣的:(数据处理)