随机四边形内切最大16:9矩形(代码修改四边形坐标和输出矩形的比例)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from shapely.geometry import Polygon, box


def find_largest_ratio_rect(polygon, ratio):
    min_x, min_y, max_x, max_y = polygon.bounds
    best_rect = None
    best_area = 0

    step = 0.1  # Initial step size

    x = min_x
    while x <= max_x:
        y = min_y
        while y <= max_y:
            width = step
            height = step / ratio

            while (x + width <= max_x) and (y + height <= max_y):
                candidate = box(x, y, x + width, y + height)
                if polygon.contains(candidate):
                    area = candidate.area
                    if area > best_area:
                        best_area = area
                        best_rect = candidate
                width += step
                height = width / ratio
            y += step
        x += step

    return best_rect, best_area


def plot_polygon_and_incircle_rectangle(polygon_points, ratio):
    # Create a polygon object from the points
    poly = Polygon(polygon_points)

    # Find the largest ratio rectangle
    largest_ratio_rect, largest_area = find_largest_ratio_rect(poly, ratio)

    fig, ax = plt.subplots()

    # Draw the original polygon
    polygon_patch = patches.Polygon(polygon_points, closed=True, fill=True, color='blue', alpha=0.5)
    ax.add_patch(polygon_patch)

    # Draw the largest ratio rectangle if found
    if largest_ratio_rect:
        x, y = largest_ratio_rect.exterior.coords.xy
        rect_points = np.array([x, y]).T[:-1]  # Remove the redundant last point
        rect_patch = patches.Polygon(rect_points, closed=True, fill=None, edgecolor='red', linewidth=2)
        ax.add_patch(rect_patch)

        # Output the coordinates and area
        rect_coords = [(x[i], y[i]) for i in range(len(x) - 1)]
        print("Largest 16:9 Ratio Rectangle Coordinates:", rect_coords)
        print("Largest 16:9 Ratio Rectangle Area:", largest_area)

    # Set limits and display the plot
    min_x, min_y, max_x, max_y = poly.bounds
    ax.set_xlim(min_x - 1, max_x + 1)
    ax.set_ylim(min_y - 1, max_y + 1)
    ax.set_aspect('equal')
    plt.xlabel('X axis')
    plt.ylabel('Y axis')
    plt.title('Polygon and its largest 16:9 ratio inner rectangle')
    plt.show()


# Example usage
polygon_points = [(0, 0), (1, 7), (10, 11), (8, 1)]
ratio = 16 / 9
plot_polygon_and_incircle_rectangle(polygon_points, ratio)
 

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值