如何在Python中复刻Matlab的drawcircle交互式图像画圆功能?
实现类似MATLAB drawcircle的交互式圆标注(Python)
完全可以在Python中借助Matplotlib或OpenCV实现交互式画圆并测量半径的功能,无需控制台迭代输入坐标。以下是两种实用方案:
方法一:使用Matplotlib实现交互式画圆
代码示例
import matplotlib.pyplot as plt import numpy as np class InteractiveCircleDrawer: def __init__(self, img): self.img = img self.fig, self.ax = plt.subplots() self.ax.imshow(img) self.circle = None self.center = None self.radius = 0 # 绑定鼠标事件回调 self.fig.canvas.mpl_connect('button_press_event', self.on_press) self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion) self.fig.canvas.mpl_connect('button_release_event', self.on_release) def on_press(self, event): if event.button == 1: # 左键点击确定圆心 self.center = (event.xdata, event.ydata) self.circle = plt.Circle(self.center, 0, edgecolor='red', facecolor='none', linewidth=2) self.ax.add_patch(self.circle) def on_motion(self, event): if self.center is not None and event.inaxes == self.ax: # 实时计算并更新半径 dx = event.xdata - self.center[0] dy = event.ydata - self.center[1] self.radius = np.sqrt(dx**2 + dy**2) self.circle.set_radius(self.radius) self.fig.canvas.draw() def on_release(self, event): if event.button == 1 and self.center is not None: # 标注半径数值 self.ax.text( self.center[0], self.center[1]-self.radius-10, f'Radius: {self.radius:.2f}', color='white', fontsize=10, backgroundcolor='black' ) self.center = None # 重置状态,可继续绘制新圆 self.fig.canvas.draw() # 使用示例 if __name__ == '__main__': img = plt.imread('your_image_path.jpg') # 替换为你的图像路径 drawer = InteractiveCircleDrawer(img) plt.show()
操作方式
- 左键点击图像任意位置确定圆心
- 拖拽鼠标调整圆的半径,实时预览效果
- 松开左键完成绘制,自动显示半径数值
- 可重复操作绘制多个圆
方法二:使用OpenCV实现交互式画圆
代码示例
import cv2 import numpy as np drawing = False # 是否处于绘制状态 center = (-1, -1) radius = 0 def draw_circle(event, x, y, flags, param): global drawing, center, radius, img_copy if event == cv2.EVENT_LBUTTONDOWN: drawing = True center = (x, y) radius = 0 elif event == cv2.EVENT_MOUSEMOVE: if drawing: # 实时更新预览圆(每次复制原图避免轨迹残留) img_copy = img.copy() dx = x - center[0] dy = y - center[1] radius = int(np.sqrt(dx**2 + dy**2)) cv2.circle(img_copy, center, radius, (0, 0, 255), 2) elif event == cv2.EVENT_LBUTTONUP: drawing = False # 绘制最终圆并标注半径 cv2.circle(img_copy, center, radius, (0, 255, 0), 2) cv2.putText( img_copy, f'Radius: {radius}', (center[0]-50, center[1]-radius-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1 ) # 使用示例 if __name__ == '__main__': img = cv2.imread('your_image_path.jpg') # 替换为你的图像路径 img_copy = img.copy() cv2.namedWindow('Interactive Circle Drawer') cv2.setMouseCallback('Interactive Circle Drawer', draw_circle) while True: cv2.imshow('Interactive Circle Drawer', img_copy) key = cv2.waitKey(1) & 0xFF if key == 27: # 按ESC键退出 break cv2.destroyAllWindows()
操作方式
- 左键按下确定圆心
- 拖拽鼠标调整半径,实时显示红色预览圆
- 松开左键完成绘制,圆变为绿色并显示半径数值
- 按ESC键退出窗口
内容的提问来源于stack exchange,提问作者Rowland
相关产品推荐
相关产品推荐

