LoginSignup
1
4

More than 5 years have passed since last update.

画像データをnumpyに変化しよう

Last updated at Posted at 2019-04-24

このメモは画像データをnumpyに変換するScriptを書きます。
まずは必要なライブラリーをインストールしますね!

pip install pillow

Folder構成

Folderの中にclsA,clsB,clsC3つのFolderがありまして、中に200枚つつの.jpg写真があります。
絵からみるとこんな感じかな:

|-clsA
| |-photo1.jpg..etc
|-clsB
| |-photo1.jpg..etc
|-clsC
| |-photo1.jpg..ec

流れ

  1. 各Folderの名前を配列として初期化します。
  2. 画像用のTemp配列とLabel用のTemp配列を作成します。
  3. For loopでFolderの中にLoopし、Patternが同じFileを探します。
  4. もう1個もFor loop始まり、Pillowライブラリーを使ってImageを処理します。
  5. 処理から出てきたデータをTemp配列に入れます。
  6. 最後はnumpy配列に変換します。

…って感じかな?

各Folderの名前を配列として初期化

from PIL import Image
import os,glob
import numpy as np

classes=['clsA','clsB','clsC']
num_classes=len(classes)

#resize the image to 50px
image_size=50

画像用のTemp配列とLabel用のTemp配列を作成

#image data
X=[]

#label data
Y=[]

For loopでFolderの中にLoopし、Patternが同じFileを探し

for index,clss in enumerate(classes):
    photos_dir='./'+clss
    #get the same pattern of files
    #in this case is .jpg files
    files=glob.glob(photos_dir+'/*.jpg')

Pillowライブラリーを使ってImageを処理

    for i,file in enumerate(files):
        #in this apps, only have 200 pictures
        if i >=200:
            break

        image=Image.open(file)
        image=image.convert('RGB')
        image=image.resize((image_size,image_size))
        data=np.asarray(image)

        #0=clsA
        #1=clsB
        #2=clsC
        X.append(data)
        Y.append(index)

numpy配列に変換

#change to numpy array
X=np.array(X)
Y=np.array(Y)

Scriptの全体

from PIL import Image
import os,glob
import numpy as np
from sklearn.model_selection import cross_validate

#the name of your classes but also the path name
classes=['clsA','clsB','clsC']
num_classes=len(classes)

#resize the image to 50px
image_size=50

#load the images

#image data
X=[]

#label data
Y=[]

for index,clss in enumerate(classes):
    photos_dir='./'+clss
    #get the same pattern of files
    #in this case is .jpg files
    files=glob.glob(photos_dir+'/*.jpg')
    for i,file in enumerate(files):
        #in this apps, only have 200 pictures
        if i >=200:
            break

        image=Image.open(file)
        image=image.convert('RGB')
        image=image.resize((image_size,image_size))
        data=np.asarray(image)

        X.append(data)
        Y.append(index)

#change to numpy array
X=np.array(X)
Y=np.array(Y)

実行してみよう

Xの長さは600になり、つまり200x3になります。

len(X)

Yの100番、200番、300番にもそれぞれ0,1,2がちゃんと配られるとわかってます。

Y[100]
Y[200]
Y[400]
1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4