如何用OpenCV在Python中找到图像的平均颜色?

2024-05-13 19:45:02 发布

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

我试过这个密码:

import cv2
image = cv2.imread("sample.jpg")
pixel = image[200, 550]
print pixel

但我的错误是:

'Nonetype' no attributes error getitem

执行第三行代码后将显示此错误。


Tags: samplenoimageimport密码错误errorcv2
3条回答

如何修正错误

发生此错误有两个潜在原因:

  1. 文件名拼写错误。
  2. 图像文件不在当前工作目录中。

若要解决此问题,应确保文件名拼写正确(请执行区分大小写的检查,以防万一),并且图像文件位于当前工作目录中(此处有两个选项:您可以更改IDE中的当前工作目录或指定文件的完整路径)。

平均颜色与主色

然后要计算“平均颜色”,你必须决定你所指的是什么。在灰度图像中,它只是整个图像灰度的平均值,但对于颜色来说,没有所谓的“平均值”。实际上,颜色通常是通过三维矢量来表示的,而灰度则是标量。平均标量是可以的,但平均向量是没有意义的。

将图像分割成彩色分量并取其平均值是一种可能的方法。然而,这种方法可能会产生一种毫无意义的色彩。你可能真正想要的是主色而不是平均色。

实施

让我们慢慢地检查代码。我们首先导入必要的模块并读取图像:

import cv2
import numpy as np
from skimage import io

img = io.imread('https://i.stack.imgur.com/DNM65.png')[:, :, :-1]

然后,我们可以按照与@Ruan B提出的方法类似的方法计算每个色通道的平均值:

average = img.mean(axis=0).mean(axis=0)

接下来,我们应用k-means clustering创建一个具有图像最具代表性颜色的调色板(在这个玩具示例中,n_colors被设置为5)。

pixels = np.float32(img.reshape(-1, 3))

n_colors = 5
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1)
flags = cv2.KMEANS_RANDOM_CENTERS

_, labels, palette = cv2.kmeans(pixels, n_colors, None, criteria, 10, flags)
_, counts = np.unique(labels, return_counts=True)

最后,主色是在量化图像上出现频率最高的调色板颜色:

dominant = palette[np.argmax(counts)]

结果比较

为了说明这两种方法之间的差异,我使用了以下示例图像:

lego

所获得的平均颜色值,即其成分是三个色通道平均值的颜色,以及通过k-平均值聚类计算出的主色是相当不同的:

In [30]: average
Out[30]: array([91.63179156, 69.30190754, 58.11971896])

In [31]: dominant
Out[31]: array([179.3999  ,  27.341282,   2.294441], dtype=float32)

让我们看看这些颜色看起来如何,以便更好地理解这两种方法之间的差异。下图左侧显示的是平均颜色。很明显,计算出的平均颜色不能正确地描述原始图像的颜色内容。事实上,在原始图像中没有一个像素有这种颜色。图的右侧显示了按重要性(出现频率)降序从上到下排序的五种最具代表性的颜色。这个调色板很明显地表明,主色调是红色,这与原始图像中最大的均匀颜色区域对应于红色乐高玩具的事实是一致的。

Results

这是用于生成上图的代码:

import matplotlib.pyplot as plt

avg_patch = np.ones(shape=img.shape, dtype=np.uint8)*np.uint8(average)

indices = np.argsort(counts)[::-1]   
freqs = np.cumsum(np.hstack([[0], counts[indices]/counts.sum()]))
rows = np.int_(img.shape[0]*freqs)

dom_patch = np.zeros(shape=img.shape, dtype=np.uint8)
for i in range(len(rows) - 1):
    dom_patch[rows[i]:rows[i + 1], :, :] += np.uint8(palette[indices[i]])

fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(12,6))
ax0.imshow(avg_patch)
ax0.set_title('Average color')
ax0.axis('off')
ax1.imshow(dom_patch)
ax1.set_title('Dominant colors')
ax1.axis('off')
plt.show(fig)

TL;DR应答

总之,尽管平均颜色的计算——正如@Ruan B.的答案中所建议的那样——从数学角度来看在技术上是正确的,但得到的结果可能不能充分代表图像的颜色内容。一种更合理的方法是通过矢量量化(聚类)来确定主色。

另一种使用K-Means Clustering确定^{}图像中主色的方法


输入图像

结果

对于n_clusters=5,这里是最主要的颜色和百分比分布

[76.35563647 75.38689122 34.00842057] 7.92%
[200.99049989  31.2085501   77.19445073] 7.94%
[215.62791291 113.68567694 141.34945328] 18.85%
[223.31013152 172.76629675 188.26878339] 29.26%
[234.03101989 217.20047979 229.2345317 ] 36.03%

每个颜色簇的可视化

enter image description here

n_clusters=10相似

[161.94723762 137.44656853 116.16306634] 3.13%
[183.0756441    9.40398442  50.99925105] 4.01%
[193.50888866 168.40201684 160.42104169] 5.78%
[216.75372674  60.50807092 107.10928817] 6.82%
[73.18055782 75.55977818 32.16962975] 7.36%
[226.25900564 108.79652434 147.49787087] 10.44%
[207.83209569 199.96071651 199.48047163] 10.61%
[236.01218943 151.70521203 182.89174295] 12.86%
[240.20499237 189.87659523 213.13580544] 14.99%
[235.54419627 225.01404087 235.29930545] 24.01%

enter image description here

import cv2, numpy as np
from sklearn.cluster import KMeans

def visualize_colors(cluster, centroids):
    # Get the number of different clusters, create histogram, and normalize
    labels = np.arange(0, len(np.unique(cluster.labels_)) + 1)
    (hist, _) = np.histogram(cluster.labels_, bins = labels)
    hist = hist.astype("float")
    hist /= hist.sum()

    # Create frequency rect and iterate through each cluster's color and percentage
    rect = np.zeros((50, 300, 3), dtype=np.uint8)
    colors = sorted([(percent, color) for (percent, color) in zip(hist, centroids)])
    start = 0
    for (percent, color) in colors:
        print(color, "{:0.2f}%".format(percent * 100))
        end = start + (percent * 300)
        cv2.rectangle(rect, (int(start), 0), (int(end), 50), \
                      color.astype("uint8").tolist(), -1)
        start = end
    return rect

# Load image and convert to a list of pixels
image = cv2.imread('1.png')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
reshape = image.reshape((image.shape[0] * image.shape[1], 3))

# Find and display most dominant colors
cluster = KMeans(n_clusters=5).fit(reshape)
visualize = visualize_colors(cluster, cluster.cluster_centers_)
visualize = cv2.cvtColor(visualize, cv2.COLOR_RGB2BGR)
cv2.imshow('visualize', visualize)
cv2.waitKey()

我可以通过以下方法得到平均颜色:

import cv2
import numpy
myimg = cv2.imread('image.jpg')
avg_color_per_row = numpy.average(myimg, axis=0)
avg_color = numpy.average(avg_color_per_row, axis=0)
print(avg_color)

结果:

[ 197.53434769  217.88439451  209.63799938]

Great Resource which I referenced

相关问题 更多 >