用Python查找图像的主要颜色

Fork me on GitHub

A few weeks ago, I was having a discussion about the possibility of detecting the colour of user uploaded images. The idea was that if a dominant colour was known, it could be used to create matching titles. I decided to give it a go using Python and Pillow.

几周前,我曾讨论过检测用户上传图片的颜色的可能性。我的想法是,如果知道一个主要的颜色,它可以用来创建匹配的标题。我决定用Python和Pillow来试试

Average Colour

平均颜色

Naively I tried averaging all the colours. This didn’t work so well.

我直截了当地尝试将所有的颜色平均化。这并不奏效。

def average_colour(image):

  colour_tuple = [None, None, None]
  for channel in range(3):

      # Get data for one channel at a time
      pixels = image.getdata(band=channel)

      values = []
      for pixel in pixels:
          values.append(pixel)

      colour_tuple[channel] = sum(values) / len(values)

  return tuple(colour_tuple)

Here is the result on one of my photos from Paris.

这是我在巴黎拍摄的一张照片的结果。

The green/blue/grey colour is the average of all the pixels. While I can see how this colour is the average (green and blue with bits of grey), it doesn’t represent a dominant colour of the image.

绿/蓝/灰的颜色是所有像素的平均值。虽然我可以看到这种颜色是平均的(绿色和蓝色,有一些灰色),但它并不代表图像的主要颜色。

Colour Frequency

颜色频率

I thought a better approach could be to determine the most commonly occurring colour.

我想一个更好的方法可以是确定最常出现的颜色。

def most_frequent_colour(image):

    w, h = image.size
    pixels = image.getcolors(w * h)

    most_frequent_pixel = pixels[0]

    for count, colour in pixels:
        if count  most_frequent_pixel[0]:
            most_frequent_pixel = (count, colour)

    compare("Most Common", image, most_frequent_pixel[1])

    return most_frequent_pixel

This worked surprisingly well. The Pillow image.getColors() method conveniently returns a tuple containing all the colours in the image and the number of times the colour occurred.

这样做的效果出乎意料地好。Pillowimage.getColors() 方法方便地返回一个包含图像中所有颜色和颜色出现次数的元组。

This is the result on the same image.

这是在同一图像上的结果。

The selected colour nicely matches the image.

所选的颜色与图像很匹配。

The most frequent colour method starts to run into problems when its run against photos which ...

开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.137.1. UTC+08:00, 2024-11-22 13:44
浙ICP备14020137号-1 $访客地图$