0-4 「Python Numpy R,G,B 色分割」
PILで取得した画像データをNumpy配列へ代入し、R,G,B各色について、色分割して表示する実験をしました。
#!/usr/bin/python # -*- coding: utf-8 -*- # カラー画像から、R,G,Bの色情報を取り出す。 from PIL import Image import numpy as np from matplotlib import pylab as plt # 画像の読み込み im = np.array(Image.open('input2x3.bmp')) print(im) # imの中身は以下 # [[[255 0 0] # [ 0 255 0] # [ 0 0 255]] # # [[ 0 0 0] # [128 128 128] # [255 255 255]]] # 画像の表示 plt.imshow(im) plt.show() # 赤のみ抽出し表示 img_red = im.copy() img_red[:, :, 1] = 0 # 緑ゼロ img_red[:, :, 2] = 0 # 青ゼロ print(img_red) # im_redの中身は以下 # Green,Blueの色は、0となっている # [[[255 0 0] # [ 0 0 0] # [ 0 0 0]] # # [[ 0 0 0] # [128 0 0] # [255 0 0]]] # 画像の表示 plt.imshow(img_red) plt.show() # 緑のみ抽出し表示 img_green = im.copy() img_green[:, :, 0] = 0 # 赤ゼロ img_green[:, :, 2] = 0 # 青ゼロ print(img_green) # im_greenの中身は以下 # Red,Blueの色は、0となっている # [[[ 0 0 0] # [ 0 255 0] # [ 0 0 0]] # # [[ 0 0 0] # [ 0 128 0] # [ 0 255 0]]] # 画像の表示 plt.imshow(img_green) plt.show() # 青のみ抽出し表示 img_blue = im.copy() img_blue[:, :, 0] = 0 # 赤ゼロ img_blue[:, :, 1] = 0 # 緑ゼロ print(img_blue) # im_blueの中身は以下 # Red,Greenの色は、0となっている # [[[ 0 0 0] # [ 0 0 0] # [ 0 0 255]] # # [[ 0 0 0] # [ 0 0 128] # [ 0 0 255]]] # 画像の表示 plt.imshow(img_blue) plt.show() #保存 Image.fromarray(img_red).save('red_save.jpg') Image.fromarray(img_green).save('green_save.jpg') Image.fromarray(img_blue).save('blue_save.jpg')
実行結果
プログラムの実行結果を確認していきます。
# 画像の読み込み
>im = np.array(Image.open('input2x3.bmp'))
>print(im)
> [[[255 0 0] (ピクセル座標(0.0), RGB=(255, 0, 0) )
> [ 0 255 0] (ピクセル座標(0.1), RGB=(0, 255, 0) )
> [ 0 0 255]] (ピクセル座標(0.2), RGB=(0, 0, 255) )
>
> [[ 0 0 0] (ピクセル座標(1.0), RGB=(0, 0, 0) )
> [128 128 128] (ピクセル座標(1.1), RGB=(128, 128, 128) )
> [255 255 255]]] (ピクセル座標(1.2), RGB=(255, 255, 255) )
ピクセル座標の値に対して、各色が割り当てられています。
# 赤のみ抽出し表示
>img_red = im.copy()
>img_red[:, :, 1] = 0 # 緑ゼロ
>img_red[:, :, 2] = 0 # 青ゼロ
>print(img_red)
> [[[255 0 0]
> [ 0 0 0]
> [ 0 0 0]]
>
> [[ 0 0 0]
> [128 0 0]
> [255 0 0]]]
Green,Blueの色は、0となっていることが確認できます。
同様に、緑のみ抽出し表示した場合は、Red,Blueの色は、0となっていることがわかります。
> [[[ 0 0 0]
> [ 0 255 0]
> [ 0 0 0]]
>
> [[ 0 0 0]
> [ 0 128 0]
> [ 0 255 0]]]
青のみ抽出し表示た場合も同様の結果となり、Red,Greenの色は、0となります。
> [[[ 0 0 0]
> [ 0 0 0]
> [ 0 0 255]]
>
> [[ 0 0 0]
> [ 0 0 128]
> [ 0 0 255]]]