Home>

I want to convert the image drawn in RGB of matplotlib to HSV format.
It is the contents of the program, but the color and shape are displayed randomly, and the image will be updated each time you press the button on tkinter.
Currently, RGB is expressed as 0.-1 as random.random() in order to generate colors randomly.
As you can see in the source code, I tried using matplotlib.colors.rgb_to_hsv() which is a function of the matplotlib.colors module to change from RGB to HSV, but it does not work well and I can not display the image is.
No error message is displayed.
Would you please teach me an expert person?

Applicable source code
import sys
import tkinter
import numpy as np
import random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
import matplotlib.colors as mcolors

def draw(event):
    fig = plt.figure(figsize=(4,4))
    ax=fig.gca(projection='3d')
    ax.set_xlim([-1., 1.])
    ax.set_ylim([-1., 1.])
    ax.set_zlim([-1., 1.])
    for a in [ax.xaxis, ax.yaxis, ax.zaxis]:
        a.set_ticklabels([])
        a._axinfo['grid']['linewidth'] = 0
        a._axinfo['tick']['linewidth'] = 0
    for a in [ax.w_xaxis, ax.w_yaxis, ax.w_zaxis]:
        a.line.set_linewidth(0)
        a.set_pane_color((0., 0., 0., 0.))
        # In order RGBA
    ax.set_facecolor('black')
    u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:25j]
    x = np.cos(u) * np.sin(v)
    y = np.sin(u) * np.sin(v)
    z = np.cos(v)

    R=random.random()
    G=random.random()
    B=random.random()
    colors = np.zeros((50, 25, 3))
    for i in range(0, 25):
        for j in range(0, 25):
            colors[i][j][0] = R
            colors[i][j][1] = G
            colors[i][j][2] = B
    colors2=mcolors.rgb_to_hsv(mcolors.to_rgb(colors))
    ax.plot_surface(x, y, z, facecolors = colors2, shade = False)
    moon=random.randint(-90,270)
    ax.view_init(elev = 0, azim = moon)
    canvas = FigureCanvasTkAgg(fig, master=root)
    canvas.get_tk_widget().place(x=0,y=0)
root = tkinter.Tk()
root.geometry("800x600")
root.wm_title ("Randomly display colors and shapes")
button= tkinter.Button(root, text=u'update', width=15)
button.bind("<Button-1>",draw)
button.place(x=300,y=450)
tkinter.mainloop()
  • Answer # 1

    I'm not sure if it's correct, but using the colorsys module,

    colorH,colorS,colorV = colorsys.rgb_to_hsv(a, b, c)
    print(colorH*360)
    print(colorS*100)
    print(colorV*100)


    I was able to convert successfully.
    Thank you for looking at the question and thinking.