Friday, November 15, 2024
Google search engine
HomeLanguagesBuild GUI Application Pencil Sketch from Photo in Python

Build GUI Application Pencil Sketch from Photo in Python

In this article, we will cover how to convert images to watercolor sketches and pencil sketch Linux.

Sketching and painting are used by artists of many disciplines to preserve ideas, recollections, and thoughts. Experiencing art from painting and sculpting to visiting an art museum—provides a variety of well-being advantages, including reduced stress and improved critical thinking abilities. Drawing, sketching, and painting in particular, have been linked to increased creativity, memory, and stress alleviation, and are utilized in art therapy.

Through this article, we can now build a web application to directly convert an image to a sketch using a python framework Streamlit. The user can upload an image to convert it to either a watercolor sketch or a pencil sketch. The user can further download the converted image, before that let us understand some of the definitions that we will use in this article.

  • Streamlit – Streamlit is a popular open-source web application framework among Python developers. It is interoperable and compatible with a wide range of frequently used libraries, including Keras, Sklearn, Numpy, and pandas.
  • PIL – PIL stands for Python Imaging Library. It is a package for image processing in the Python programming language. It includes lightweight image processing tools that help with picture editing, creation, and storing. 
  • Numpy – Numpy is a widely used Python programming library utilized for high-level mathematical computations. 
  • cv2 – This library is utilized for solving computer vision problems

Package required

pip install streamlit
pip install opencv-python
pip install numpy
pip install Pillow

Stepwise Implementation

Step 1: Install Streamlit

 

Similarly, we will install PIL, Numpy, and cv2.

Step 2: Test that the installation worked

streamlit hello

 

Step 3: Now run the streamlit web application. We need to type the following command

streamlit run app.py

 

Step 4: Now the web application has been launched successfully. You can access the web application through the local URL or the Network URL.

 

Step 5: Create a new folder named – Web Application to convert images to sketches.

Step 6: Paste the code of the web application in the file ‘app.py‘ and save the file.

Initially in the code, we import all the required frameworks, packages, libraries, and modules that we will utilize to build the web application. Further, we have to use user-defined functions utilized to convert an image to a watercolor sketch and to convert an image to a pencil sketch. There is also a function to load an image utilizing the PIL library. The main function has the code for the web application. Initially, we have some headings and subheadings to guide the user to upload an image. For uploading the image we have utilized streamlit’s file uploader. We are also providing a drop-down menu for the user to choose between producing a watercolor sketch / producing a pencil sketch and then based on their choice, we render the results. Both the original image and the image after applying the filter are rendered side by side such that the user can compare both images to see the results. Finally, the user can also download the image to their local machine. This is done by utilizing the streamlit’s download button.

Complete Code

Python3




# import the frameworks, packages and libraries
import streamlit as st
from PIL import Image
from io import BytesIO
import numpy as np
import cv2  # computer vision
  
# function to convert an image to a 
# water color sketch
def convertto_watercolorsketch(inp_img):
    img_1 = cv2.edgePreservingFilter(inp_img, flags=2, sigma_s=50, sigma_r=0.8)
    img_water_color = cv2.stylization(img_1, sigma_s=100, sigma_r=0.5)
    return(img_water_color)
  
# function to convert an image to a pencil sketch
def pencilsketch(inp_img):
    img_pencil_sketch, pencil_color_sketch = cv2.pencilSketch(
        inp_img, sigma_s=50, sigma_r=0.07, shade_factor=0.0825)
    return(img_pencil_sketch)
  
# function to load an image
def load_an_image(image):
    img = Image.open(image)
    return img
  
# the main function which has the code for
# the web application
def main():
    
    # basic heading and titles
    st.title('WEB APPLICATION TO CONVERT IMAGE TO SKETCH')
    st.write("This is an application developed for converting\
    your ***image*** to a ***Water Color Sketch*** OR ***Pencil Sketch***")
    st.subheader("Please Upload your image")
      
    # image file uploader
    image_file = st.file_uploader("Upload Images", type=["png", "jpg", "jpeg"])
  
    # if the image is uploaded then execute these 
    # lines of code
    if image_file is not None:
        
        # select box (drop down to choose between water 
        # color / pencil sketch)
        option = st.selectbox('How would you like to convert the image',
                              ('Convert to water color sketch',
                               'Convert to pencil sketch'))
        if option == 'Convert to water color sketch':
            image = Image.open(image_file)
            final_sketch = convertto_watercolorsketch(np.array(image))
            im_pil = Image.fromarray(final_sketch)
  
            # two columns to display the original image and the
            # image after applying water color sketching effect
            col1, col2 = st.columns(2)
            with col1:
                st.header("Original Image")
                st.image(load_an_image(image_file), width=250)
  
            with col2:
                st.header("Water Color Sketch")
                st.image(im_pil, width=250)
                buf = BytesIO()
                img = im_pil
                img.save(buf, format="JPEG")
                byte_im = buf.getvalue()
                st.download_button(
                    label="Download image",
                    data=byte_im,
                    file_name="watercolorsketch.png",
                    mime="image/png"
                )
  
        if option == 'Convert to pencil sketch':
            image = Image.open(image_file)
            final_sketch = pencilsketch(np.array(image))
            im_pil = Image.fromarray(final_sketch)
              
            # two columns to display the original image
            # and the image after applying
            # pencil sketching effect
            col1, col2 = st.columns(2)
            with col1:
                st.header("Original Image")
                st.image(load_an_image(image_file), width=250)
  
            with col2:
                st.header("Pencil Sketch")
                st.image(im_pil, width=250)
                buf = BytesIO()
                img = im_pil
                img.save(buf, format="JPEG")
                byte_im = buf.getvalue()
                st.download_button(
                    label="Download image",
                    data=byte_im,
                    file_name="watercolorsketch.png",
                    mime="image/png"
                )
  
  
if __name__ == '__main__':
    main()


Output:

 

 

 

 

 

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments