0% found this document useful (0 votes)
18 views

CV-Mini Project 2

hvnnfssdbjnfws

Uploaded by

faisalaliansari7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

CV-Mini Project 2

hvnnfssdbjnfws

Uploaded by

faisalaliansari7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Quaid-E-Awam University Of Engineering, Science &

Technology, Nawabshah.

Thesis For Image Enhancer Project

Name : Faisal Rehman

Roll no : 21ai47

Semester / Year : 6th Semester

Department : Artificial Intelligence

Subject Teacher : Sir Asghar Chandio

Date : 12-Aug-2024

1 |21AI47
Thesis: Enhancing Images Using Python: A Practical
Implementation
Abstract
This thesis presents a practical implementation of an image enhancement application using
Python. The application utilizes OpenCV's Deep Learning Super-Resolution (DNN-SR) model
to upscale images and improve their quality. It integrates various image processing
techniques, including CLAHE (Contrast Limited Adaptive Histogram Equalization) and
bilateral filtering, and provides a graphical user interface (GUI) for user interaction. The
project demonstrates the capability of Python in handling advanced image processing tasks
with a user-friendly interface.

Introduction
With the advent of digital imaging, the need for high-quality images has increased
significantly. Image enhancement is a crucial aspect of improving image quality, especially
for applications requiring clear and detailed visuals. This thesis explores the development of
a Python-based image enhancement tool that allows users to upscale and improve images
using advanced algorithms and a stylish GUI.

Objectives
Develop an Image Enhancement Tool:

Implement a Python application that uses DNN-SR models to upscale images.

Integrate additional image processing techniques to further enhance the image quality.

Create a User-Friendly GUI:

Design a GUI that allows users to select, enhance, and save images with ease.

Ensure Quality and Performance:

Optimize the application for quality and performance, ensuring enhanced images are clear
and accurately processed.

2 |21AI47
Methodology
1. Image Processing Techniques:

Deep Learning Super-Resolution (DNN-SR): The ESPCN_x4.pb model, part of the Efficient Sub-
Pixel Convolutional Network (ESPCN) architecture, is designed for high-performance image super-
resolution tasks. This model leverages deep learning techniques to enhance image resolution by a
factor of four, effectively reconstructing finer details and textures that are typically lost in low-
resolution images. By utilizing sub-pixel convolution layers, the ESPCN optimally processes features
at multiple scales, enabling it to produce high-quality upscaled images with minimal artifacts. This
model is particularly valuable in applications such as digital photography, video enhancement, and
medical imaging, where clarity and detail are paramount. Its efficiency and effectiveness make it a
popular choice for researchers and developers working in the field of computer vision and image
processing.

CLAHE (Contrast Limited Adaptive Histogram Equalization): Applied to improve image


contrast and visibility. The CLAHE effect is fine-tuned to 30% opacity to balance
enhancement and natural appearance.

Bilateral Filtering: Used to reduce noise while maintaining edge sharpness, enhancing the
overall image quality.

2. GUI Development:

Toolkit Used: Tkinter and ThemedTk libraries are used to create a stylish and functional GUI.

Features:

Image Selection: Users can select images from their filesystem.

Image Enhancement: Apply enhancement algorithms to the selected image.

Image Saving: Save the enhanced image with a unique, random filename to avoid
overwriting.

Implementation
Import Required Libraries:

import cv2

import numpy as np

import os

import tkinter as tk

3 |21AI47
from tkinter import filedialog, messagebox, ttk

from PIL import Image, ImageTk

from ttkthemes import ThemedTk

import uuid

Class Definition: The ImageEnhancer class encapsulates the functionality for loading,
processing, and saving images, as well as the GUI components.

GUI Components:

Select Image Button: Opens a file dialog to choose an image.

Enhance Image Button: Processes the selected image using the enhancement algorithms.

Save Image Button: Saves the processed image with a unique, random filename.

Image Processing Functions:

Image Upscaling:

def upscale_image(self, image, scale_factor):

height, width = image.shape[:2]

new_dimensions = (int(width * scale_factor), int(height * scale_factor))

upscaled_image = cv2.resize(image, new_dimensions, interpolation=cv2.INTER_CUBIC)

return upscaled_image

Blending and CLAHE Application:

def blend_images(self, image1, image2, opacity):

blended_image = cv2.addWeighted(image1, 1 - opacity, image2, opacity, 0)

return blended_image

Saving Images with Random Names:

def save_image(self):

if hasattr(self, 'enhanced_image'):

4 |21AI47
output_folder = 'Enhanced'

os.makedirs(output_folder, exist_ok=True)

random_filename = f"{uuid.uuid4().hex}.jpg"

output_path = os.path.join(output_folder, random_filename)

cv2.imwrite(output_path, self.enhanced_image)

messagebox.showinfo("Success", f"Enhanced image saved at {output_path}")

Results

Screenshots:

Here is Full Image Before & After Results.

Before After

And this is Zoomed One Before & After Result.

5 |21AI47
Before After

GUI Screenshot:

Shows the main interface with buttons for selecting and processing images.

Here is What Happen When you Select Image.

6 |21AI47
After selecting Image we Click to Enhance Image.

You can see live results in this tkinter Window.

7 |21AI47
Performance:
The application successfully enhances image quality by upscaling and applying advanced
filtering techniques.

The GUI provides an intuitive and seamless user experience.

Conclusion:
This Python-based image enhancement tool demonstrates the effectiveness of modern
image processing techniques and their integration into a user-friendly application. The use
of DNN-SR for upscaling, combined with CLAHE and bilateral filtering, results in improved
image quality, making this tool a valuable asset for users seeking high-quality image
enhancements.

8 |21AI47
Full Code
import cv2

import numpy as np

import os

import tkinter as tk

from tkinter import filedialog, messagebox, ttk

from PIL import Image, ImageTk

from ttkthemes import ThemedTk

import uuid

class ImageEnhancer:

def __init__(self, root):

self.root = root

self.root.title("Image Enhancer")

self.image_path = None

self.enhanced_image = None

# Create GUI components with styles

self.style = ttk.Style()

self.style.configure('TButton', font=('Helvetica', 12), padding=10)

self.style.configure('TLabel', font=('Helvetica', 12), padding=10)

# Create a frame for the image and buttons

self.frame = ttk.Frame(root, padding="10")

self.frame.pack(fill=tk.BOTH, expand=True)

9 |21AI47
self.select_image_button = ttk.Button(self.frame, text="Select Image",
command=self.load_image)

self.select_image_button.pack(pady=10)

self.enhance_button = ttk.Button(self.frame, text="Enhance Image",


command=self.enhance_image, state=tk.DISABLED)

self.enhance_button.pack(pady=10)

self.save_button = ttk.Button(self.frame, text="Save Enhanced Image",


command=self.save_image, state=tk.DISABLED)

self.save_button.pack(pady=10)

self.image_label = ttk.Label(self.frame)

self.image_label.pack(pady=10)

def load_image(self):

file_path = filedialog.askopenfilename(filetypes=[("Image Files", "*.jpg;*.jpeg;*.png")])

if file_path:

self.image_path = file_path

self.show_image(file_path)

self.enhance_button.config(state=tk.NORMAL)

def show_image(self, image_path):

image = Image.open(image_path)

max_width, max_height = 400, 400

width, height = image.size

if width > height:

new_width = max_width

10 |21AI47
new_height = int((max_width / width) * height)

else:

new_height = max_height

new_width = int((max_height / height) * width)

image = image.resize((new_width, new_height), Image.LANCZOS)

self.tk_image = ImageTk.PhotoImage(image)

self.image_label.config(image=self.tk_image)

def enhance_image(self):

if self.image_path:

image = cv2.imread(self.image_path)

if image is None:

messagebox.showerror("Error", "Could not load the image.")

return

print("Original image dimensions:", image.shape)

# Create a DNN Super-Resolution object

sr = cv2.dnn_superres.DnnSuperResImpl_create()

model_path = "models/ESPCN_x4.pb"

if not os.path.exists(model_path):

messagebox.showerror("Error", f"Could not find the model at {model_path}")

return

try:

11 |21AI47
sr.readModel(model_path)

sr.setModel("espcn", 4)

print("Model loaded and set to x4 upscale.")

except cv2.error as e:

messagebox.showerror("Error", f"Failed to load the model - {e}")

return

intermediate_image = sr.upsample(image)

print("After 4x upscaling dimensions:", intermediate_image.shape)

final_upscaled_image = self.upscale_image(intermediate_image, 1.5)

print("After 1.5x upscaling dimensions:", final_upscaled_image.shape)

filtered_image = cv2.bilateralFilter(final_upscaled_image, d=9, sigmaColor=75,


sigmaSpace=75)

filter_opacity = 0.50

blended_image = self.blend_images(final_upscaled_image, filtered_image, filter_opacity)

lab_image = cv2.cvtColor(blended_image, cv2.COLOR_BGR2LAB)

l_channel, a_channel, b_channel = cv2.split(lab_image)

clahe = cv2.createCLAHE(clipLimit=10.0, tileGridSize=(8, 8))

cl_l_channel = clahe.apply(l_channel)

clahe_enhanced_image = cv2.merge((cl_l_channel, a_channel, b_channel))

clahe_enhanced_image = cv2.cvtColor(clahe_enhanced_image, cv2.COLOR_LAB2BGR)

clahe_opacity = 0.20

12 |21AI47
final_image = self.blend_images(blended_image, clahe_enhanced_image, clahe_opacity)

sharpen_kernel = np.array([[0, -0.5, 0],

[-0.5, 3, -0.5],

[0, -0.5, 0]])

final_image = cv2.filter2D(final_image, -1, sharpen_kernel)

self.enhanced_image = final_image

self.save_button.config(state=tk.NORMAL)

self.show_image_from_cv(final_image)

def upscale_image(self, image, scale_factor):

height, width = image.shape[:2]

new_dimensions = (int(width * scale_factor), int(height * scale_factor))

upscaled_image = cv2.resize(image, new_dimensions, interpolation=cv2.INTER_CUBIC)

return upscaled_image

def blend_images(self, image1, image2, opacity):

blended_image = cv2.addWeighted(image1, 1 - opacity, image2, opacity, 0)

return blended_image

def show_image_from_cv(self, cv_image):

image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)

image = Image.fromarray(image)

max_width, max_height = 400, 400

width, height = image.size

13 |21AI47
if width > height:

new_width = max_width

new_height = int((max_width / width) * height)

else:

new_height = max_height

new_width = int((max_height / height) * width)

image = image.resize((new_width, new_height), Image.LANCZOS)

self.tk_image = ImageTk.PhotoImage(image)

self.image_label.config(image=self.tk_image)

def save_image(self):

if hasattr(self, 'enhanced_image'):

output_folder = 'Enhanced'

os.makedirs(output_folder, exist_ok=True)

random_filename = f"{uuid.uuid4().hex}.jpg"

output_path = os.path.join(output_folder, random_filename)

cv2.imwrite(output_path, self.enhanced_image)

messagebox.showinfo("Success", f"Enhanced image saved at {output_path}")

if __name__ == "__main__":

# Create a themed tkinter window

root = ThemedTk(theme="arc") # You can choose other themes from 'ttkthemes'

app = ImageEnhancer(root)

root.mainloop()

14 |21AI47
Future Work:
Algorithm Optimization: Explore additional algorithms and techniques for further image
improvement.

Extended Features: Include options for adjusting filter parameters and other advanced
image processing functions.

Cross-Platform Compatibility: Ensure the application works seamlessly across different


operating systems.

15 |21AI47

You might also like