How to programmatically (preferably using PIL in python) calculate the total number of pixels of an object with a stripped background?

Viewed 382

I have multiple pictures, each of which has an object with its background removed. The pictures are 500x400 pixels in size.

I am looking for a way to programmatically (preferably using python) calculate the total number of pixels of the image inside the picture (inside the space without the background).

I used the PIL package in Python to get the dimensions of the image object, as follows:

print(image.size)

This command successfully produced the dimensions of the entire picture (500x400 pixels) but not the dimensions of the object of interest inside the picture.

Does anyone know how to calculate the dimensions of an object inside a picture using python? An example of a picture is embedded below.

Picture

1 Answers

You could floodfill the background pixels with some colour not present in the image, e.g. magenta, then count the magenta pixels and subtract that number from number of pixels in image (width x height).

Here is an example:

#!/usr/bin/env python3

from PIL import Image, ImageDraw
import numpy as np

# Open the image and ensure RGB
im = Image.open('man.png').convert('RGB')

# Make all background pixels magenta
ImageDraw.floodfill(im,xy=(0,0),value=(255,0,255),thresh=50)

# Save for checking
im.save('floodfilled.png')

# Make into Numpy array
n = np.array(im)

# Mask of magenta background pixels
bgMask =(n[:, :, 0:3] == [255,0,255]).all(2)
count = np.count_nonzero(bgMask)

# Report results
print(f"Background pixels: {count} of {im.width*im.height} total")

Sample Output

Background pixels: 148259 of 199600 total

enter image description here

Not sure how important the enclosed areas between arms and body are to you... if you just replace all greys without using the flood-filling technique, you risk making, say, the shirt magenta and counting that as background.

Related