我以两种方式实现了Python Imaging Library图像的平均RGB值的计算:
def getAverageRGB(image):
"""
Given PIL Image, return average value of color as (r, g, b)
"""
# no. of pixels in image
npixels = image.size[0]*image.size[1]
# get colors as [(cnt1, (r1, g1, b1)), ...]
cols = image.getcolors(npixels)
# get [(c1*r1, c1*g1, c1*g2),...]
sumRGB = [(x[0]*x[1][0], x[0]*x[1][1], x[0]*x[1][2]) for x in cols]
# calculate (sum(ci*ri)/np, sum(ci*gi)/np, sum(ci*bi)/np)
# the zip gives us [(c1*r1, c2*r2, ..), (c1*g1, c1*g2,...)...]
avg = tuple([sum(x)/npixels for x in zip(*sumRGB)])
return avg
def getAverageRGBN(image):
"""
Given PIL Image, return average value of color as (r, g, b)
"""
# get image as numpy array
im = np.array(image)
# get shape
w,h,d = im.shape
# change shape
im.shape = (w*h, d)
# get average
return tuple(np.average(im, axis=0))
我惊讶地发现#1的运行速度比#2快20%。
我正确使用numpy吗?有没有更好的方法来实现平均计算?
答案 0 :(得分:2)
确实令人惊讶。
您可能想要使用:
tuple(im.mean(axis=0))
计算你的平均值(r,g,b)
,但我怀疑它会改进很多东西。您是否尝试过分析getAverageRGBN
并找到瓶颈?
答案 1 :(得分:0)
单行无需更改维度或编写getAverageRGBN:
np.array(image).mean(axis=(0,1))
同样,它可能无法改善任何表现。
答案 2 :(得分:0)
在PIL或Pillow中,在Python 3.4 +中:
from statistics import mean
average_color = [mean(image.getdata(band)) for band in range(3)]