【问题标题】:PIL mean of all non-transparent/black pixels in RGBA imageRGBA 图像中所有不透明/黑色像素的 PIL 平均值
【发布时间】:2020-02-14 16:06:42
【问题描述】:
我想达到和中一样的效果:cv::mean for non black pixel
但是我正在使用 PIL 并将 PIL 图像转换为 cv 图像并返回太多开销。
我尝试过使用
mean_color = ImageStat.Stat(img).mean
得到平均颜色。但是,这也将包括所有透明像素。我想计算所有 alpha 值大于 0 的像素的平均值。所以是所有非完全透明像素的平均值。
我正在努力使代码保持良好和快速,因为我必须处理一堆文件。我希望有一些内置的 PIL 函数来执行此操作,但找不到。
【问题讨论】:
标签:
python
numpy
image-processing
python-imaging-library
【解决方案1】:
这可能不是最干净的解决方案,但我得到了它的工作。
def mean(rgb, a):
"""
Supply with an RGB PIL Image and Alpha Channel PIL Image.
Calculates the mean over all non-fully-transparent pixels in rgb.
"""
a_arr = np.array(a) # Convert Alpha values Image to array.
img_arr = np.array(rgb) # Convert Image RGB values to array.
mask = (a_arr > 0) # Create mask from all non-transparent pixels
stuff = img_arr[mask] # Array containing all pixels that aren't transparent
rows = len(stuff) # Get the row size.
if rows < 1: # If all pixels are transparent:
return (0, 0, 0) # The mean is simply black
cols = len(stuff[0]) # Else, continue with the size of cols
data = np.zeros([cols, rows, 3], dtype = np.uint8) # Create an array to contain the pixels
data[:] = stuff # Put the pixels with at least a > 0 into the created array.
c_img = Image.fromarray(data, 'RGB') # Convert back to RGB PIL Image
return ImageStat.Stat(c_img).mean # Calculate the mean over all pixels
就性能而言,这对我来说已经足够了。
转换大约一千个 16x16 图像文件大约需要 3.44 秒。
过程是:
取平均值然后保存Image.new('RGB', (16, 16), mean)。