Skip to content

Instantly share code, notes, and snippets.

@rcamilo1526
Last active February 23, 2021 21:50
Show Gist options
  • Save rcamilo1526/78c38d74ff8b8284ca4ac5912dcf26b0 to your computer and use it in GitHub Desktop.
Save rcamilo1526/78c38d74ff8b8284ca4ac5912dcf26b0 to your computer and use it in GitHub Desktop.
from PIL import Image
import os
import numpy as np
import pathlib
def prepare_tif(path,output,img_height,img_widht,it='tif'):
images = []
labels = []
categories = os.listdir(path)
print(categories)
for c in categories:
data_dir = pathlib.Path(os.path.join(path,c))
tif_data = list(data_dir.glob(f'./*.{it}'))
for image in tif_data:
im = Image.open(str(image))
imarray = np.array(im)
imarray = np.reshape(imarray,(img_height,img_widht,1))
images.append(imarray)
labels.append(c)
print(f"Founded {len(images)} images from {len(set(labels))} classes")
encoded = np.zeros((len(labels), 9))
encoding = dict(zip(np.unique(labels),range(len(np.unique(labels)))))
for i in range(len(encoded)):
position = encoding[labels[i]]
encoded[i][position] = 1
np.savez_compressed(output+'.npz', x=np.array(images), y=np.array(encoded))
""" Example: use in keras
prepare_tif('images/train',output='images_np/train',img_height=200,img_widht=200)
prepare_tif('images/val',output='images_np/val',img_height=200,img_widht=200)
train_data = np.load('images_np/train.npz')
val_data = np.load('images_np/val.npz')
X = train_data['x']
y = train_data['y']
X_val = val_data['x']
y_val = val_data['y']
num_classes = len(y[0])
batch_size = 32
step_size_train = len(X)/batch_size
step_size_val = len(X_val)/batch_size
model = Sequential()
# create model with some layers
model.add(Conv2D(32, (3, 3), padding='same', input_shape=(200, 200,1), activation='relu'))
...
...
...
...
...
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X,y,
steps_per_epoch = step_size_train,
validation_data = (X_val,y_val),
validation_steps = step_size_val,
epochs=50)
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment