[英]Get RGB value from a pixel
I am working on a problem in which I am plotting a GeoTIFF image using matplotlib.我正在解决一个问题,我正在使用 matplotlib 绘制 GeoTIFF 图像。 I want to implement a function such that when I click on the image, the function must return the RGB value of the pixel on which I clicked, using matplotlib only.
我想实现一个函数,当我单击图像时,该函数必须返回我单击的像素的 RGB 值,仅使用 matplotlib。
I had seen all the previous solutions provided on Stack Overflow, none of those worked for me.我已经看过 Stack Overflow 上提供的所有以前的解决方案,但没有一个对我有用。
Here is my code:这是我的代码:
src = rasterio.open("rgb.tif")
src1 = rasterio.plot.reshape_as_image(src.read())
#segments = quickshift(image, ratio=1, kernel_size=20, max_dist=80,
#return_tree=False, sigma=0, convert2lab=True, random_seed=42
def onclick(event):
print(event)
global ix, iy
global area
area = 7
ix, iy = event.xdata, event.ydata
print ('ix ',ix)
print ("iy ",iy)
#X = '${}$'.format(ix)
#Y = '${}$'.format(iy)
datacursor(bbox=dict(fc='white'),formatter="longitude:{x:.2f}\nlatitude:{y:.2f}\ncolor:{z}".format)
return
#print ("color ",image[int(event.xdata)][int(event.ydata)])
fig,ax = plt.subplots()
graph1 = show(src.read(), transform=src.transform , ax = ax)
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
Suppose im = plt.imshow(data)
is an image you plot.假设
im = plt.imshow(data)
是您绘制的图像。 Then, if data
is a numpy array from a three channel tif image, the RGB values of coordinates i,j
is data[j,i,:]
.然后,如果
data
是来自三通道 tif 图像的 numpy 数组,则坐标i,j
的 RGB 值为data[j,i,:]
。 If data
is a single channel image, it would be plotted with a colormap.如果
data
是单通道图像,则将使用颜色图进行绘制。 In that case, the RGB value is im.cmap(im.norm(data[j,i]))
.在这种情况下,RGB 值为
im.cmap(im.norm(data[j,i]))
。
If you want to retrieve the RGB-value of a pixel you could use the following:如果要检索像素的 RGB 值,可以使用以下命令:
def onclick(event):
r, g, b = event.inaxes.get_images()[0].get_cursor_data(event)[:3]
print([r, g, b])
This way you don't need to use complicated indexing and you can also zoom-in and find the RGB-values这样您就不需要使用复杂的索引,您还可以放大并找到 RGB 值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.