LoginSignup
7
9

More than 5 years have passed since last update.

画像をnumpy形式で保存する

Posted at

はじめに

画像を学習用データとテストデータに分けた時の手法のメモ

使用したモジュール

#画像を取得するため
from PIL import Image
#ファイルのパスなどを扱うので 
import os,glob
#numpy形式でファイルを保存する
import numpy as np
#データ分割用のためのscikit-learn
from sklearn import model_selection

ラベルと画像サイズ

今回はサルとイノシシとカラスの画像を用意した。

#配列を用意
classes = ["monkey","boar","crow"]
#0をサル、1をイノシシ、2をカラスとする
NumClasses = len(classes)
#画像の大きさを50*50とする
ImageSize = 50

データの変換

#変数の代入用の配列を宣言
X = []
Y = []
#0のmonkey,1のboar,3のcrowをindexに代入
#enumerate()を使うことでインデックス番号、要素の順番で取得する
for index, ClassLabel in enumerate(classes):
    PhotosDir = "./"+ClassLabel
    #写真をfilesに代入
    files = glob.glob(PhotosDir+"/*.jpg")
    for i, file in enumerate(files):
        #写真を開く
        image = Image.open(file)
        #RGBに変換
        image = image.convert("RGB")
        #大きさの統一(50*50)
        image = image.resize((ImageSize,ImageSize))
        #画像を配列に変換
        data = np.asarray(image)
        X.append(data)
        Y.append(index)

データの保存

他のプログラムで画像データを使いまわすときのためにデータを numpy 形式で保存します。

#numpy配列に変換
X = np.array(X)
Y = np.array(Y)
#テストデータと訓練用データに分割
X_train,X_test,Y_train,Y_test = model_selection.train_test_split(X,Y)
#一つの変数に保存
xy = (X_train,X_test,Y_train,Y_test)
#numpy形式で保存
np.save("./animal.npy",xy)

学習データを増やす

取得した画像を回転や左右反転することで学習データとなる画像を増やすことができます。

# 0のmonkey,1のboar,3のcrowをindexに代入
for index, ClassLabel in enumerate(classes):
    PhotosDir = "./"+ClassLabel
    # 写真をfilesに代入
    files = glob.glob(PhotosDir+"/*.jpg")
    for i, file in enumerate(files):
        # 写真を開く
        image = Image.open(file)
        # RGBに変換
        image = image.convert("RGB")
        # 大きさの統一
        image = image.resize((ImageSize, ImageSize))
        # 画像を配列に変換
        data = np.asarray(image)
        #num_testdataは100とします
        if i < num_testdata:
            X_test.append(data)
            Y_test.append(index)
        else:
        #-20度から20度まで5度ずつ回転させる
            for angle in range(-20, 20, 5):
                # 回転
                img_r = image.rotate(angle)
                data = np.asarray(img_r)
                X_train.append(data)
                Y_train.append(index)
                # 左右反転
                img_trans = image.transpose(Image.FLIP_LEFT_RIGHT)
                data = np.asarray(img_trans)
                X_train.append(data)
                Y_train.append(index)

7
9
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
7
9