matplotlib - 以十六进制格式显示图像颜色

时间:2021-04-30 22:01:14

标签: matplotlib

我想 imshow 以十六进制格式显示当前图像像素值,默认情况下它以十进制格式显示像素。

例如,红色将显示为 (255,0,0),我希望它是 (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

1 个答案:

答案 0 :(得分:1)

您可以连接一个函数 motion_notify_event 并更新工具栏。这是一个独立的示例:

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