Matplotlib中无法将图像裁剪至旋转多边形的问题求助
Matplotlib中无法将图像裁剪至旋转多边形的问题求助
大家好,我正在做一个项目,需要用Matplotlib把光伏模块的图像裁剪成旋转后的矩形多边形,但遇到了一个棘手的问题:在很多旋转角度下,图像的裁剪效果都不理想,图像只会贴合多边形矩形的短边,没法完全匹配整个旋转后的多边形区域。
我目前写的代码如下:
import matplotlib.patches as mp import matplotlib.pyplot as plt import numpy as np from PIL import Image def set_pv_modules_envelope(module_poly: list) -> list: """ compute bounding box for the polygon. """ xs = [p[0] for p in module_poly] ys = [p[1] for p in module_poly] x_min_poly, x_max_poly = min(xs), max(xs) y_min_poly, y_max_poly = min(ys), max(ys) return [x_min_poly, x_max_poly, y_min_poly, y_max_poly] def rotate_point(point, angle_degrees): angle_radians = np.radians(angle_degrees) rotation_matrix = np.array([ [np.cos(angle_radians), -np.sin(angle_radians)], [np.sin(angle_radians), np.cos(angle_radians)] ]) return np.dot(rotation_matrix, point) poly = [(0, 0), (5, 0), (5, 10), (0, 10)] rotate_angle = 90 target_polygon = np.array([rotate_point(point, rotate_angle) for point in poly]) pv_module_img = plt.imread("..\\module_img.png") pv_module_img_uint8 = (pv_module_img * 255).astype(np.uint8) pv_module_img_reshaped = np.squeeze(pv_module_img_uint8) rotated = Image.fromarray(pv_module_img_reshaped).rotate(rotate_angle) fig, ax = plt.subplots(figsize=(8, 6)) extent = set_pv_modules_envelope(target_polygon) patch = mp.Polygon(target_polygon, closed=True) ax.add_patch(patch) ax.imshow( rotated, extent=extent, clip_path=patch, clip_on=True, zorder=3 ) plt.axis("scaled") plt.axis("off") plt.show()
下面是出现的问题效果:
当旋转角度为90度时,裁剪后的图像只贴合了短边:

当旋转角度为45度时,同样有这个问题:

这是我使用的原始光伏模块图像:
有没有大佬能帮我看看问题出在哪,怎么才能让图像完全贴合旋转后的多边形,正确完成裁剪呢?
备注:内容来源于stack exchange,提问作者Nitcha
相关产品推荐
相关产品推荐

