温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Colored Histogram HSV 1D
matplotlib opencv python

python - 彩色直方图HSV 1D

发布于 2020-12-10 12:13:06

我想从这样的图像创建直方图1d

在此处输入图片说明

但是我不知道该怎么做。有谁能够帮助我?

这是我的HSV直方图的简单代码:

from matplotlib import pyplot as plt
import cv2

image = cv2.imread('sample/sample4.jpg')

cv2.cvtColor(image, cv2.COLOR_RGB2HSV)

H, S, V = image[:,:,0],image[:,:,1],image[:,:,2]

plt.figure(figsize=(10,8))
plt.subplot(311)                             #plot in the first cell
plt.subplots_adjust(hspace=.5)
plt.title("Hue")
plt.hist(np.ndarray.flatten(H), bins=180)
plt.subplot(312)                             #plot in the second cell
plt.title("Saturation")
plt.hist(np.ndarray.flatten(S), bins=128)
plt.subplot(313)                             #plot in the third cell
plt.title("Luminosity Value")
plt.hist(np.ndarray.flatten(V), bins=128)
plt.show()

谢谢帮我

查看更多

提问者
Angelo Gabriel Abrita
被浏览
0
fmw42 2020-06-22 15:00

这是使用Python / OpenCV / Scipy / Matplotpy做到这一点的一种方法,但是使用BGR颜色。

  • 读取输入
  • 使用kmeans将颜色减少到16种颜色
  • 获取独特颜色的数组和独特颜色的数量
  • 将每个计数绘制为由颜色着色的条形图
  • 保存结果

输入:

在此处输入图片说明

import cv2
import numpy as np
from matplotlib import pyplot as plt
from sklearn import cluster

# read image into range 0 to 1
img = cv2.imread('barn.jpg') / 255

# set number of colors
number = 16

# quantize to 16 colors using kmeans
h, w, c = img.shape
img2 = img.reshape(h*w, c)
kmeans_cluster = cluster.KMeans(n_clusters=number)
kmeans_cluster.fit(img2)
cluster_centers = kmeans_cluster.cluster_centers_
cluster_labels = kmeans_cluster.labels_

# need to scale back to range 0-255 and reshape
img3 = cluster_centers[cluster_labels].reshape(h, w, c)*255.0
img3 = img3.astype('uint8')

cv2.imshow('reduced colors',img3)
cv2.waitKey(0)
cv2.destroyAllWindows()

# reshape img to 1 column of 3 colors
# -1 means figure out how big it needs to be for that dimension
img4 = img3.reshape(-1,3)

# get the unique colors
colors, counts = np.unique(img4, return_counts=True, axis=0)
print(colors)
print("xxx")
print(counts)
unique = zip(colors,counts)

# function to convert from r,g,b to hex 
def encode_hex(color):
    b=color[0]
    g=color[1]
    r=color[2]
    hex = '#'+str(bytearray([r,g,b]).hex())
    print(hex)
    return hex

# plot each color
fig = plt.figure()
for i, uni in enumerate(unique):
    color = uni[0]
    count = uni[1]
    plt.bar(i, count, color=encode_hex(color))

# show and save plot
plt.show()
fig.savefig('barn_color_historgram.png')
plt.close(fig) 

生成的彩色直方图图:

在此处输入图片说明