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

只谈情不闲聊 提交于 2019-12-10 16:27:57

问题


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.


回答1:


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

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.



来源:https://stackoverflow.com/questions/58250682/how-to-programmatically-preferably-using-pil-in-python-calculate-the-total-num

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!