Reputation: 1
I am working on a problem in which I am plotting a GeoTIFF image using matplotlib. 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.
I had seen all the previous solutions provided on Stack Overflow, none of those worked for me.
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()
Upvotes: 0
Views: 1654
Reputation: 412
If you want to retrieve the RGB-value of a pixel you could use the following:
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
Upvotes: 0
Reputation: 339230
Suppose
im = plt.imshow(data)
is an image you plot. Then, if data
is a numpy array from a three channel tif image, the RGB values of coordinates i,j
is data[j,i,:]
. If data
is a single channel image, it would be plotted with a colormap. In that case, the RGB value is im.cmap(im.norm(data[j,i]))
.
Upvotes: 2