Python / PIL / 画像の読み込み、サイズの取得、RGB値の取得、輝度の計算、ヒストグラムの表示

from PIL import Image

import matplotlib.pyplot as plt
import numpy             as np

class IMAGE:
    def __init__(self, imgPath):
        self.srcImg        = Image.open(imgPath)                                  # 画像を読み込む。
        self.numOfPixels   = self.srcImg.width * self.srcImg.height               # 全画素数を取得する。
        self.AllRGB        = np.asarray(self.srcImg).reshape(self.numOfPixels, 3) # 各画素のRGB値を画像の左上からZ字順に並べ替える。
        self.AllBrightness = np.mean(self.AllRGB, axis=1, dtype="uint16")         # 各画素の輝度(ここではRGBの平均値とする)を取得する。
        
    def showImg(self):
        plt.imshow(self.srcImg)
        plt.show()
        return self
        
    def showHist(self):
        plt.figure()
        plt.xlabel("val")
        plt.ylabel("freq")
        plt.hist(self.AllBrightness, range=(-0.5, 255.5), bins=256)
        plt.show()
        return self
        
########
# test #
########
if __name__ == "__main__":
    IMAGE("H:\\img\\yuri.png").showImg().showHist()
    IMAGE("H:\\img\\mono.png").showImg().showHist()

実行結果:
f:id:ti-nspire:20180803054534p:plain:w300