计算图像平均RGB值的基准函数

2024-09-26 17:56:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我用两种方法实现了Python图像库图像平均RGB值的计算:

1-使用列表

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

2-使用numpy

^{pr2}$

我很惊讶地发现1比2快20%。在

我正确地使用了numpy吗?有没有更好的方法来实现平均计算?在


Tags: of方法in图像imagecisizereturn
3条回答

一个不改变尺寸或写入getAverageRGBN的行程序:

np.array(image).mean(axis=(0,1))

同样,它可能不会提高任何性能。在

真令人惊讶。在

您可能需要使用:

tuple(im.mean(axis=0))

来计算你的平均值,但我怀疑它是否能改善很多事情。您是否尝试分析getAverageRGBN并找到瓶颈?在

在PIL或Pillow中,在Python 3.4+中:

from statistics import mean
average_color = [mean(image.getdata(band)) for band in range(3)]

相关问题 更多 >

    热门问题