im1 = cv2.imread(imgpath)##imgpath为图像路径
fig = plt.figure()
def call_back(event):
axtemp = event.inaxes
base_scale=2
x_min, x_max = axtemp.get_xlim()##获取x轴范围
y_min, y_max = axtemp.get_ylim()##获取y轴范围
fanwei_x = (x_max - x_min)/2#范围缩放
fanwei_y = (y_max - y_min)/2
xdata = event.xdata # get event x location
ydata = event.ydata # get event y location
if event.button == 'up':
# deal with zoom in
scale_factor = 1 / base_scale
elif event.button == 'down':
# deal with zoom out
scale_factor = base_scale
else:
# deal with something that should never happen
scale_factor = 1
print( event.button)
axtemp.set(xlim=(xdata - fanwei_x*scale_factor, xdata + fanwei_x *scale_factor))
axtemp.set(ylim=(ydata - fanwei_y*scale_factor , ydata +fanwei_y*scale_factor))
# axtemp.set(ylim=(ydata - fanwei_y*2, ydata + fanwei_y*2))
fig.canvas.draw_idle() # 绘图动作实时反映在图像上
fig.canvas.mpl_connect('scroll_event', call_back)
fig.canvas.mpl_connect('button_press_event', call_back)
plt.imshow(im1)
plt,show()
本文介绍了一种使用Python的OpenCV库读取图像,并利用matplotlib库进行图像显示的方法。通过定义回调函数处理鼠标滚轮事件,实现了图像的动态缩放功能。此外,还介绍了如何响应鼠标点击事件,为图像交互提供了更多可能。
988





