203. Image Segmentation using Contour Detection

Image Segmentation

Here is one way to implement Image segmentation using contour detection.
The precision is not quite there, but I was amazed that you can do segmentation just with contour detection.

I think it is still usable if..

  1. You only want to know the outline shape.
  2. You don’t need to identify the class
  3. The image is simple
import cv2
import matplotlib.pyplot as plt
import numpy as np

#Read Image
path = 'IMG.png'
img = cv2.imread(path)
img = cv2.resize(img,(256,256))

# Convert Image to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)

#Compute Threshold; 
_,thresh = cv2.threshold(gray, np.mean(gray), 255, cv2.THRESH_BINARY_INV)

#Convert pixels above threshold to white, otherwise 0
edges = cv2.dilate(cv2.Canny(thresh,0,255),None)

#Contour Function to find all open/closed regions in image
cnt = sorted(cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2], key=cv2.contourArea)[-1]

#Draw detected countours on the created mask
mask = np.zeros((256,256), np.uint8)
masked = cv2.drawContours(mask, [cnt],-1, 255, -1)
plt.imshow(img)
plt.imshow(masked,alpha =0.4)