Hello everyone! ๐
In recent weeks, Iโve been exploring OpenCV for image processing. OpenCV is a powerful library in Python used for various computer vision tasks. As a beginnerโs project, I decided to build a simple application to convert images to grayscale. This feature is commonly used in image editors, but I wanted to develop it myself using Python. And guess what? Itโs super easy to do!
In this tutorial, I’ll walk you through the process of building a simple grayscale image converter using OpenCV and Streamlit.
You can install all the required packages using the following command:
pip install opencv-python streamlit pillow numpy
Next, you need to import the necessary libraries:
import cv2
import streamlit as st
import numpy as np
from PIL import Image
import io
Here, we define a function to convert the uploaded image to a grayscale image.
def convert_to_grayscale(image):
# Convert image to numpy array
image_array = np.array(image)
# Convert to grayscale using OpenCV
gray_image = cv2.cvtColor(image_array, cv2.COLOR_RGB2GRAY)
return gray_image
Now, letโs build a simple UI with Streamlit where users can upload an image, see the converted grayscale image, and download it.
st.title("Image to Grayscale Converter")
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"])
if uploaded_file is not None:
image = Image.open(uploaded_file)
# Create two columns
col1, col2 = st.columns(2)
# Display original image in first column
with col1:
st.image(image, caption="Uploaded Image", use_container_width=True)
# Display grayscale image in second column
with col2:
gray_image = convert_to_grayscale(image)
st.image(gray_image, caption="Grayscale Image", use_container_width=True, clamp=True)
# Convert grayscale image to PIL format for saving
gray_pil = Image.fromarray(gray_image)
# Save image to a buffer
buf = io.BytesIO()
gray_pil.save(buf, format="PNG")
byte_im = buf.getvalue()
# Provide a download button centered
st.download_button(label="Download Grayscale Image",
data=byte_im,
file_name="grayscale_image.png",
mime="image/png")
convert_to_grayscale()
Function: This function takes an image as input, converts it to a numpy array, and then applies OpenCVโs cvtColor()
function to convert the image to grayscale.Save your script in a .py
file, for example, app.py
. To run the app, use the following command:
streamlit run app.py
Open the URL provided by Streamlit, and you can use your simple grayscale converter right in your browser!
And thatโs it! I just built a basic image converter that turns any image into grayscale using OpenCV and Streamlit.
Hope you enjoyed this post. Happy coding! ๐