Monday, August 28, 2023

TKINTER: List Widget untuk Memilih Histogram Citra yang ditampilkan

 Program berikut memiliki empat kelas terpisah dengan tujuan masing-masing. Pada kasus ini, list widget tkinter dipakai untuk memilih histogram yang akan ditampilkan. SEMANGAT BELAJAR!!!


HORAS!!!

Balige Academy

Kota Balige




SOURCE CODE:

#tkinter6.py
import tkinter as tk
from tkinter import filedialog
from design_jendela import Design_Jendela
from helper_tampil import Helper_Tampil
from PIL import Image

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")

        #Panggil metode tempatkan_widgets()
        self.tempatkan_widgets()

        #Menciptakan objek dari Helper_Tampil
        self.obj_tampil = Helper_Tampil()

        # Bind the selection event to a function
        self.obj_jendela.listbox.bind("<<ListboxSelect>>", self.pilih_list_widget)

        #Menonaktifkan list widget saat awal aplikasi dijalankan
        self.obj_jendela.listbox.config(state=tk.DISABLED)

    def pilih_list_widget(self, event):
        dipilih = self.obj_jendela.listbox.get(self.obj_jendela.listbox.curselection())
        print(dipilih)
        citra = Image.open(self.path)
        self.obj_tampil.pilih_grafik(citra, dipilih, self.obj_jendela.figure2, self.obj_jendela.canvas2)

    def tempatkan_widgets(self):       
        #Ciptakan objek dari Design_Jendela
        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):
        self.path = filedialog.askopenfilename(filetypes=[("Image Files", "*.png *.jpg *.jpeg *.gif *.bmp")])
        citra = Image.open(self.path)
        if self.path:
            self.obj_tampil.tampilkan_citra(citra, self.obj_jendela.figure1, self.obj_jendela.canvas1)
            self.obj_tampil.tampilkan_histogram2(citra, self.obj_jendela.figure2, self.obj_jendela.canvas2)

        #Mengaktifkan list widget setelah citra dipilih
        self.obj_jendela.listbox.config(state=tk.NORMAL)
             
if __name__ == "__main__":
    root = tk.Tk()
    app = TampilGambar(root)
    root.mainloop()

#helper_tampil.py
from helper_citra import Helper_Citra

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

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

    def tampilkan_histogram(self, citra, figure, canvas):
        figure.clear()

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

        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")

        figure.tight_layout()
        canvas.draw()

    def tampilkan_histogram2(self, citra, figure, canvas):
        figure.clear()

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

        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()

    def tampilkan_histogram_kanal(self, path, figure, canvas, mode="red"):
        figure.clear()

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

        plot = figure.add_subplot(1, 1, 1)
        if mode=="red":
            plot.plot(red_hist[1][:-1], red_hist[0], color="red", linewidth=3, label="Red")
        elif mode=="green":            
            plot.plot(green_hist[1][:-1], green_hist[0], color="green", linewidth=3,  label="Green")
        elif mode=="blue":
            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()        

    def pilih_grafik(self, citra, dipilih, figure, canvas):
        if dipilih == "Satu Plot":
            self.tampilkan_histogram2(citra, figure, canvas)
        elif dipilih == "Tiga Plot":
            self.tampilkan_histogram(citra, figure, canvas)

        elif dipilih == "Red":
            self.tampilkan_histogram_kanal(citra, figure, canvas, mode="red")

        elif dipilih == "Green":
            self.tampilkan_histogram_kanal(citra, figure, canvas, mode="green")

        elif dipilih == "Blue":
            self.tampilkan_histogram_kanal(citra, figure, canvas, mode="blue") 


#helper_citra.py
import numpy as np
class Helper_Citra:
    def array_citra(self, citra):        
        arr_citra = np.array(citra)
        return arr_citra
    
    def hitung_histogram(self, citra):
        arr_citra = self.array_citra(citra)
        #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.py
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)
        self.figure1.patch.set_facecolor("lightgray")
        self.canvas1 = FigureCanvasTkAgg(self.figure1, master=root)
        self.canvas1.get_tk_widget().grid(row=0, column=1, columnspan=1, rowspan=25, padx=5, pady=5, 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)
        self.figure2.patch.set_facecolor("lightgray")
        self.canvas2 = FigureCanvasTkAgg(self.figure2, master=root)
        self.canvas2.get_tk_widget().grid(row=0, column=2, columnspan=1, rowspan=25, padx=5, pady=5, sticky="n")

        #Menambahkan label
        self.label = tk.Label(root, text = "PILIH PLOT", fg = "red")
        self.label.grid(row=1, column=0, padx=5, pady=1, sticky="w")

        #Menambahkan list widget
        self.listbox = tk.Listbox(root, selectmode=tk.SINGLE, width=25)
        self.listbox.grid(row=2, column=0, sticky='n', padx=5, pady=1)

        # Menyisipkan item ke dalam list widget
        items = ["Satu Plot", "Tiga Plot", "Red", "Green", "Blue"]
        for item in items:
            self.listbox.insert(tk.END, item)

        self.listbox.config(height=len(items))            








No comments:

Post a Comment