如何从matplotlib pyplot生成的图像中提取图像像素坐标到2元组的列表



我正在处理一个python图像处理文件,在该文件中,我需要从一个起始图像生成一个ROI图像。

要做到这一点,我希望用户可以使用从左上到右下的逻辑手动输入ROI的点坐标,或者使用鼠标左键点击2次进入所示起始图像的matplotlib-pyplot图。

出于缩短的原因,我省略了手动ROI创建部分和ROI图,因为我的问题只与鼠标点击点坐标提取有关

在网站上搜索时,我遇到了这个问题,它展示了如何通过点击绘图来存储一对点的点坐标元组。事实上,它是在一个简单的绘图中完成的,而不是在图像中,我现在不知道如何在图像绘图中实现相同的功能。

网站上的问题是:使用matplotlib 存储鼠标点击事件坐标

根据我在发布的链接上发现的内容,我试图实现的代码是:

# import the necessary packages
import cv2 as cv
import matplotlib.pyplot as plt
image=".\Esercizi_da_consegnare\Avanzato\aaa\DSCF0336.jpg"
# Simple mouse click function to store coordinates
def onclick(event):
global ix, iy
ix, iy = event.xdata, event.ydata
x_int=int(ix)
y_int=int(iy)
# print 'x = %d, y = %d'%(
#     ix, iy)
# assign global variable to access outside of function
global coords
coords.append((x_int,y_int))

# Disconnect after 2 clicks
if len(coords) == 2:
image.mpl_disconnect(cid)
plt.close(1)
return
cv.imread(image, cv.IMREAD_GRAYSCALE)
plt.imshow(image, cmap="gray")
plt.show()
coords = []
# Call click func
cid = image.mpl_connect('button_press_event', onclick)
plt.show()
print(coords)

显然,使存储操作起作用的.mpl_connect(...).mpl_disconnect(...)plt.imshow(...)不起作用。我希望这能适用于作为矩阵加载的图像,因此我希望可以提取像素坐标,即每个像素的行/列索引,如果在浮点坐标点位置进行单击,则可以将其转换为整数,方法与fig.ax(...)方法相同。

我自己在matplotlib的事件处理和交互式图形文档中找到了解决方案(但我认为如果我阅读了基本图形编码,我会得到相同的结果):

https://matplotlib.org/stable/users/explain/event_handling.html

https://matplotlib.org/stable/users/explain/interactive.html

关键是初始化图形,然后创建具有单个绘图的子绘图,然后将图像加载到该绘图中,这样就可以使用.canvas.mpl_connect()disconnect()

这是代码:

# import the necessary packages
import cv2 as cv
import matplotlib.pyplot as plt
image_path=".\Esercizi_da_consegnare\Avanzato\aaa\DSCF0336.jpg"
image=cv.imread(image_path, cv.IMREAD_GRAYSCALE)
fig,ax=plt.subplots()
plt.subplot(1,1,1)
plt.imshow(image, cmap="gray")
coords = []
# Simple mouse click function to store coordinates
def onclick(event):
global ix, iy
ix, iy = event.xdata, event.ydata
x_int=int(ix)
y_int=int(iy)

# assign global variable to access outside of function
global coords
coords.append((x_int,y_int))

# Disconnect after 2 clicks
if len(coords) == 2:
fig.canvas.mpl_disconnect(cid)
plt.close(1)
return
# Call click func
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show(block=True)
print(coords)

最新更新