Build GUI Application Pencil Sketch from Photo in Python

Build GUI Application Pencil Sketch from Photo in Python

Building a GUI application in Python to create a pencil sketch from a photo involves a combination of image processing and a graphical user interface (GUI). We can use OpenCV for the image processing part and Tkinter for the GUI. Here's a step-by-step guide:

Step 1: Install Required Libraries

First, ensure you have the necessary libraries: OpenCV and Pillow. You can install them using pip:

pip install opencv-python pillow 

Step 2: Image Processing Function

Create a function that converts an image to a pencil sketch using OpenCV:

import cv2 def pencil_sketch(image_path): # Read the image img = cv2.imread(image_path) # Convert to grey image grey_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Invert the grey image invert_img = cv2.bitwise_not(grey_img) # Blur the image blur_img = cv2.GaussianBlur(invert_img, (21, 21), sigmaX=0, sigmaY=0) # Invert the blurred image invblur_img = cv2.bitwise_not(blur_img) # Sketch sketch_img = cv2.divide(grey_img, invblur_img, scale=256.0) return sketch_img 

Step 3: Building the GUI with Tkinter

Now, let's create the GUI application:

import tkinter as tk from tkinter import filedialog from PIL import Image, ImageTk import os def open_file(): file_path = filedialog.askopenfilename() if file_path: sketch = pencil_sketch(file_path) cv2.imwrite('sketch.png', sketch) load_image('sketch.png') def load_image(image_path): img = Image.open(image_path) img = img.resize((250, 250), Image.ANTIALIAS) img = ImageTk.PhotoImage(img) panel = tk.Label(window, image=img) panel.image = img panel.grid(column=0, row=1) window = tk.Tk() window.title('Pencil Sketch App') btn = tk.Button(window, text='Open Image', command=open_file) btn.grid(column=0, row=0) window.mainloop() 

This script creates a simple GUI with a button to open an image file and a panel to display the pencil sketch. When you click the button, it opens a file dialog to select an image, then processes the image and displays the sketch.

Complete Program

Combine the image processing function and the GUI code to have a complete application.

Usage

Run the Python script. A window will open with a button labeled "Open Image". Click the button to choose an image from your file system. The application will then display the pencil sketch of the selected image.

Note

  • The pencil sketch function provided is basic. You might need to adjust the parameters or method for better results depending on the images.
  • The GUI is minimalistic; you can expand it with additional features like saving the sketch, error handling, and more sophisticated layout and styling.

More Tags

nunit intel nlp uitextview azure-cosmosdb-sqlapi virtual-machine mongoose chartjs-2.6.0 mongo-shell regex

More Programming Guides

Other Guides

More Programming Examples