Extracting connected objects from an image in Python
If the border of objects are completely clear and you have a binary image in img, you can avoid Gaussian filtering and just do this line:
labeled, nr_objects = ndimage.label(img)
J.F. Sebastian shows a way to identify objects in an image. It requires manually choosing a gaussian blur radius and threshold value, however:
from PIL import Image
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt
fname='index.png'
blur_radius = 1.0
threshold = 50
img = Image.open(fname).convert('L')
img = np.asarray(img)
print(img.shape)
# (160, 240)
# smooth the image (to remove small objects)
imgf = ndimage.gaussian_filter(img, blur_radius)
threshold = 50
# find connected components
labeled, nr_objects = ndimage.label(imgf > threshold)
print("Number of objects is {}".format(nr_objects))
# Number of objects is 4
plt.imsave('/tmp/out.png', labeled)
plt.imshow(labeled)
plt.show()
With blur_radius = 1.0
, this finds 4 objects.
With blur_radius = 0.5
, 5 objects are found: