Saturday, August 26, 2023

Displaying Image and its Histogram in Figure Canvas Tkinter

 This codes shows image and its histogram in a figure canvas Tkinter:



VERSI SATU KELAS (ONE CLASS):

import tkinter as tk
from tkinter import filedialog
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
from PIL import Image

class TampilGambar:
    def __init__(self, root):
        self.root = root
        self.root.geometry(f"{1500}x{650}")
        self.root.title("Menampilkan Gambar pada Canvas Figure")
        self.tambahkan_widgets(self.root)

    def tambahkan_widgets(self, root):
        #Menambahkan canvas widget pada root untuk menampilkan citra
        self.figure1 = Figure(figsize=(4, 4), dpi=100)
        self.figure1.patch.set_facecolor('lightgray')
        self.canvas1 = FigureCanvasTkAgg(self.figure1, master=self.root)
        self.canvas1.get_tk_widget().grid(row=0, column=1, columnspan=1, rowspan=25, padx=10, pady=10, sticky="n")

        #Menambahkan canvas widget pada root untuk menampilkan citra
        self.figure2 = Figure(figsize=(9, 6), dpi=100)
        self.figure2.patch.set_facecolor('lightgray')
        self.canvas2 = FigureCanvasTkAgg(self.figure2, master=self.root)
        self.canvas2.get_tk_widget().grid(row=0, column=2, columnspan=1, rowspan=25, padx=10, pady=10)

        #Menambahkan button widget pada root
        self.tombol = tk.Button(root, height=3, width=20, text="TAMPILKAN GAMBAR", command=self.pilih_gambar)
        self.tombol.grid(row=0, column=0, sticky='n', padx=5, pady=5)

    def pilih_gambar(self):
        self.image_path = filedialog.askopenfilename(filetypes=[("Image files", "*.png *.jpg *.jpeg *.gif *.bmp")])
        if self.image_path:
            self.tampilkan_gambar()
            self.tampilkan_histogram2()

    def array_gambar(self):
        image = Image.open(self.image_path)
        image_array = np.array(image)
        return image_array
    
    def tampilkan_gambar(self):
        self.figure1.clear()
        self.plot = self.figure1.add_subplot(1,1,1)      

        image_array = self.array_gambar()

        self.plot.imshow(image_array, aspect='auto', extent=(0, 1, 0, 1))
        self.plot.axis('off')
        self.figure1.tight_layout()
        self.canvas1.draw()    

    def hitung_histogram(self):
        image_array = self.array_gambar()

        # Calculate RGB histograms
        red_hist = np.histogram(image_array[:, :, 0], bins=256, range=(0, 256))
        green_hist = np.histogram(image_array[:, :, 1], bins=256, range=(0, 256))
        blue_hist = np.histogram(image_array[:, :, 2], bins=256, range=(0, 256))

        return red_hist, green_hist, blue_hist

    def tampilkan_histogram(self):
        self.figure2.clear()          

        red_hist, green_hist, blue_hist = self.hitung_histogram()

        # Gambarkan histogram
        self.plot1 = self.figure2.add_subplot(3,1,1)  
        self.plot1.plot(red_hist[1][:-1], red_hist[0], color='red', linewidth=2)
        self.plot1.set_facecolor("black")
        self.plot1.grid(True)
        self.plot1.set_title('Red Component')

        self.plot2 = self.figure2.add_subplot(3,1,2)  
        self.plot2.plot(green_hist[1][:-1], green_hist[0], color='green')
        self.plot2.set_facecolor("black")
        self.plot2.grid(True)
        self.plot2.set_title('Green Component')

        self.plot3 = self.figure2.add_subplot(3,1,3)  
        self.plot3.plot(blue_hist[1][:-1], blue_hist[0], color='blue')
        self.plot3.set_facecolor("black")
        self.plot3.grid(True)        
        self.plot3.set_title('Blue Component')

        self.figure2.tight_layout()
        self.canvas2.draw()

    def tampilkan_histogram2(self):
        self.figure2.clear()          

        red_hist, green_hist, blue_hist = self.hitung_histogram()

        # Gambarkan histogram
        self.plot = self.figure2.add_subplot(1,1,1)  
        self.plot.bar(red_hist[1][:-1], red_hist[0], color='red', linewidth=3, label="Red")
        self.plot.bar(green_hist[1][:-1], green_hist[0], color='green', linewidth=3, label="Green")
        self.plot.bar(blue_hist[1][:-1], blue_hist[0], color='blue', linewidth=3, label="Blue")
        self.plot.set_facecolor("black")
        self.plot.grid(True)
        self.plot.legend()
        self.plot.set_title('Image Histogram')
        self.plot.set_xlabel("Intensitas")
        self.plot.set_ylabel("Frekuensi")
        self.figure2.tight_layout()
        self.canvas2.draw()

if __name__ == "__main__":
    root=tk.Tk()
    app = TampilGambar(root)
    root.mainloop()


VERSI EMPAT KELAS (FOUR CLASSES):

#gambar_kelas
import tkinter as tk
import numpy as np
from tkinter import filedialog
from design_jendela import Design_Jendela
from helper_tampil import Helper_Tampil

class TampilGambar:
    def __init__(self, root):
        self.inisialisasi()

    def inisialisasi(self):
        self.root = root
        lebar = 1500
        tinggi = 650
        self.root.geometry(f"{lebar}x{tinggi}")
        self.root.title("Menampilkan Gambar pada Canvas")
        self.tambahkan_widgets()
        self.obj_tampil = Helper_Tampil()

    def tambahkan_widgets(self):
        self.obj_jendela = Design_Jendela()
        self.obj_jendela.tambahkan_widgets(self.root)
        self.obj_jendela.tombol.config(command=self.pilih_citra)
 
    def pilih_citra(self):
        path = filedialog.askopenfilename(filetypes=[("Image Files", "*.png *.jpg *.jpeg *.gif *.bmp")])
        if path:
            self.obj_tampil.tampilkan_citra(path, self.obj_jendela.figure1, self.obj_jendela.canvas1)
            self.obj_tampil.tampilkan_histogram(path, self.obj_jendela.figure2, self.obj_jendela.canvas2, mode=2)

if __name__ == "__main__":
    root = tk.Tk()
    app = TampilGambar(root)
    root.mainloop()

#helper_citra.py
from PIL import Image
import numpy as np

class Helper_Citra:  
    def array_citra(self, path):
        citra = Image.open(path)
        arr_citra = np.array(citra)
        return arr_citra
    
    def hitung_histogram(self, path):
        arr_citra = self.array_citra(path)

        #Menghitung histogram tiap kanal RGB
        red_hist = np.histogram(arr_citra[:, :, 0], bins=256, range=(0,256))
        green_hist = np.histogram(arr_citra[:, :, 1], bins=256, range=(0,256))
        blue_hist = np.histogram(arr_citra[:, :, 2], bins=256, range=(0,256))

        return red_hist, green_hist, blue_hist

#design_jendela
import tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

class Design_Jendela:
    def tambahkan_widgets(self, root):
        #Menambahkan canvas widget pada root untuk citra digital
        self.figure1 = Figure(figsize=(4, 4), dpi=100, facecolor="lightgray")
        self.canvas1 = FigureCanvasTkAgg(self.figure1, master=root)
        self.canvas1_widget = self.canvas1.get_tk_widget()
        self.canvas1_widget.grid(row=0, column=1, columnspan=1, rowspan=25, padx=10, pady=10, sticky="n")

        #Menambahkan button widget pada root
        self.tombol = tk.Button(root, height=2, width=20, text="TAMPILKAN GAMBAR")
        self.tombol.grid(row=0, column=0, sticky='n', padx=5, pady=5)

        #Menambahkan canvas widget pada root untuk histogram
        self.figure2 = Figure(figsize=(9, 6), dpi=100, facecolor="lightgray")
        self.canvas2 = FigureCanvasTkAgg(self.figure2, master=root)
        self.canvas2_widget = self.canvas2.get_tk_widget()
        self.canvas2_widget.grid(row=0, column=2, columnspan=1, rowspan=25, padx=10, pady=10, sticky="n")   

#helper_tampil
from helper_citra import Helper_Citra

class Helper_Tampil:
    def __init__(self):
        self.obj = Helper_Citra()

    def tampilkan_citra(self, path, figure, canvas):        
        figure.clear()
        plot = figure.add_subplot(1,1,1)
        arr_citra = self.obj.array_citra(path)
        plot.imshow(arr_citra, aspect='auto')
        plot.axis('off')
        figure.tight_layout()
        canvas.draw()

    def tampilkan_histogram(self, path, figure, canvas, mode=1):
        figure.clear()

        red_hist, green_hist, blue_hist = self.obj.hitung_histogram(path)

        if mode == 1:
            plot1 = figure.add_subplot(3, 1, 1)
            plot1.plot(red_hist[1][:-1], red_hist[0], color="red", linewidth=3)
            plot1.set_facecolor("black")
            plot1.grid(True)
            plot1.set_title("Komponen Red")

            plot2 = figure.add_subplot(3, 1, 2)
            plot2.plot(green_hist[1][:-1], green_hist[0], color="green", linewidth=3)
            plot2.set_facecolor("black")
            plot2.grid(True)
            plot2.set_title("Komponen Green")

            plot3 = figure.add_subplot(3, 1, 3)
            plot3.plot(blue_hist[1][:-1], blue_hist[0], color="blue", linewidth=3)
            plot3.set_facecolor("black")
            plot3.grid(True)
            plot3.set_title("Komponen Blue")
        elif mode == 2:
            plot = figure.add_subplot(1, 1, 1)
            plot.plot(red_hist[1][:-1], red_hist[0], color="red", linewidth=3, label="Red")
            plot.plot(green_hist[1][:-1], green_hist[0], color="green", linewidth=3,  label="Green")
            plot.plot(blue_hist[1][:-1], blue_hist[0], color="blue", linewidth=3,  label="Blue")
            plot.set_facecolor("black")
            plot.grid(True)
            plot.legend()
            plot.set_title("Image Histogram")
            plot.set_xlabel("Intensitas")
            plot.set_ylabel("Frekuensi")

        figure.tight_layout()
        canvas.draw()



No comments:

Post a Comment