import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np
class RectangleDrawer:
def __init__(self, image):
self.image = image
self.fig, self.ax = plt.subplots()
self.ax.imshow(self.image)
self.rectangles = []
self.counter = 1
self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press)
self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release)
def on_press(self, event):
if event.inaxes:
self.x0, self.y0 = event.xdata, event.ydata
rect = Rectangle((self.x0, self.y0), 1, 1, linewidth=1, edgecolor='r', facecolor='none')
self.ax.add_patch(rect)
self.rectangles.append((rect, (self.x0, self.y0)))
self.ax.text(self.x0, self.y0 - 10, f'{self.counter}', color='red')
self.fig.canvas.draw()
self.counter += 1
def on_release(self, event):
if event.inaxes:
self.x1, self.y1 = event.xdata, event.ydata
width = abs(self.x1 - self.x0)
height = abs(self.y1 - self.y0)
aspect_ratio = height / width
rect, _ = self.rectangles[-1]
rect.set_width(width)
rect.set_height(height)
self.fig.canvas.draw()
print(f'Rectangle {self.counter - 1}:')
print(f' Size: Width={width:.2f}, Height={height:.2f}')
print(f' Aspect Ratio: {aspect_ratio:.2f}')
# 读取图像
image = plt.imread('test_110_1212_0164.png')
# 创建 RectangleDrawer 对象
drawer = RectangleDrawer(image)
plt.show()
使用maltplot在图片上绘制矩形框,并输出长宽和长宽比率
最新推荐文章于 2024-08-11 18:55:18 发布