[英]PIL mean of all non-transparent/black pixels in RGBA image
我想達到與以下相同的效果: cv::mean for non black pixel
但是,我正在使用 PIL 並將 PIL 圖像轉換為 cv 圖像並返回太多開銷。
我嘗試使用mean_color = ImageStat.Stat(img).mean
來獲得平均顏色。 但是,這也將包括所有透明像素。 我想計算所有 alpha 值大於 0 的像素的平均值。所以所有非完全透明像素的平均值。
我試圖讓代碼保持良好和快速,因為我必須處理一堆文件。 我希望有一些內置的 PIL function 來做到這一點,但找不到任何東西。
它可能不是最干凈的解決方案,但我讓它工作了。
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
就性能而言,這對我來說已經足夠了。
大約 3.44 秒轉換大約一千個 16x16 圖像文件。 過程是:
取平均值然后保存Image.new('RGB', (16, 16), mean)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.