图像灰度直方图用来统计0到255的各灰度值在图像中的出现频次,也就是有多少个像素的值为0,多少个像素的值为1,等等。对于彩色图像,直方图为红、绿、蓝各分量的统计结果。

from os.path import isfile

from PIL import Image

def his(imageFile):

#确保参数为图像文件
    assert isfile(imageFile) and imageFile.endswith(('.bmp', '.jpg', '.png')), 'Must be image file'
    #打开图像文件
    im = Image.open(imageFile)
    #获取图像颜色深度
    c = im.getpixel((0,0))
    #默认为彩色图像
    flag = False
    #灰度图像
    if isinstance(c, int):
        flag = True
    r = [0] * 256
    g = [0] * 256
    b = [0] * 256
    #获取图像尺寸
    width, height = im.size
    for w in range(width):
        for h in range(height):
            #读取像素颜色,并统计各分量值的频次
            c = im.getpixel((w,h))
            if flag:
                r[c] += 1
            else:
                r[c[0]] += 1
                g[c[1]] += 1
                b[c[2]] += 1
    if flag:
        return r
    else:
        return r+g+b
def his1(imageFile):
    #真正使用时建议直接直接使用pillow库中Image对象的histogram()获取直方图
    im = Image.open(imageFile)
    return im.histogram()
print(his('6.jpg')==his1('6.jpg'))