我有多张照片,每一张都有一个背景被移除的物体。图片大小为500×400像素。
我正在寻找一种以编程方式(最好使用python)的方法来计算图片中(在没有背景的空间中)图像的总像素数。
我使用Python中的PIL包获取图像对象的维度,如下所示:
print(image.size)该命令成功地生成了整个图片的尺寸(500x400像素),但没有生成图片中感兴趣的对象的尺寸。
有人知道如何使用python计算图片中对象的尺寸吗?下面是图片的一个例子。

发布于 2019-10-05 17:48:12
你可以用一些不存在于图像中的颜色来填充背景像素,例如洋红色,然后计数洋红像素并从图像中的像素数(宽度x高度)中减去这个数字。
下面是一个示例:
#!/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")样本输出
Background pixels: 148259 of 199600 total

不知道手臂和身体之间的封闭区域对你有多重要.如果你只是替换所有灰色,而不使用充水技术,你冒着制造,比如说,衬衫洋红色的风险,并把它作为背景。
https://stackoverflow.com/questions/58250682
复制相似问题