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)