Open In App

Contour Detection with Custom Seeds using Python – OpenCV

Last Updated : 03 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This article discusses how we can dynamically detect contours by clicking on the Image and assign different colors to different parts of the image. Contours are a very useful tool for shape analysis and object detection and recognition.  This program uses OpenCV, Numpy, and Matplotlib libraries.  It also uses a built-in OpenCV Watershed algorithm to detect contours. 

Requirements

  • Python and OpenCV must be installed on the local machine.
  • Install Jupyter Notebook for easy debugging.
  • Here, Matplotlib’s colormap is used to get different colors. In the example given below, we will be using tab10. You can choose different colormaps. Refer to this site for different colors.

Explanation

  • Run the program.
  • Click on the image where you want to make contours.
  • Select a different color for a different part of the image by pressing numbers from zero to nine. (One number for one color)

Below is the Implementation.

Python3




# Import modules
import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
  
# Upload the image in the same directory and then run the code
# If image not found you may get an error
# Reading Image
road = cv2.imread('road_image.jpg')
  
# Making Copy of Image
road_copy = np.copy(road)
  
# Creating two black image of same size as original image
marker_image = np.zeros(road.shape[:2], dtype=np.int32)
segments = np.zeros(road.shape, dtype=np.uint8)
  
# Function to return tuple of colors
def create_rgb(i):
    x = np.array(cm.tab10(i))[:3]*255
    return tuple(x)
  
  
# Storing Colors
colors = []
  
# One color for each single digit
for i in range(10):
    colors.append(create_rgb(i))
  
# Global Variables
# Color Choices
# Number of markers
no_markers = 10
  
# Current markers
current_marker = 1
  
# Flag
marks_updated = False
  
# CALLBACK FUNCTION
def mouse_callback(event, x, y, flags, param):
    global marks_updated
  
    if event == cv2.EVENT_LBUTTONDOWN:
          
        # TRACKING FOR MARKERS
        cv2.circle(marker_image, (x, y), 5, (current_marker), -1)
          
        # DISPLAY ON USER IMAGE
        cv2.circle(road_copy, (x, y), 5, colors[current_marker], -1)
  
        marks_updated = True
  
  
# Naming the window and setting call back function to it
cv2.namedWindow('Road Image')
cv2.setMouseCallback('Road Image', mouse_callback)
  
while True:
    
    # Show the 2 windows
    cv2.imshow('WaterShed Segments', segments)
    cv2.imshow('Road Image', road_copy)
  
    # Close everything if Esc is pressed
    k = cv2.waitKey(1)
    if k == 27:
        break
  
    # Clear all colors and start over if 'c' is pressed
    elif k == ord('c'):
        road_copy = road.copy()
        marker_image = np.zeros(road.shape[0:2], dtype=np.int32)
        segments = np.zeros(road.shape, dtype=np.uint8)
  
    # If a number 0-9 is chosen index the color
    elif k > 0 and chr(k).isdigit():
          
        # chr converts to printable digit
        current_marker = int(chr(k))
  
    # If we clicked somewhere, call the watershed 
    # algorithm on our chosen markers
    if marks_updated:
        marker_image_copy = marker_image.copy()
        cv2.watershed(road, marker_image_copy)
        segments = np.zeros(road.shape, dtype=np.uint8)
  
        for color_ind in range(no_markers):
            
            # COLORING SEGMENTS
            segments[marker_image_copy == (color_ind)] = colors[color_ind]
  
        marks_updated = False
  
# Destroy all the windows at the end
cv2.destroyAllWindows()


Output:

This code will open two windows. One with the original image and one black. Clicking on the original image will create small circles on it and the contours will show on the black image. (Press numbers from 0-9 to change colors and produce a different contour plot.)

Original Image

Processed Image



Similar Reads

Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | Corner detection with Harris Corner Detection method using OpenCV
Harris Corner detection algorithm was developed to identify the internal corners of an image. The corners of an image are basically identified as the regions in which there are variations in large intensity of the gradient in all possible dimensions and directions. Corners extracted can be a part of the image features, which can be matched with fea
2 min read
Python | Corner Detection with Shi-Tomasi Corner Detection Method using OpenCV
What is a Corner? A corner can be interpreted as the junction of two edges (where an edge is a sudden change in image brightness). Shi-Tomasi Corner Detection - Shi-Tomasi Corner Detection was published by J.Shi and C.Tomasi in their paper 'Good Features to Track'. Here the basic intuition is that corners can be detected by looking for significant
3 min read
Python OpenCV - Find center of contour
Prerequisite: How to Detect Shapes in Images in Python using OpenCV? In this article, we will learn how to find centers of contours using OpenCV in python. We will be using the findContours() and moments() functions. We will be using the following image for center point detection: Stepwise Implementation Step 1: Import the required module. C/C++ Co
3 min read
Check if image contour is convex or not in OpenCV Python
In this article we will see different ways to check if an image contour is convex or not with help of python OpenCV. Contour: Contours are continuous curves that represent the boundaries of an object in an image. In the field of computer vision and image processing, contours are used to detect and analyze the shape and structure of objects in image
4 min read
OpenCV - Facial Landmarks and Face Detection using dlib and OpenCV
Content has been removed on Author's request.
1 min read
Face detection using Cascade Classifier using OpenCV-Python
In this article, we are going to see how to detect faces using a cascade classifier in OpenCV Python. Face detection has much significance in different fields of today's world. It is a significant step in several applications, face recognition (also used as biometrics), photography (for auto-focus on the face), face analysis (age, gender, emotion r
4 min read
3D Contour Plotting in Python using Matplotlib
Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the time when the release of 1.0 occurred, the 3d utilities were developed upon the 2d and thus, we have 3d implementation of data available today! The 3d plots are enabled by importing the mplot3d toolkit. Let's look at a 3d contour diagram of a 3d cosine function. Th
2 min read
Contour Plot using Matplotlib - Python
Contour plots also called level plots are a tool for doing multivariate analysis and visualizing 3-D plots in 2-D space. If we consider X and Y as our variables we want to plot then the response Z will be plotted as slices on the X-Y plane due to which contours are sometimes referred as Z-slices or iso-response. Contour plots are widely used to vis
2 min read
Contour Plots using Plotly in Python
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Contour Plots in Plotly A contour plot has a f
4 min read
Article Tags :
Practice Tags :