lucky1928
lucky1928

Reputation: 8905

matplotlib - show image color in hex format

I would like imshow display current image pixel value in hex format, by default it display pixel with decimal format.

for example, red color will be displayed as (255,0,0), I would like it to be (FF,00,00).

#!/usr/bin/env python3
import matplotlib.pyplot as plt
import matplotlib.image as image
import matplotlib.patches as patches
import matplotlib
import cv2
matplotlib.use('tkagg')

img = cv2.imread("input.png",cv2.IMREAD_UNCHANGED)# cv2.IMREAD_UNCHANGED load alpha channel
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
fig,ax =plt.subplots(1,figsize=(15,15))
ax.imshow(img)

fig.tight_layout()
plt.show()

enter image description here

Upvotes: 0

Views: 415

Answers (1)

JohanC
JohanC

Reputation: 80459

You could connect a function the motion_notify_event and update the toolbar. Here is a standalone example:

import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib

def show_hex_coords(event):
    text = ''
    rgb = img_plot.get_cursor_data(event)
    if rgb is not None:
        r, g, b = rgb
        text = f'x={event.xdata:.0f} y={event.ydata:.0f}\n{r:02X} {g:02X} {b:02X}'
        # print( f'#{r:02X}{g:02X}{b:02X}')
    fig.canvas.toolbar.set_message(text)

matplotlib.use('tkagg')

with cbook.get_sample_data('grace_hopper.jpg') as image_file:
    img = plt.imread(image_file)

fig, ax = plt.subplots(1, figsize=(6, 6))
img_plot = ax.imshow(img)

fig.canvas.mpl_connect("motion_notify_event", show_hex_coords)
plt.show()

showing rgb while hovering

Upvotes: 1

Related Questions