Contours in Images

Source: Deep Learning on Medium

Bounding a contour

%matplotlib inline 
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread("imgs/chapter6/contour2.jpg", 0);
# Change thresholding and check
#ret,thresh = cv2.threshold(imgray,127,255,0)
ret,thresh = cv2.threshold(img,127,255,0)
#ret,thresh = cv2.threshold(imgray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# drawing contours over original image img_with_contours = img.copy()
img_with_contours = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) cv2.drawContours(img_with_contours, contours, 1, (0,255,0), 3)
# Talk about (0, 255, 0) colors
plt.figure(figsize=(8, 8))
plt.imshow(img_with_contours[:,:,::-1])
plt.show()

Straight rectangle

cnt = contours[1]

#################FOCUS#############################
x,y,w,h = cv2.boundingRect(cnt)
###################################################

img_with_contours = img.copy();
img_with_contours = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR);
cv2.rectangle(img_with_contours,(x,y),(x+w,y+h),(0,255,0),2)

plt.figure(figsize=(8, 8));
plt.imshow(img_with_contours[:,:,::-1])
plt.show()

Rotated rectangle

cnt = contours[1]

#######################FOCUS#########################
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
#######################################################

img_with_contours = img.copy();
img_with_contours = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR);
cv2.drawContours(img_with_contours,[box],0,(0,0,255),2)

plt.figure(figsize=(8, 8));
plt.imshow(img_with_contours[:,:,::-1])
plt.show()

Circular bounding

cnt = contours[1]

###############################FOCUS##############################
(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
radius = int(radius)
print(radius)
##################################################################

img_with_contours = img.copy()
img_with_contours = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
cv2.circle(img_with_contours, center, radius,(0,255,0),2)

plt.figure(figsize=(8, 8))
plt.imshow(img_with_contours[:,:,::-1])
plt.show()

Elliptical bounding

#########################FOCUS######################################
cnt = contours[1]
ellipse = cv2.fitEllipse(cnt)
####################################################################
img_with_contours = img.copy()
img_with_contours = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR);
cv2.ellipse(img_with_contours,ellipse,(0,255,0),2)
plt.figure(figsize=(8, 8))
plt.imshow(img_with_contours[:,:,::-1])
plt.show()