OpenCV: Automatic select big contour areas and remove

Using OpenCV with python to select for color some areas into the images and after maintain only the biggest areas and remove it from image with the obtained mask.

Example of color crop


The requirements are only Python3 installed and installed libraries opencv, matplotlib and jupyter notebook, but I will use a colab notebook.
Remember that opencv on linux need to install it by pip and also with your package manager you mast instal python3-opencv, so if you are locally:

sudo apt install python3-opencv
python3 -m pip install opencv-python notebook

Now you can use Colab or run your jupyter notebook locally with:

jupyter notebook 
python3 -m jupyter notebook


At first we need an image that we can download with that command into the notebook:

!wget -O tes.jpg

We also need to import the library that we will use:

import cv2
from IPython.display import Image
import numpy as np
import matplotlib.pyplot as plt

Read and show image

To show an image file is simple on jupyter notebook:

img_path = 'tes.jpg'
Image(img_path, height=300)

But we need to read it with opencv to elaborate:

img = cv2.imread(img_path)

(Remember if you do plt.imshow(img) it will plot the image but with wrong color because matplotlib use RGB instead opencv have BGR)

Select Color

To select for color we must chouse a range of colors and after we can exec:

lower_val = np.array([0,0,0])
upper_val = np.array([40,40,100])
mask = cv2.inRange(img, lower_val, upper_val)

Now we can plot the mask obtained:

Region selection

Select biggest Areas

Now we want to select only the biggest areas

contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
selected_contours = []
for contour in contours:
area = cv2.contourArea(contour)
if area > 10000:
blank_image = np.zeros(mask.shape, np.uint8)
cv2.fillPoly(blank_image, pts=selected_contours, color= (255,255,255))
Selected Areas

Remove contour from image

So now we can remove it from image:

rgb_mask = cv2.cvtColor(blank_image,cv2.COLOR_GRAY2RGB)
out_img = img * (1 - rgb_mask/255)]

And save

cv2.imwrite('out.png', out_img)
Cropped Img

Now we have the script to remove also to alarge number of images the area with same properties.


Opencv have the same potential of GIMP (or Photoshop), but it enable you to scriptize the function, also ffmpeg give this capability, but you can also create plugin for GIMP.
So is not importat witch technique you will use, but contrinbute to opensource because it give you all that softwers!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nicola Landro

Nicola Landro

Linux user and Open Source fun. Deep learning PhD Student, Full stack web developer, Mobile developer, Musitian.