绘制灰度图像的直方图

时间:2017-03-07 03:48:35

标签: python matplotlib

我试图找到一种方法来找到灰度图像的直方图。所以首先我发现图像的平均重量然后将其输出为灰度,很好。我只是把灰色图像绘制成直方图而感到困惑。有人可以帮我弄清楚如何将灰度图像绘制成直方图吗?

import numpy as np
import matplotlib.pyplot as py
from PIL import Image as im
from scipy import misc


img = misc.imread("Zpicture.jpg")

def weightedAverage(pixel): ## function to calculate
    return 0.299*pixel[0] + 0.587*pixel[1] + 0.114*pixel[2]

grey = np.zeros((img.shape[0], img.shape[1])) # init 2D numpy array
# get row number
for rownum in range(len(img)):
 for colnum in range(len(img[rownum])):
  grey[rownum][colnum] = weightedAverage(img[rownum][colnum])


 py.imshow(grey, cmap = py.matplotlib.cm.Greys_r)
 py.show()

3 个答案:

答案 0 :(得分:3)

我认为您正在寻找plt.hist(grey)。请注意,通常的约定是导入matplotlib.pyplot plt。坚持使用常用款式很好!

最后,您的图片转换代码可以简化为:

grey = 0.299*img[:,:,0] + 0.587*img[:,:,0] + 0.114*img[:,:,0]

答案 1 :(得分:0)

考虑使用Seaborn。它是Matplotlib的包装器,提供稍微简化的API。

import seaborn as sn

sn.distplot(grey, bins=100, kde=False)
sn.plt.show()

检查文档中的关键字参数。设置为kde的{​​{1}}将执行直方图的KDE拟合。

答案 2 :(得分:0)

您可以使用matplotlib.pyplot.histnumpy.ndarray.ravel()

from matplotlib import pyplot as plt

gray_image = cv2.imread("Zpicture.jpg", cv2.IMREAD_GRAYSCALE)
plt.hist(gray_image .ravel(), bins=255)
plt.show()

注意:我正在使用numpy-v1.15

相关问题