Image segmentation using segment seeds - the watershed algorithm
The watershed algorithm of image segmentation is used when we have initial segmented points and want to automatically fill surrounding areas with the same segmentation class. These initial segmented points are called seeds, and they should be set manually, but in some cases, it's possible to automatically assign them. This recipe shows how to implement the watershed segmentation algorithm in OpenCV.
Getting ready
Install the OpenCV 3.x Python API package and the matplotlib
package.
How to do it...
- Import the necessary modules and functions:
import cv2, random import numpy as np from random import randint
- Load an image to segment and create its copy and other images to store seeds and the segmentation result:
img = cv2.imread('../data/Lena.png') show_img = np.copy(img) seeds = np.full(img.shape[0:2], 0, np.int32) segmentation = np.full(img.shape, 0, np.uint8)
- Define the number of seed types, the color for each seed type, and some variables...