使用maltplot在图片上绘制矩形框,并输出长宽和长宽比率

本文介绍了一个使用PythonMatplotlib库创建的RectangleDrawer类,该类允许用户在图像上进行点击并实时绘制矩形,同时显示矩形的尺寸和宽高比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值