Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting connected objects from an image in Python

I have a graysacle png image and I want to extract all the connected components from my image. Some of the components have same intensity but I want to assign a unique label to every object. here is my image

enter image description here

I tried this code:

img = imread(images + 'soccer_cif' + str(i).zfill(6) + '_GT_index.png')
labeled, nr_objects = label(img)
print "Number of objects is %d " % nr_objects

But I get just three objects using this. Please tell me how to get each object.

like image 396
Khushboo Avatar asked Jun 05 '13 10:06

Khushboo


People also ask

What is extraction of connected components in image processing?

Connected components labeling scans an image and groups its pixels into components based on pixel connectivity, i.e. all pixels in a connected component share similar pixel intensity values and are in some way connected with each other.

What is cv2 ConnectedComponentsWithStats?

ConnectedComponentsWithStats Method (InputArray, OutputArray, OutputArray, OutputArray, PixelConnectivity, MatType) computes the connected components labeled image of boolean image. image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 represents the background label.

What are connected components Python?

What are Connected Components? Connected Components or Components in Graph Theory are subgraphs of a connected graph in which any two vertices are connected to each other by paths, and which is connected to no other vertice in the supergraph.

Can you load images in python?

Python has several libraries like OpenCV, PIL, and matplotlib that can be used to load and save the image.


2 Answers

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()

enter image description here

With blur_radius = 1.0, this finds 4 objects. With blur_radius = 0.5, 5 objects are found:

enter image description here

like image 69
unutbu Avatar answered Sep 21 '22 18:09

unutbu


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)
like image 24
Daniel MM. Kamani Avatar answered Sep 17 '22 18:09

Daniel MM. Kamani