OpenCV: Automatic select big contour areas and remove
Create a Mask using opencv python by color selection and contours filtering
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:
python3 -m jupyter notebook
At first we need an image that we can download with that command into the notebook:
!wget -O tes.jpg https://newseu.cgtn.com/news/2021-03-27/First-image-of-polarized-black-hole-shows-swirling-magnetic-fields-YVGl157P56/img/033a8ca73e47437a8ef81d7f96c6eeaa/033a8ca73e47437a8ef81d7f96c6eeaa-1280.jpeg
We also need to import the library that we will use:
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'
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)
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:
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))
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)]
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!