15
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

大量の画像をNumpy配列に変換するプログラム作ってみた

Posted at

GitHub

import numpy as np
import glob
from keras.preprocessing.image import load_img,img_to_array
from tqdm import tqdm

IMG_SIZE=32
# True=Grayscale, False=RGB
COLOR=True
# Name to load images Folder
DIR_NAME='./Images'
# Name to save
SAVE_FILE_NAME='SaveImages'
# sahpe File Name
if COLOR:
    SAVE_FILE_NAME=SAVE_FILE_NAME+'_'+str(IMG_SIZE)+'Gray'
else:
    SAVE_FILE_NAME=SAVE_FILE_NAME+'_'+str(IMG_SIZE)+'RGB'

# load madomagi images and reshape
img_list=glob.glob(DIR_NAME+'/*.jpg')
temp_img_array_list=[]
for img in tqdm(img_list):
    temp_img=load_img(img,grayscale=COLOR,target_size=(IMG_SIZE,IMG_SIZE))
    temp_img_array=img_to_array(temp_img)
    temp_img_array_list.append(temp_img_array)


temp_img_array_list=np.array(temp_img_array_list)

# save np.array
np.save(SAVE_FILE_NAME+'.npy',temp_img_array_list)

# confirmation
print(temp_img_array_list)
print(temp_img_array_list.shape)

使い方

IMG_SIZE=32で画像の幅を指定します。ここでは32にします。
どんな形の画像でも、32x32の形に整形します。

COLOR=Trueでカラーを指定します。
Trueの場合はGrayscale。Falseの場合はRGBとなります。

DIR_NAME='./Images'に画像が入っているフォルダのパスを指定します。

SAVE_FILE_NAME='SaveImages'で保存するファイルの名前を指定します。

SnapCrab_NoName_2018-2-14_11-36-32_No-00.png SnapCrab_NoName_2018-2-14_11-46-56_No-00.png

実行すると画像のようにnpyファイルが生成されます。
今回の場合であれば、(10,32,32,1)という形のNumpy配列が保存されています。
KerasのデータセットであるMNISTやCifar10などと似たような形で利用することができます。

利用するときは

import numpy as np

ndarr=np.load('SaveImages_32Gray.npy')

といった感じですぐに利用できます。

解説

# load madomagi images and reshape
img_list=glob.glob(DIR_NAME+'/*.jpg')
temp_img_array_list=[]
for img in tqdm(img_list):
    temp_img=load_img(img,grayscale=COLOR,target_size=(IMG_SIZE,IMG_SIZE))
    temp_img_array=img_to_array(temp_img)
    temp_img_array_list.append(temp_img_array)


temp_img_array_list=np.array(temp_img_array_list)

glob()でフォルダからjpg画像の名前を一覧で取得します。
それをパスとして、load_img()で指定サイズ、カラーに変換し、その後、配列に変換しています。

15
14
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
15
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?