尝试在tkinter窗口上显示matplotlib图像直方图

weylhg0b  于 2023-01-09  发布在  其他
关注(0)|答案(1)|浏览(159)

试图输出一个颜色直方图从输入的图像到一个tkinter的图形用户界面窗口,但找不到任何建议。看到的方法,把其他图表,但不是特别直方图。感谢您的任何建议!

import imageio.v3 as iio
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg)
from tkinter import *

image = iio.imread(uri = (r"C:\Users\System_2\Sample_image.PNG"))

def histogram():
    # tuple to select colors of each channel line
    colors = ("red", "green", "blue")

# create the histogram plot, with three lines, one for
# each color
plt.figure()
plt.xlim([0, 256])
for channel_id, color in enumerate(colors):
    histogram, bin_edges = np.histogram(
        image[:, :, channel_id], bins=256, range=(0, 2000)
    )
    plt.plot(bin_edges[0:-1], histogram, color=color)

#axis labels
plt.xlabel("Color value")
plt.ylabel("Pixel count")

#plots the histogram in a matplotlib GUI
plt.plot(bin_edges[0:-1], histogram)
plt.show()

histogram()

#tkinter gui
def window():
    root = Tk()
    root.geometry("500x400")
    root.title("Histogram")

    root.mainloop()

window()

能够输出其他图形的GUI窗口,但只是不能让它与这个颜色直方图。似乎总是得到错误,修复他们,并得到一个不同的错误。此外,找不到任何与直方图和tkinter在线。感谢任何帮助,你可以给予

z0qdvdin

z0qdvdin1#

1.保存matplotlib图像

image_name = "Temporary Image.png"
plt.savefig(image_name)
plt.close()

1.在tkinter窗口中绘制图像

pic = PhotoImage(file = image_name)
image_label = Label(root, image = pic)
image_label.pack()

1.使用os模块删除映像

import os
os.remove(image_name)

下面是完整的代码

import imageio.v3 as iio
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg)
from tkinter import *
import os

image = iio.imread(uri = (r"C:\Users\System_2\Sample_image.PNG"))

# tuple to select colors of each channel line
colors = ("red", "green", "blue")

# create the histogram plot, with three lines, one for each color
plt.figure()
plt.xlim([0, 256])
for channel_id, color in enumerate(colors):
    histogram, bin_edges = np.histogram(image[:, :, channel_id], bins=256, range=(0, 2000))
    plt.plot(bin_edges[0:-1], histogram, color=color)

#axis labels
plt.xlabel("Color value")
plt.ylabel("Pixel count")

#plots the histogram in a matplotlib GUI
plt.plot(bin_edges[0:-1], histogram)
image_name = "Temporary Image.png"
plt.savefig(image_name)
plt.close()

#tkinter gui
def window():
    root = Tk()
    root.title("Histogram")
    pic = PhotoImage(file = image_name)
    image_label = Label(root, image = pic)
    image_label.pack()
    os.remove(image_name)
    root.mainloop()

window()

相关问题