<jupyter_start><jupyter_text>모바일넷을 이용한 이미지분류(Image Classification using Mobilenet)성  민  석(<NAME>)--- 강의목차1&nbsp;&nbsp;Keras h5 파일을 Tensorflow pb파일로 변환2&nbsp;&nbsp;Tensorflow pb파일을 OpenVINO xml, bin파일로 변환3&nbsp;&nbsp;OpenVINO에서 xml,bin파일로 추론4&nbsp;&nbsp;Reference  Keras h5 파일을 Tensorflow pb파일로 변환<jupyter_code>%run ./utils/keras_to_freeze_binary.py ./bin/mobilenetv2_class20.h5 ./bin/mobilenetv2<jupyter_output>Using TensorFlow backend.
/home/intel/imobilenet/myvenv/lib/python3.5/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint8 = np.dtype([("qint8", np.int8, 1)])
/home/intel/imobilenet/myvenv/lib/python3.5/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint8 = np.dtype([("quint8", np.uint8, 1)])
/home/intel/imobilenet/myvenv/lib/python3.5/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint16 = np.dtype([("qint16", np.int16, 1)])
/home/intel/imobilenet/myvenv/lib/p[...]<jupyter_text>Tensorflow pb파일을 OpenVINO xml, bin파일로 변환<jupyter_code>%run /opt/intel/openvino/deployment_tools/model_optimizer/mo.py \
    --framework tf \
    --input_model ./bin/mobilenetv2.pb \
    --batch 1 \
    --data_type FP32 \
    --output_dir bin/<jupyter_output>Model Optimizer arguments:
Common parameters:
	- Path to the Input Model: 	/home/intel/imobilenet/./bin/mobilenetv2.pb
	- Path for generated IR: 	/home/intel/imobilenet/bin/
	- IR output name: 	mobilenetv2
	- Log level: 	ERROR
	- Batch: 	1
	- Input layers: 	Not specified, inherited from the model
	- Output layers: 	Not specified, inherited from the model
	- Input shapes: 	Not specified, inherited from the model
	- Mean values: 	Not specified
	- Scale values: 	Not specified
	- Scale factor: 	Not specified
	- Precision of IR: 	FP32
	- Enable fusing: 	True
	- Enable grouped convolutions fusing: 	True
	- Move mean values to preprocess section: 	False
	- Reverse input channels: 	False
TensorFlow specific parameters:
	- Input model in text protobuf format: 	False
	- Path to model dump for TensorBoard: 	None
	- List of shared libraries with TensorFlow custom layers implementation: 	None
	- Update the configuration file with input/output node names: 	None
	- Use configuration file used to gene[...]<jupyter_text>OpenVINO에서 xml,bin파일로 추론<jupyter_code>import os
# assert 'computer_vision_sdk' in os.environ['PYTHONPATH']

from PIL import Image
import numpy as np

try:
    from openvino import inference_engine as ie
    from openvino.inference_engine import IENetwork, IEPlugin
except Exception as e:
    exception_type = type(e).__name__
    print("The following error happened while importing Python API module:\n[ {} ] {}".format(exception_type, e))
    sys.exit(1)
    
    
import pickle
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing.image import load_img
def pre_process_image(imagePath, img_height=224):
    # Model input format
    n, c, h, w = [1, 3, img_height, img_height]
    image = Image.open(imagePath)
    processedImg = image.resize((h, w), resample=Image.BILINEAR)

    # Normalize to keep data between 0 - 1
    processedImg = (np.array(processedImg) - 0) / 255.0

    # Change data layout from HWC to CHW
    processedImg = processedImg.transpose((2, 0, 1))
    processedImg = processedImg.reshape((n, c, h, w))

    return image, processedImg, imagePath
# Plugin initialization for specified device and load extensions library if specified.
plugin_dir = None
model_xml = './bin/mobilenetv2.xml'
model_bin = './bin/mobilenetv2.bin'
# Devices: GPU (intel), CPU, MYRIAD
# plugin = IEPlugin("MYRIAD", plugin_dirs=plugi)
plugin = IEPlugin("CPU")
# Read IRn_dir
net = IENetwork.from_ir(model=model_xml, weights=model_bin)
assert len(net.inputs.keys()) == 1
assert len(net.outputs) == 1
input_blob = next(iter(net.inputs))
out_blob = next(iter(net.outputs))
# Load network to the plugin
exec_net = plugin.load(network=net)
del net
import os
test_list = list(map(lambda x:x.split('.')[0],os.listdir('./img/test/')))
print(test_list)
# Run inference
input_file = input('Select Test File : ')

fileName = './img/test/{}.jpg'.format(input_file)
image, processedImg, imagePath = pre_process_image(fileName)
res = exec_net.infer(inputs={input_blob: processedImg})
# Access the results and get the index of the highest confidence score
output_node_name = list(res.keys())[0]
res = res[output_node_name]
# Predicted class index.
idx = np.argsort(res[0])[-1]
# decode the predictions
with open('./bin/class20.pickle', 'rb') as f:
    labels = pickle.load(f)
    
plt.imshow(load_img(fileName))
plt.show()    
print('Predicted : {} ({:.2f}%)'.format(labels[idx].upper(),res[0][idx]*100))
import pandas as pd
pd.DataFrame(res,columns=labels.values()).T.plot(kind='bar')
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1235417861923886, 'fraction_numerical': 0.01778542742398164, 'mean_word_length': 4.557917109458024, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 7}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '363598', 'license': 'MIT', 'n_tokens_mistral': 1924, 'n_tokens_neox': 1918, 'n_words': 489, 'path': 'Lecture09 - OpenVINO Inference(MobileNet).ipynb', 'repo_name': 'minsuk-sung/intel-image-classification', 'size': '5234'}