Skip to content

S-Rabbit81/Somayeh-Komeylian-Computer-Vision-Digital-Memorial-Albums-with-Python-Codes

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 

Repository files navigation

Provided by Somayeh Komeylian: PhD Student at UCSD & SDSU

Computer Vision - Digital Memorial Albums with Python Codes

Please save all files (a Jupyter file, the images and a movie) in the given Zip code here first in the same folder, then run the second cell of the Jupyter file

import tkinter as tk from PIL import Image, ImageTk import os import cv2 import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

--- Configuration ---

Use forward slashes for cross-platform compatibility

image_files = [ r'C:/Users/komey/OneDrive/Desktop/Summer_classes/Computer Vision/Final Project/image1.jpg', r'C:/Users/komey/OneDrive/Desktop/Summer_classes/Computer Vision/Final Project/image2.jpg', r'C:/Users/komey/OneDrive/Desktop/Summer_classes/Computer Vision/Final Project/image3.jpg', r'C:/Users/komey/OneDrive/Desktop/Summer_classes/Computer Vision/Final Project/image4.jpg', r'C:/Users/komey/OneDrive/Desktop/Summer_classes/Computer Vision/Final Project/image5.jpg', r'C:/Users/komey/OneDrive/Desktop/Summer_classes/Computer Vision/Final Project/image6.jpg', r'C:/Users/komey/OneDrive/Desktop/Summer_classes/Computer Vision/Final Project/image7.jpg', r'C:/Users/komey/OneDrive/Desktop/Summer_classes/Computer Vision/Final Project/image8.jpg', r'C:/Users/komey/OneDrive/Desktop/Summer_classes/Computer Vision/Final Project/image9.jpg' ]

Path to the loading movie file

loading_movie_path = r'C:/Users/komey/OneDrive/Desktop/Summer_classes/Computer Vision/Final Project/loading.mp4'

Set the delay in milliseconds for 5 seconds for the image slideshow

delay_milliseconds = 5 * 1000 # 5 seconds = 5000 milliseconds

--- Global variables to manage the slideshow state and image references ---

current_image_index = 0 image_labels = {} # Dictionary to hold the labels for each channel

--- Matplotlib setup ---

Create a Matplotlib figure for the histogram plot

fig, ax = plt.subplots(figsize=(6, 4), tight_layout=True) ax.set_title("BGR Histogram") ax.set_xlabel("Pixel Value") ax.set_ylabel("Frequency") ax.grid(True)

--- Tkinter setup ---

root = tk.Tk() root.title("Loading Movie and Image Slideshow with Histograms")

--- Function to handle key presses ---

def key_handler(event): """Handles keyboard events, primarily for quitting the application.""" if event.char == 'q': # Release the video capture object before destroying the window if 'video_cap' in globals() and video_cap.isOpened(): video_cap.release() root.destroy()

--- Function to update and display the next image ---

def update_image(): """Loads the next image, splits it into channels, updates the labels, and plots the histogram.""" global current_image_index global image_labels if not image_files: print("Error: No image files specified.") return

image_path = image_files[current_image_index]
try:
    img = cv2.imread(image_path)
    if img is None:
        print(f"Error: Could not read image from path {image_path}")
        current_image_index = (current_image_index + 1) % len(image_files)
        root.after(delay_milliseconds, update_image)
        return
except Exception as e:
    print(f"An error occurred while loading image {image_path}: {e}")
    current_image_index = (current_image_index + 1) % len(image_files)
    root.after(delay_milliseconds, update_image)
    return

# Resize the image for display
display_width = 400
display_height = 300
resized_img = cv2.resize(img, (display_width, display_height), interpolation=cv2.INTER_AREA)

# Split the image into B, G, R channels
B, G, R = cv2.split(resized_img)
zeros = np.zeros_like(G)
blue = cv2.merge([B, zeros, zeros])
green = cv2.merge([zeros, G, zeros])
red = cv2.merge([zeros, zeros, R])

def to_photoimage(cv2_image):
    img_rgb = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2RGB)
    pil_image = Image.fromarray(img_rgb)
    return ImageTk.PhotoImage(pil_image)

photos = {
    'Original': to_photoimage(resized_img),
    'Blue': to_photoimage(blue),
    'Green': to_photoimage(green),
    'Red': to_photoimage(red)
}

if not image_labels:
    for widget in root.winfo_children():
        widget.destroy()
    
    main_frame = tk.Frame(root)
    main_frame.pack(padx=10, pady=10)

    titles = ['Original', 'Blue', 'Green', 'Red']
    for i, title in enumerate(titles):
        row = i // 2
        col = i % 2
        label_frame = tk.Frame(main_frame)
        label_frame.grid(row=row, column=col, padx=5, pady=5)
        image_label = tk.Label(label_frame, image=photos[title])
        image_label.pack()
        title_label = tk.Label(label_frame, text=title)
        title_label.pack()
        image_labels[title] = image_label
        
    # Create a new frame for the histogram plot
    histogram_frame = tk.Frame(root)
    histogram_frame.pack(padx=10, pady=10)
    
    # Embed the matplotlib figure into the Tkinter frame
    canvas = FigureCanvasTkAgg(fig, master=histogram_frame)
    canvas.draw()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    # Optional: Add a toolbar for the plot
    toolbar = NavigationToolbar2Tk(canvas, histogram_frame)
    toolbar.update()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
    
else:
    for title in ['Original', 'Blue', 'Green', 'Red']:
        image_labels[title].config(image=photos[title])
        image_labels[title].image = photos[title]
        
# Calculate and plot the histogram for each channel
ax.clear()  # Clear the previous plot
colors = ('b', 'g', 'r')
for i, col in enumerate(colors):
    hist = cv2.calcHist([resized_img], [i], None, [256], [0, 256])
    ax.plot(hist, color=col)

ax.set_title("BGR Histogram")
ax.set_xlabel("Pixel Value")
ax.set_ylabel("Frequency")
ax.grid(True)

fig.canvas.draw()

current_image_index = (current_image_index + 1) % len(image_files)
root.after(delay_milliseconds, update_image)

--- Functions for playing the loading video ---

def play_video(): """Starts playing the loading movie.""" global video_cap, video_label, loading_label # Create a frame to hold both the video and the loading text loading_frame = tk.Frame(root) loading_frame.pack(fill="both", expand=True)

# Create and pack the loading label
loading_label = tk.Label(loading_frame, text="Loading Digital Memorial Albums\n Computer Vision in Tehran Institute of Technology" , font=("Helvetica", 24), fg="white", bg="green")
loading_label.pack(pady=20)

# Create and pack the video label within the same frame
video_label = tk.Label(loading_frame)
video_label.pack()

video_cap = cv2.VideoCapture(loading_movie_path)
if not video_cap.isOpened():
    print(f"Error: Could not open video file {loading_movie_path}. Starting slideshow immediately.")
    loading_frame.destroy()
    update_image()
    return
update_frame()

def update_frame(): """Reads a new frame and updates the video label.""" global video_cap, video_label ret, frame = video_cap.read() if ret: # Resize frame to a fixed size to avoid resizing issues display_width = 640 display_height = 480 resized_frame = cv2.resize(frame, (display_width, display_height)) frame_rgb = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2RGB) pil_img = Image.fromarray(frame_rgb) tk_img = ImageTk.PhotoImage(image=pil_img) video_label.config(image=tk_img) video_label.image = tk_img fps = video_cap.get(cv2.CAP_PROP_FPS) if fps > 0: frame_delay = int(1000 / fps) else: frame_delay = 30 root.after(frame_delay, update_frame) else: video_cap.release() print("Video finished. Starting image slideshow.") # Destroy the loading frame and its contents (including the label) for widget in root.winfo_children(): widget.destroy() update_image()

--- Main execution ---

if name == 'main': root.bind('', key_handler) play_video() root.mainloop()

About

Computer Vision-Digital Memorial Albums with Python Codes

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published