您可以使用PIL在每个维度上反复将图像缩小2倍,直到达到1x1。我不知道PIL在大比例缩小时使用什么算法,因此在单个调整大小中直接转到1x1可能会丢失信息。它可能不是最有效的,但是它将为您提供图像的“平均”颜色。


0

0

Python Imaging Library在Image对象上具有方法getcolors:
im.getcolors() =>(计数,颜色)元组的列表或无
我猜您仍然可以尝试在此之前调整图像的大小,然后查看其效果是否更好。
0

下面是一个基于c ++ Qt的示例,用于猜测主要的图像颜色。您可以使用PyQt并将其翻译为等效的Python。
#include <Qt/QtGui>
#include <Qt/QtCore>
#include <QtGui/QApplication>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QPixmap pixmap("logo.png");
QImage image = pixmap.toImage();
QRgb col;
QMap<QRgb,int> rgbcount;
QRgb greatest = 0;
int width = pixmap.width();
int height = pixmap.height();
int count = 0;
for (int i = 0; i < width; ++i)
{
for (int j = 0; j < height; ++j)
{
col = image.pixel(i, j);
if (rgbcount.contains(col)) {
rgbcount[col] = rgbcount[col] + 1;
}
else {
rgbcount[col] = 1;
}
if (rgbcount[col] > count) {
greatest = col;
count = rgbcount[col];
}
}
}
qDebug() << count << greatest;
return app.exec();
}
0

不必像Peter所建议的那样使用k均值来找到主要颜色。这使一个简单的问题复杂化了。您还受到选择的集群数量的限制,因此从根本上讲,您需要了解所查看的内容。
正如您所提到的和zvone的建议,使用Pillow库可以快速找到最常见/最主要的颜色。我们只需要按像素数对像素进行排序。
from PIL import Image
def find_dominant_color(filename):
#Resizing parameters
width, height = 150,150
image = Image.open(filename)
image = image.resize((width, height),resample = 0)
#Get colors from image object
pixels = image.getcolors(width * height)
#Sort them by count number(first element of tuple)
sorted_pixels = sorted(pixels, key=lambda t: t[0])
#Get the most frequent color
dominant_color = sorted_pixels[-1][1]
return dominant_color
唯一的问题是,当颜色数量大于256时,方法getcolors()
返回None。您可以通过调整原始图像的大小来处理它。
总之,它可能不是最精确的解决方案,但可以完成工作。
0

尝试Color-thief 。它基于PIL
,效果很棒。
安装
pip install colorthief
用法
from colorthief import ColorThief
color_thief = ColorThief('/path/to/imagefile')
# get the dominant color
dominant_color = color_thief.get_color(quality=1)
它也可以找到颜色调色板
palette = color_thief.get_palette(color_count=6)
0

如果您仍在寻找答案,这对我有用,尽管效率不高:
from PIL import Image
def compute_average_image_color(img):
width, height = img.size
r_total = 0
g_total = 0
b_total = 0
count = 0
for x in range(0, width):
for y in range(0, height):
r, g, b = img.getpixel((x,y))
r_total += r
g_total += g
b_total += b
count += 1
return (r_total/count, g_total/count, b_total/count)
img = Image.open('image.png')
#img = img.resize((50,50)) # Small optimization
average_color = compute_average_image_color(img)
print(average_color)
0

要添加到Peter的答案中,如果PIL给您的图像的模式为“ P”或几乎所有非“ RGBA”的模式,那么您需要应用Alpha蒙版将其转换为RGBA。您可以使用以下方法轻松完成此操作:
if im.mode == 'P':
im.putalpha(0)
0

这是使用Pillow和Scipy的cluster软件包的代码。
为简单起见,我将文件名硬编码为“ image.jpg”。调整图像大小是为了提高速度:如果您不介意等待,请注释一下调整大小调用。当在此蓝胡椒样本图像上运行时,通常会说主导色是#d8c865,它大致对应于两个胡椒左下角的浅黄色区域。我说“通常”是因为所使用的聚类算法具有一定程度的随机性。您可以通过多种方式更改此设置,但出于您的目的,它可能非常适合。 (如果需要确定的结果,请检查kmeans2()变体上的选项。)
from __future__ import print_function
import binascii
import struct
from PIL import Image
import numpy as np
import scipy
import scipy.misc
import scipy.cluster
NUM_CLUSTERS = 5
print('reading image')
im = Image.open('image.jpg')
im = im.resize((150, 150)) # optional, to reduce time
ar = np.asarray(im)
shape = ar.shape
ar = ar.reshape(scipy.product(shape[:2]), shape[2]).astype(float)
print('finding clusters')
codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)
print('cluster centres:\n', codes)
vecs, dist = scipy.cluster.vq.vq(ar, codes) # assign codes
counts, bins = scipy.histogram(vecs, len(codes)) # count occurrences
index_max = scipy.argmax(counts) # find most frequent
peak = codes[index_max]
colour = binascii.hexlify(bytearray(int(c) for c in peak)).decode('ascii')
print('most frequent is %s (#%s)' % (peak, colour))
注意:当我将聚类的数量从5扩展到10或15时,结果通常是绿色或蓝色。给定输入图像,这些结果也是合理的……我也无法确定哪种颜色在该图像中真正占主导地位,因此我也不会指责算法!
还有一点好处:仅使用N种最常用的颜色保存缩小尺寸的图像:
# bonus: save image using only the N most common colours
import imageio
c = ar.copy()
for i, code in enumerate(codes):
c[scipy.r_[scipy.where(vecs==i)],:] = code
imageio.imwrite('clusters.png', c.reshape(*shape).astype(np.uint8))
print('saved clustered image')
- 社区规范
- 提出问题
- 进行投票
- 个人资料
- 优化问题
- 回答问题
0
我正在寻找一种使用python查找图像中最主要的颜色/色调的方法。可以使用平均阴影,也可以使用最常见的RGB。我看过Python Imaging库,找不到任何与我在他们的手册中找的东西有关的内容,也没有在VTK上找到任何相关信息。
但是,我确实找到了一个可以满足我需要的PHP脚本, 在这里 (需要登录才能下载)。该脚本似乎将图像大小调整为150 * 150,以显示主要颜色。但是,在那之后,我相当失落。我确实考虑过写一些东西,可以将图像调整为较小的尺寸,然后检查每隔一个像素是否有图像,尽管我认为这样做效率不高(尽管将这个想法实现为C python模块可能是一个想法)。
但是,尽管如此,我还是很困惑。所以,我转向你。是否有一种简单有效的方法来查找图像中的主色。