【问题标题】:Checking if image is mostly black and white or color检查图像是否主要是黑白或彩色
【发布时间】:2018-11-29 14:14:00
【问题描述】:

我正在尝试分类图像是否主要包含黑白或彩色,准确地说是影印照片(想想施乐),主要是黑白的。图像不是单通道图像,但 3 通道图像。

我只是想知道是否有任何明显的方法可以解决我缺少的问题。

现在我正在尝试绘制直方图并且可能会进行像素计数,但这看起来不太有希望,对此的任何建议都会非常有帮助。

提前致谢。

【问题讨论】:

  • 你是指真实的BW还是灰度?
  • 图像是彩色图像,但图像中的主要对象将是黑白对象。
  • 你有示例图片吗?`
  • 当然,给我一分钟发帖
  • 如您所见,图像大部分是黑白的,但不完全。

标签: python image-processing


【解决方案1】:

我不确定确切的用例,但在遇到类似问题后,我使用了这篇很有帮助的文章。

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

【讨论】:

  • 您好,感谢您的回复。让我看看这是否有效
  • 请将相关代码部分复制到这里,以防链接失效。
  • 谢谢,一切准备就绪
猜你喜欢
  • 2021-04-14
  • 1970-01-01
  • 2013-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多