Home > OS >  counting the number of objects in a segmented image
counting the number of objects in a segmented image

Time:12-30

this is a color based segmented image

hi, this is a color based segmented image the image to process I need a method to count the number of white holes in the image please, how I can do that using python

CodePudding user response:

To count the number of white holes in an image like the one you linked to, you can use the following steps:

Load the image into memory using the Python Pillow library (or another library such as OpenCV).

Convert the image to grayscale, which will make it easier to work with and will allow us to threshold the image to create a binary image.

Threshold the grayscale image to create a binary image, where white pixels represent foreground pixels and black pixels represent background pixels.

Use a morphological operation such as dilation or erosion to fill in any small holes or gaps in the foreground objects.

Use connected component analysis to identify and label each separate connected region in the image.

Iterate through the connected components and count the number of components that are white (foreground) pixels.

Here's some example code that demonstrates how you might implement this in Python using the Pillow library:

from PIL import Image

# Load the image and convert it to grayscale
image = Image.open('image.png').convert('L')

# Threshold the image to create a binary image
threshold = 128
image = image.point(lambda x: 0 if x < threshold else 255, '1')

# Use dilation to fill in small holes in the image
image = image.dilate()

# Use connected component analysis to identify and label each connected region
image = image.convert('L')
labels, num_labels = image.convert('L').label(background=0)

# Count the number of white holes
hole_count = 0
for label in range(1, num_labels   1):
    if image.getdata()[labels.index(label)] == 255:
        hole_count  = 1

print(f'Number of white holes: {hole_count}')

This code should work for the specific image you linked to, but you may need to adjust the threshold value or use a different morphological operation depending on the characteristics of the images you're working with.

CodePudding user response:

You can use skimage to determine the contours and then count the contours. The code will something like this:

from skimage import io
from skimage import measure

url = "https://i.stack.imgur.com/ct9rO.png"
image = io.imread(url, as_gray=True)

contours = measure.find_contours(image)

print("Number of blobs = ", len(contours))

The output I got was 125. However it is counting some small noisy parts towards the topleft (which are pretty small) and you might want to filter them before running this code, which should give some value less than 125.

  • Related