我正在尝试对图像是否主要包含黑白或彩色进行分类,确切地说,它是复印件的照片(如xerox),大多数为黑白。图像不是单通道图像,但3通道图像。
我只想知道是否有任何明显的方法可以解决这一遗失的问题。
目前我正尝试绘制直方图,可能只是进行像素计数,但这看起来并不十分有希望,对此的任何建议将非常有帮助。
谢谢。
答案 0 :(得分:0)
我不确定确切的用例,但是在遇到类似问题时,我使用了这篇很有帮助的文章。
https://www.alanzucconi.com/2015/05/24/how-to-find-the-main-colours-in-an-image/
包含完整代码的GitHub可在以下位置找到:https://gist.github.com/jayapal/077f63f3163abbfb3c50c7d209524cc6
如果这是您自己的视觉效果,则直方图就足够了,但是如果您尝试自动进行,则将颜色值向上或向下取整可能会有所帮助,这将提供有关图像是暗还是亮的信息。一定的值。
从更大的角度来看,您将这段代码用于什么?也许这将有助于提供更充分的信息
编辑:上面的代码还提供了定义图像区域的功能,希望这将使您的选择更加准确
直接添加代码
from sklearn.cluster import KMeans
from sklearn import metrics
import cv2
import numpy as np
import cv2
image = cv2.imread("red.png")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Resize it
h, w, _ = image.shape
w_new = int(100 * w / max(w, h) )
h_new = int(100 * h / max(w, h) )
image = cv2.resize(image, (w_new, h_new));
# Reshape the image to be a list of pixels
image_array = image.reshape((image.shape[0] * image.shape[1], 3))
print image_array
# Clusters the pixels
clt = KMeans(n_clusters = 3)
clt.fit(image_array)
def centroid_histogram(clt):
# grab the number of different clusters and create a histogram
# based on the number of pixels assigned to each cluster
numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)
(hist, _) = np.histogram(clt.labels_, bins = numLabels)
# normalize the histogram, such that it sums to one
hist = hist.astype("float")
hist /= hist.sum()
# return the histogram
return hist
# Finds how many pixels are in each cluster
hist = centroid_histogram(clt)
# Sort the clusters according to how many pixel they have
zipped = zip (hist, clt.cluster_centers_)
zipped.sort(reverse=True, key=lambda x : x[0])
hist, clt.cluster_centers = zip(*zipped)
# By Adrian Rosebrock
import numpy as np
import cv2
bestSilhouette = -1
bestClusters = 0;
for clusters in range(2, 10):
# Cluster colours
clt = KMeans(n_clusters = clusters)
clt.fit(image_array)
# Validate clustering result
silhouette = metrics.silhouette_score(image_array, clt.labels_,
metric='euclidean')
# Find the best one
if silhouette > bestSilhouette:
bestSilhouette = silhouette;
bestClusters = clusters;
print bestSilhouette
print bestClusters