본문 바로가기

Deep Learning

[tensorflow] How to read a bmp file and feed it into CNN

반응형

** BMP, JPG 등 이미지 파일 읽어서 feed_dict 형식으로 CNN 입력하기 **


Assume you trained a CNN which takes RGB image of size (height, width, channel) as an input.

After loading the trained CNN graph from, you may want to feed a test image into the CNN and see the inference result.

 

// CODE ///////////////////////////

import tensorflow as tf
import numpy as np
import os
import skimage.io as io
from skimage import transform
from PIL import Image
from scipy import ndimage

def make_cnn_input(input):

# crop input image
input_crop = input[120:240, :, :]

# data type conversion
input_crop_ = input_crop.astype('float32')

# expend dimension (mini_batch_size, height, width, channel)
output = np.expand_dims(input_crop_, 0)

return output

# save trained net
net_dir = 'path_to_saved_network'
image_path = 'path_to_bmp_files'


with tf.Session() as sess:

# Step1) Load graph from meta file (meta file contains the graph that I had defined before)
saver = tf.train.import_meta_graph(os.path.join(net_dir, 'saved_checkpoint-0.meta'))

# Step2) Restore all the weights values
saver.restore(sess, os.path.join(net_dir, 'saved_checkpoint-0'))
print('Trained Deep Network is restored')

# Step3) Recall placeholder and operation
graph = tf.get_default_graph()
x = graph.get_tensor_by_name("input_node:0")
r = graph.get_tensor_by_name("output_node:0")

# # EVALUATION
overal_cnt = 0
for step in range(0, num_images):

if (overal_cnt > -1):

# # Load test data
img = io.imread(parse_file_name_read(image_path, overal_cnt))
X_ = make_cnn_input(img)

# # Do regression
regression = sess.run([r], feed_dict={x: X_})

overal_cnt = overal_cnt + 1

sess.close()