[keras] 이미지 파일 읽어서 numpy로 (나중에 다시 코딩하기 귀찮음)

2020. 10. 23. 18:16파이썬

tensorflow 1.15.0

keras 2.3.1

# -*- coding: utf-8 -*-
import os
import numpy as np
from keras.preprocessing import image


X = []
Y = []
filenames = []
z = 0

dataset_dir = 'D:/DataDir/'

print(os.walk(dataset_dir))

for subdir, dirs, files in os.walk(dataset_dir):
    print('subdir : ', subdir, 'dirs : ', dirs)
    for f_path in files[:]:
        if f_path.endswith('png'):
            img = image.load_img(os.path.join(subdir, f_path),
                                     #target_size=None,
                                     target_size=(128, 128),
                                     # grayscale=True, color_mode='rgb')
                                     color_mode='grayscale')
            #print(type(img))
            img = image.img_to_array(img)
            #print(type(img))
            img = img/255.0
            X.append(img)
            #print(type(X))


print(type(X), len(X))
X = np.array(X)
print(type(X), X.shape)
X = X.reshape((X.shape[0], -1))
print(type(X), X.shape)

 

** 결과

<class 'list'> 1512
<class 'numpy.ndarray'> (1512, 256, 256, 1)
<class 'numpy.ndarray'> (1512, 65536)