Image processing from scratch with python (4) Contour extraction

A series of studying basic image processing from scratch (4).

Refer to the OpenCV-Python tutorial Image recognition book https://www.amazon.co.jp/dp/4061529129/ It is a policy to promote understanding of the processing that is being done in.

table of contents

  1. Environment
  2. Contour extraction
  3. Contour approximation
  4. Inscribed figure

environment

Python 3.7.0 OpenCV 4.1.0 Jupyter Notebook

Contour extraction

Perform contour extraction on the binarized panda image. The return value contours of findContours is the coordinate set for each contour, and the hierarchy is the hierarchical structure of the contour. This time, the outline is made into two layers. The outline was drawn on the original panda image.

rinkaku.py


import cv2
import numpy as np
from matplotlib import pyplot as plt
from pylab import rcParams #Change the size of the image display
%matplotlib inline
rcParams['figure.figsize'] = 25, 20  #Image display size

img = cv2.imread('/brabra/6.jpg',0)
#Compress the image
img = cv2.resize(img, dsize=None, fx=0.15, fy=0.15)
#Binarization(The threshold is from the binarization of Otsu)
ret,thresh = cv2.threshold(img,59,255,0)
#Invert
thresh= cv2.bitwise_not(thresh)

#Contour extraction(RETR_CCOMP has two layers)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) #Convert to RGB format

#Draw the found outline on the original image
for i in range(len(contours)):
    
    #Draw the top layer (green)
    if hierarchy[0][i][3] == -1:        
        cv2.drawContours(img, contours, i, (0, 255, 0), 2)
    #Draw the second layer (light blue)
    else:
        cv2.drawContours(img, contours, i, (0, 255, 255), 2)        

plt.imshow(img)

rinkakua.png

It is not perfect, but the outline is mostly extracted.

Contour approximation

The contour is drawn with many vertices when attention is paid to details, but when the vertices up to that point are not needed, the contour can be approximated. Here, I tried to approximate the contour of the foot part.

rinkakukinzi.py


img = cv2.imread('/brabra/6.jpg',0)
img = cv2.resize(img, dsize=None, fx=0.15, fy=0.15)
ret,thresh = cv2.threshold(img,59,255,0)
thresh= cv2.bitwise_not(thresh)

#Contour extraction
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) #Convert to RGB format

#Outline of the foot part
cnt = contours[7]

#Contour approximation epsilon is the degree of approximation
epsilon = 0.01*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)

#Draw an approximate contour on the original image
cv2.drawContours(img, [approx], -1, (0, 255, 0), 2)

plt.imshow(img)

rink.png

It was nice and angular.

Inscribed figure

It is possible to draw a figure that circumscribes the contour. I drew quadrilaterals, circles, ellipses that circumscribe, and similar lines.

gaisetsu.py


img = cv2.imread('C:/brabra/6.jpg',0)
img = cv2.resize(img, dsize=None, fx=0.15, fy=0.15)
ret,thresh = cv2.threshold(img,59,255,0)
thresh= cv2.bitwise_not(thresh)

#Contour extraction
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) #Convert to RGB format

#Draw the outline of the foot
cv2.drawContours(img, contours, 7, (0, 255, 0), 2)

cnt = contours[7]

#External rectangle
x,y,w,h = cv2.boundingRect(cnt)
img0 = img.copy()
img0 = cv2.rectangle(img0,(x,y),(x+w,y+h),(0,255,0),2)

#External rectangle considering rotation
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
img00 = img.copy()
img00 = cv2.drawContours(img00,[box],0,(0,0,255),2)

#Minimum circumscribed circle
(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
radius = int(radius)
img1 = img.copy()
img1 = cv2.circle(img1,center,radius,(0,255,255),2)

#Ellipse fitting
ellipse = cv2.fitEllipse(cnt)
img2 = img.copy()
img2 = cv2.ellipse(img2,ellipse,(255,255,0),2)

#Straight line fitting
rows,cols = img.shape[:2]
[vx,vy,x,y] = cv2.fitLine(cnt, cv2.DIST_L2,0,0.01,0.01)
lefty = int((-x*vy/vx) + y)
righty = int(((cols-x)*vy/vx)+y)
img3 = img.copy()
img3 = cv2.line(img3,(cols-1,righty),(0,lefty),(255,255,255),2)

plt.subplot(231),plt.imshow(img0)
plt.title('en'), plt.xticks([]), plt.yticks([])
plt.subplot(232),plt.imshow(img00)
plt.title('en'), plt.xticks([]), plt.yticks([])
plt.subplot(233),plt.imshow(img1)
plt.title('en'), plt.xticks([]), plt.yticks([])
plt.subplot(234),plt.imshow(img2)
plt.title('daen'), plt.xticks([]), plt.yticks([])
plt.subplot(235),plt.imshow(img3)
plt.title('line'), plt.xticks([]), plt.yticks([])

plt.show()

gaisetsu.png

Summary

I deepened my understanding of contour extraction.

References

--Image processing using OpenCV (OpenCV-Python tutorial) http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_imgproc/py_table_of_contents_imgproc/py_table_of_contents_imgproc.html#py-table-of-content-imgproc

--Image recognition (machine learning professional series) https://www.amazon.co.jp/dp/4061529129/

Recommended Posts

Image processing from scratch with python (4) Contour extraction
Image processing from scratch with python (5) Fourier transform
Image processing with Python
Image processing with Python (Part 2)
Image processing with Python (Part 1)
Image processing with Python (Part 3)
[Python] Image processing with scikit-image
Image processing with Python 100 knocks # 2 Grayscale
python image processing
Basics of binarized image processing with Python
Image processing with Python 100 knock # 10 median filter
Image processing with Python 100 knocks # 8 Max pooling
Business efficiency starting from scratch with Python
Image processing with Python & OpenCV [Tone Curve]
Image acquisition from camera with Python + OpenCV
Drawing with Matrix-Reinventor of Python Image Processing-
Easy image processing in Python with Pillow
Image processing with Python 100 knocks # 7 Average pooling
Light image processing with Python x OpenCV
Image processing with Python 100 knocks # 9 Gaussian filter
First Python image processing
Image Processing with Python Environment Setup for Windows
Image Processing with PIL
Region extraction method using cellular automaton Try region extraction from the image with growcut (Python)
How to scrape image data from flickr with python
Notes on HDR and RAW image processing with Python
Read QR code from image file with Python (Mac)
100 Language Processing with Python Knock 2015
Image processing with PIL (Pillow)
Acoustic signal processing with Python (2)
Acoustic signal processing with Python
Sorting image files with Python (2)
Sorting image files with Python (3)
Tweet with image in Python
Sorting image files with Python
Image processing by python (Pillow)
Image Processing Collection in Python
With skype, notify with skype from python!
[Let's play with Python] Image processing to monochrome and dots
Cut out an image with python
Real-time image processing basics with opencv
Call C from Python with DragonFFI
[Python] Using OpenCV with Python (Image Filtering)
[Python] Easy parallel processing with Joblib
Using Rstan from Python with PypeR
100 Language Processing Knock with Python (Chapter 1)
[Python] Using OpenCV with Python (Image transformation)
Install Python from source with Ansible
Create folders from '01' to '12' with python
Text extraction with AWS Textract (Python3.6)
100 Language Processing Knock with Python (Chapter 3)
Personal notes for python image processing
Run Aprili from Python with Orange
Let's do image scraping with Python
Call python from nim with Nimpy
Find image similarity with Python + OpenCV
Image processing | predicting species from images
Read fbx from python with cinema4d
Send image with python, save with php
Gradation image generation with Python [1] | np.linspace
Try to extract a character string from an image with Python3