...

Image Segmentation in OpenCV with Python and Contours

OpenCV Image Segmentation

Introduction

In this tutorial, you will learn a practical pipeline for OpenCV image segmentation in Python.
We will convert an image to grayscale, apply a smart binary threshold, detect contours, and then build a mask to extract the main object.
This workflow is fast, reproducible, and ideal for object extraction, background removal, and preprocessing for computer vision tasks.
The example focuses on choosing the largest contour to isolate the dominant subject in the scene.

Check the tutorial : https://www.youtube.com/watch?v=f6VgWTD_7kc

Contour-Based Segmentation with OpenCV

This section implements the full workflow: grayscale conversion, thresholding, contour detection, mask creation, and object extraction.
You will get both on-screen previews and saved outputs for easy verification.

### Import the OpenCV library to handle image processing operations. import cv2 ### Import NumPy for numerical operations and for creating masks as arrays. import numpy as np  ### Read the input image from disk into a NumPy array using OpenCV. img = cv2.imread("Open-CV/Image-Segmentation-using-Contour-Detection/beach-and-boats.jpeg")  ### Convert the color image to grayscale to simplify thresholding and contour detection. gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ### Apply an inverse binary threshold using the mean gray value as the threshold dynamically. _ , tresh = cv2.threshold(gray,np.mean(gray), 255, cv2.THRESH_BINARY_INV   )  ### Detect all contours from the thresholded image using a simple chain approximation. ### hierarchy is returned but not used directly in this script. contours , hierarchy = cv2.findContours(tresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)  ### Print the number of contours found for quick debugging and insight. print(len(contours))   ### Sort contours by area and select the largest one, which typically corresponds to the main object. cnt = sorted(contours, key=cv2.contourArea)[-1]  ### Create a blank single-channel mask with a specific height and width matching the target canvas. ### dtype=uint8 is required for OpenCV masking operations. mask = np.zeros( (750, 1038), dtype="uint8" )  ### Draw the largest contour onto the mask (filled) using a red color tuple. ### Color channels are provided, but with a single-channel mask the intensity value is what matters. maskedRed = cv2.drawContours(mask,[cnt] , -1 , (0 , 0 , 255), -1) ### Draw the same filled contour using white to produce the final binary mask of the object. maskedFinal = cv2.drawContours(mask,[cnt] , -1 , (255 , 255 , 255), -1)  ### Use bitwise_and to apply the mask to the original image and keep only the segmented object. finalImage = cv2.bitwise_and(img, img, mask=maskedFinal)  ### Show the original image in a window for comparison. cv2.imshow("Original", img) ### Show the masked result to verify segmentation visually. cv2.imshow("maskedFinal", finalImage)  ### Save the binary mask to disk for reuse or inspection. cv2.imwrite("c:/temp/maskedFinal.jpg",maskedFinal) ### Save the final segmented image result to disk. cv2.imwrite("c:/temp/finalImage.jpg",finalImage)  ### Wait indefinitely for a key press so the display windows remain visible. cv2.waitKey(0)  ### Clean up OpenCV windows to free resources. cv2.destroyAllWindows() 

You can find the full code here : https://ko-fi.com/s/b0b417802e

The code thresholds the grayscale image, finds all contours, selects the largest contour, fills it into a mask, and applies the mask to extract the main object.
This approach is efficient for scenes where the dominant subject is clearly separable by intensity and shape.
For production, consider sizing the mask from img.shape[:2] and refining thresholding or morphology to suit varied lighting.

You can find more similar tutorials in my blog posts page here : https://eranfeit.net/blog/

Connect :

☕ Buy me a coffee — https://ko-fi.com/eranfeit

🖥️ Email : feitgemel@gmail.com

🌐 https://eranfeit.net

🤝 Fiverr : https://www.fiverr.com/s/mB3Pbb

Enjoy,

Eran

error: Content is protected !!
Eran Feit