【问题标题】:Weird histogram result from cv2来自 cv2 的奇怪直方图结果
【发布时间】:2017-05-03 20:08:45
【问题描述】:

所以,我在这里获取了一些用于生成和绘制颜色直方图的示例代码:http://www.pyimagesearch.com/2014/01/22/clever-girl-a-guide-to-utilizing-color-histograms-for-computer-vision-and-image-search-engines/

from matplotlib import pyplot as plt
import cv2, os, glob

os.chdir(r"....pathname....")
for file in glob.glob("*.jpg"):
    image = cv2.imread(file)
    chans = cv2.split(image)
    colors = ("b", "g", "r")
    plt.figure()
    plt.title("'Flattened' Color Histogram")
    plt.xlabel("Bins")
    plt.ylabel("# of Pixels")

    for (chan, color) in zip(chans, colors):
        hist = cv2.calcHist([chan], [0], None, [256], [0, 256])
        cv2.normalize(hist,hist,8,cv2.NORM_MINMAX)
        plt.plot(hist, color = color)
        plt.xlim([0,256])
    plt.savefig(file + '_hist.jpg')

对于大多数图像,我得到一个看起来不错的直方图,例如:

但是,对于某些图像,我得到一个基本平坦的直方图,其末端为“极端”值,如下所示:

这是原始图像,生成了后一个直方图:http://i.imgur.com/xerRgy1.jpg

谁能解释发生了什么以及为什么?

【问题讨论】:

    标签: python opencv matplotlib histogram


    【解决方案1】:

    我使用 numpy 复制了您的代码,以确保不是 cv2 做错了什么。虽然看起来不寻常,但结果实际上与图像一致。

    首先看一下每个通道的图像强度(像素值):

    您可以看到花朵在蓝色通道中具有很高的值(接近 255),而背景在红色通道中具有很高的值。在绿色通道中具有高值的像素并不多。

    计算每个通道的像素值直方图我得到相同的结果:

    代码如下:

    import matplotlib.pyplot as plt
    from PIL import Image
    import numpy as np
    
    im = np.array(Image.open('im.jpg'))
    channelNames=['R','G','B']
    
    fig, axes = plt.subplots(1,3,figsize=(10,4))
    for channel, ax in enumerate(axes):
        imshow=ax.imshow(im.T[channel].T, cmap=plt.cm.gray, vmin=0, vmax=255)
        ax.set_xticks(())
        ax.set_yticks(())
        ax.set_title(channelNames[channel])
    
    fig.colorbar(imshow,fraction=0.06, pad=0.07, shrink=1.5)
    fig.tight_layout()
    fig.subplots_adjust(right=0.9)
    fig.show()
    
    fig, ax = plt.subplots(1, figsize=(6,4))
    for channel in range(3):
        cts = np.bincount(im.T[channel].flatten())
        bins=np.arange(0,256,1)
        ax.plot(bins, cts, c=channelNames[channel])
    ax.set_xlabel('Bins')
    ax.set_ylabel('# of Pixels')
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      相关资源
      最近更新 更多