• python 求直线延长线和矩形的交点


    
    # -*- coding: utf-8 -*-#
    # -------------------------------------------------------------------------------
    # Name:         test
    # Author:       yunhgu
    # Date:         2022/4/13 14:00
    # Description: 
    # -------------------------------------------------------------------------------
    from PIL import ImageDraw, Image
    
    
    def getLinearEquation(point1, point2):
        p1x, p1y = point1
        p2x, p2y = point2
        sign = 1
        a = p2y - p1y
        if a < 0:
            sign = -1
            a = sign * a
        b = sign * (p1x - p2x)
        c = sign * (p1y * p2x - p1x * p2y)
        return [a, b, -c]
    
    
    def get_intersection(rectangle_point, point1, point2):
        intersection_list = []
        a, b, c = getLinearEquation(point1, point2)
        x_list = [rectangle_point[0], rectangle_point[2]]
        y_list = [rectangle_point[1], rectangle_point[3]]
        if b == 0:
            y = point1[-1]
            if y_list[0] <= y <= y_list[1]:
                intersection_list.extend([(point1[0], y_list[0]), (point2[0], y_list[1])])
        elif a == 0:
            x = point1[0]
            if x_list[0] <= x <= x_list[1]:
                intersection_list.extend([(x_list[0], point1[1]), (x_list[1], point1[1])])
        else:
            for x in x_list:
                y = (c - a * x) / b
                if rectangle_point[1] <= y <= rectangle_point[3]:
                    intersection_list.append((x, y))
            for y in y_list:
                x = (c - b * y) / a
                if rectangle_point[0] <= x <= rectangle_point[2]:
                    intersection_list.append((x, y))
        return intersection_list
    
    
    img = Image.new("RGB", (500, 500))
    draw = ImageDraw.Draw(img)
    rectangle = (50, 50, 250, 250)  # (x0,y0,x1,y1)
    draw.rectangle(rectangle, outline="blue")
    
    pt1 = (200, 30)
    pt2 = (150, 200)
    
    intersections = get_intersection(rectangle, pt1, pt2)
    print(intersections)
    draw.line(intersections, fill="green", width=6)
    draw.line((pt1, pt2), fill="red", width=2)
    img.show()
    
    

    image

  • 相关阅读:
    App集成支付宝
    关于Objective-c和Java下DES加密保持一致的方式
    Android开发规范
    android 屏幕适配问题
    Android AES加密算法及其实现
    linux文件系统调用(1)---mount
    Java(Android)解析KML文件
    【Akka】在并发程序中使用Future
    函数指针问题,求解答
    android旋转动画的两种实现方式
  • 原文地址:https://www.cnblogs.com/yunhgu/p/16140490.html
Copyright © 2020-2023  润新知