Skip to content

Instantly share code, notes, and snippets.

@jrichardsz
Last active January 16, 2022 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrichardsz/0d386ea1d78403f04c954584394eef92 to your computer and use it in GitHub Desktop.
Save jrichardsz/0d386ea1d78403f04c954584394eef92 to your computer and use it in GitHub Desktop.
tensorflow
# Expected variables:
#
# STEPS
# MODEL_NAME
# BATCH_SIZE
# NUM_STEPS
# NUM_CLASSES
# UUID
echo "Detected arguments:"
for ARGUMENT in "$@"
do
KEY=$(echo $ARGUMENT | cut -f1 -d=)
VALUE=$(echo $ARGUMENT | cut -f2 -d=)
export "$KEY"=$VALUE
echo "$KEY"=$VALUE
done
EXEC_HOME=$(pwd)
if [ -z "${UUID}" ]; then
# UUID=$(uuidgen)
UUID=$(cat /proc/sys/kernel/random/uuid)
fi
echo ""
echo -n "Did you download the model? (y/n) "
read ans1
echo -n "Does the pipeline.config has the batch_size inmediatly after or train_config? (y/n) "
read ans2
echo -n "Does the pipeline.config has the tfrecord in the standard line number? (y/n) "
read ans3
echo ""
echo "################### "
echo "UUID: "$UUID
echo "################### "
TF2_WORKSPACE=$(pwd)/workspace/$MODEL_NAME/$UUID
if [ -d "$TF2_WORKSPACE" ]; then
echo "workspace already exist"
fi
mkdir -p $TF2_WORKSPACE
# download model if not exist
echo ""
echo "################### "
echo "model existence validation"
echo "################### "
if [ -d "$EXEC_HOME/models/$MODEL_NAME" ]
then
echo "Model aready exist: $EXEC_HOME/models/$MODEL_NAME"
else
echo "Model don't exist: $EXEC_HOME/models/$MODEL_NAME"
# download urls
curl --silent --output /dev/null https://raw.githubusercontent.com/tensorflow/models/master/research/object_detection/g3doc/tf2_detection_zoo.md -o $EXEC_HOME/models/tf2_detection_zoo.md
# cat $EXEC_HOME/models/tf2_detection_zoo.md | grep -Eo "(http|https)://[a-zA-Z0-9./?=_%:-]*" | grep "download.tensorflow" > $EXEC_HOME/models/tf2_detection_zoo_urls.txt
# cat $EXEC_HOME/models/tf2_detection_zoo_urls.txt
model_name_ocurrence_line=$(grep -n -m 1 "$MODEL_NAME" $EXEC_HOME/models/tf2_detection_zoo_urls.txt | cut -f1 -d:)
if [ -z "${model_name_ocurrence_line}" ]; then
echo "Model $MODEL_NAME name was not found on official tensorflow2 models: https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md"
echo "Available models are:"
cat $EXEC_HOME/models/tf2_detection_zoo_urls.txt
echo "Choose one (without tar.gz) and use it as MODEL_NAME parameter and try again"
exit 1
fi
echo ""
model_download_url=$(sed $model_name_ocurrence_line"q;d" $EXEC_HOME/models/tf2_detection_zoo_urls.txt)
echo "Downloading: "$model_download_url
echo "Into: "$EXEC_HOME/models/$MODEL_NAME.tar.gz
curl -silent --output /dev/null $model_download_url -o "$EXEC_HOME/models/$MODEL_NAME.tar.gz"
# curl --silent --output /dev/null $model_download_url -o "$EXEC_HOME/models/$MODEL_NAME.tar.gz"
echo "Decompressing"
mkdir -p $EXEC_HOME/models/$MODEL_NAME
tar -xzf "$EXEC_HOME/models/$MODEL_NAME.tar.gz" -C $EXEC_HOME/models/$MODEL_NAME --strip-components=1
if [ "$?" -ne "0" ]; then
echo "Error: downloading or decompressing model"
exit 1
fi
fi
if [[ $STEPS == *"0"* ]]; then
echo ""
echo "################### "
echo "pipeline.config customization"
echo "################### "
cp $EXEC_HOME/models/$MODEL_NAME/pipeline.config $TF2_WORKSPACE
# replace num_classes: 90 > num_classes: 1
if [[ -n "$NUM_CLASSES" ]]
then
sed -i -e "s/num_classes: 90/num_classes: $NUM_CLASSES/g" $TF2_WORKSPACE/pipeline.config
echo "success num_classes customization"
fi
# replace batch_size: 24 > batch_size: 8
if [[ -n "$BATCH_SIZE" ]]
then
# sed -i -e 's/batch_size: 24/batch_size: 1/g' $TF2_WORKSPACE/pipeline.config
batch_size_train_ocurrence_line=$(grep -n -m 1 'train_config' $TF2_WORKSPACE/pipeline.config | cut -f1 -d:)
batch_size_train_ocurrence_line=$((batch_size_train_ocurrence_line+1))
sed -i $batch_size_train_ocurrence_line"s/.*/ batch_size: $BATCH_SIZE/" $TF2_WORKSPACE/pipeline.config
echo "success batch_size customization"
fi
# num_steps
if [[ -n "$NUM_STEPS" ]]
then
num_steps_ocurrence_line=$(grep -n -m 1 'num_steps' $TF2_WORKSPACE/pipeline.config | cut -f1 -d:)
sed -i $num_steps_ocurrence_line"s/.*/ num_steps: $NUM_STEPS/" $TF2_WORKSPACE/pipeline.config
echo "success num_steps customization"
fi
# fine_tune_checkpoint:
fine_tune_checkpoint_ocurrence_line=$(grep -n -m 1 'fine_tune_checkpoint:' $TF2_WORKSPACE/pipeline.config | cut -f1 -d:)
fine_tune_checkpoint_location=$EXEC_HOME/models/$MODEL_NAME/checkpoint/ckpt-0
fine_tune_checkpoint_location=$(echo $fine_tune_checkpoint_location | sed 's_/_\\/_g')
sed -i $fine_tune_checkpoint_ocurrence_line"s/.*/ fine_tune_checkpoint: \"$fine_tune_checkpoint_location\"/" $TF2_WORKSPACE/pipeline.config
echo "success fine_tune_checkpoint customization"
# label_map_path
label_map_path_ocurrences_lines=$(grep -n 'label_map_path' $TF2_WORKSPACE/pipeline.config | cut -f1 -d:)
label_map_path_location=$EXEC_HOME/label_map.pbtxt
label_map_path_location=$(echo $label_map_path_location | sed 's_/_\\/_g')
for label_map_path_ocurrence_line in `echo $label_map_path_ocurrences_lines`; do
sed -i $label_map_path_ocurrence_line"s/.*/ label_map_path: \"$label_map_path_location\"/" $TF2_WORKSPACE/pipeline.config
done
echo "success label_map_path customization"
# train.record
train_record_ocurrence_line=$(grep -n -m 1 'train_input_reader' $TF2_WORKSPACE/pipeline.config | cut -f1 -d:)
train_record_ocurrence_line=$((train_record_ocurrence_line+3))
train_record_path_location=$TF2_WORKSPACE/data/train.record
train_record_path_location=$(echo $train_record_path_location | sed 's_/_\\/_g')
sed -i $train_record_ocurrence_line"s/.*/ input_path: \"$train_record_path_location\"/" $TF2_WORKSPACE/pipeline.config
echo "success train.record customization"
# test.record
test_record_ocurrence_line=$(grep -n -m 1 'eval_input_reader' $TF2_WORKSPACE/pipeline.config | cut -f1 -d:)
test_record_ocurrence_line=$((test_record_ocurrence_line+3))
test_record_path_location=$TF2_WORKSPACE/data/test.record
test_record_path_location=$(echo $test_record_path_location | sed 's_/_\\/_g')
sed -i $test_record_ocurrence_line"s/.*/ input_path: \"$test_record_path_location\"/" $TF2_WORKSPACE/pipeline.config
echo "success test.record customization"
# fine_tune_checkpoint_type
fine_tune_checkpoint_type_ocurrence_line=$(grep -n -m 1 'fine_tune_checkpoint_type' $TF2_WORKSPACE/pipeline.config | cut -f1 -d:)
sed -i $fine_tune_checkpoint_type_ocurrence_line"s/.*/ fine_tune_checkpoint_type: \"detection\"/" $TF2_WORKSPACE/pipeline.config
echo "success fine_tune_checkpoint_type customization"
fi
if [ "$?" -ne "0" ]; then
echo "Error: pipeline.config customization"
exit 1
fi
if [[ $STEPS == *"1"* ]]; then
start_time=$(date +%s)
echo ""
echo "################### "
echo "generate tfrecord"
echo "################### "
mkdir -p $TF2_WORKSPACE/data
python3 generate_tfrecord.py -x $EXEC_HOME/images/train -l $EXEC_HOME/label_map.pbtxt -o $TF2_WORKSPACE/data/train.record
python3 generate_tfrecord.py -x $EXEC_HOME/images/test -l $EXEC_HOME/label_map.pbtxt -o $TF2_WORKSPACE/data/test.record
fi
if [ "$?" -ne "0" ]; then
bash elapsed_time.sh $start_time
echo "Error: generate tfrecord"
exit 1
else
if [[ $STEPS == *"1"* ]]; then
bash elapsed_time.sh $start_time
fi
fi
if [[ $STEPS == *"2"* ]]; then
start_time=$(date +%s)
echo ""
echo "################### "
echo "train model"
echo "################### "
rm -rf $TF2_WORKSPACE/model/trained
mkdir -p $TF2_WORKSPACE/model/trained
python3 model_main_tf2.py --model_dir=$TF2_WORKSPACE/model/trained --pipeline_config_path=$TF2_WORKSPACE/pipeline.config
fi
if [ "$?" -ne "0" ]; then
echo "Error: train model"
bash elapsed_time.sh $start_time
exit 1
else
if [[ $STEPS == *"2"* ]]; then
bash elapsed_time.sh $start_time
fi
fi
if [[ $STEPS == *"3"* ]]; then
start_time=$(date +%s)
echo ""
echo "################### "
echo "export trained model"
echo "################### "
rm -rf $TF2_WORKSPACE/model/exported
mkdir -p $TF2_WORKSPACE/model/exported
python3 $EXEC_HOME/exporter_main_v2.py --input_type image_tensor --pipeline_config_path $EXEC_HOME/pipeline.config --trained_checkpoint_dir $TF2_WORKSPACE/model/trained --output_directory $TF2_WORKSPACE/model/exported
fi
if [ "$?" -ne "0" ]; then
bash elapsed_time.sh $start_time
echo "Error: export trained model"
exit 1
else
if [[ $STEPS == *"3"* ]]; then
bash elapsed_time.sh $start_time
fi
fi
if [[ $STEPS == *"4"* ]]; then
start_time=$(date +%s)
echo ""
echo "################### "
echo "object detection"
echo "################### "
python3 object_detection_exec_v2.py $TF2_WORKSPACE/model/exported $EXEC_HOME/label_map.pbtxt $EXEC_HOME/images/detection
fi
if [ "$?" -ne "0" ]; then
bash elapsed_time.sh $start_time
echo "Error: object detection"
exit 1
else
if [[ $STEPS == *"4"* ]]; then
bash elapsed_time.sh $start_time
fi
fi
# coding: utf-8
# # Object Detection Demo
# Welcome to the object detection inference walkthrough! This notebook will walk you step by step through the process of using a pre-trained model to detect objects in an image. Make sure to follow the [installation instructions](https://github.com/tensorflow/models/blob/master/object_detection/g3doc/installation.md) before you start.
# # Imports
# In[1]:
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
# ## Env setup
# In[2]:
# This is needed to display the images.
# get_ipython().magic(u'matplotlib inline')
import matplotlib
# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")
# ## Object detection imports
# Here are the imports from the object detection module.
# In[3]:
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
# # Model preparation
# ## Variables
#
# Any model exported using the `export_inference_graph.py` tool can be loaded here simply by changing `PATH_TO_CKPT` to point to a new .pb file.
#
# By default we use an "SSD with Mobilenet" model here. See the [detection model zoo](https://github.com/tensorflow/models/blob/master/object_detection/g3doc/detection_model_zoo.md) for a list of other models that can be run out-of-the-box with varying speeds and accuracies.
# In[4]:
# What model to download.
MODELS_HOME_DIR = sys.argv[1]
MODEL_NAME = sys.argv[2]
PATH_TO_LABELS = sys.argv[3]
PATH_TO_TEST_IMAGES_DIR = sys.argv[4]
MODEL_FILE = MODEL_NAME + '.tar.gz'
DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'
# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'
# List of the strings that is used to add correct label for each box.
NUM_CLASSES = 90
# ## Download Model
# In[5]:
print( " Downloading model ")
opener = urllib.request.URLopener()
downloaded_model_aboslute_path = os.path.join(MODELS_HOME_DIR,MODEL_FILE)
opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, downloaded_model_aboslute_path)
tar_file = tarfile.open(downloaded_model_aboslute_path)
for file in tar_file.getmembers():
file_name = os.path.basename(file.name)
if 'frozen_inference_graph.pb' in file_name:
tar_file.extract(file, os.getcwd())
print (" Loading frozen model into memory")
# ## Load a (frozen) Tensorflow model into memory.
# In[6]:
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
# ## Loading label map
# Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`. Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine
# In[7]:
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)
# ## Helper code
# In[8]:
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
# # Detection
# In[9]:
# For the sake of simplicity we will use only 2 images:
# image1.jpg
# image2.jpg
# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, '{}.jpg'.format(i)) for i in range(1, 5) ]
# Size, in inches, of the output images.
IMAGE_SIZE = (12, 8)
# In[11]:
with detection_graph.as_default():
with tf.Session(graph=detection_graph) as sess:
for image_path in TEST_IMAGE_PATHS:
image = Image.open(image_path)
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
image_np = load_image_into_numpy_array(image)
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np, axis=0)
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected.
boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
scores = detection_graph.get_tensor_by_name('detection_scores:0')
classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
# Actual detection.
(boxes, scores, classes, num_detections) = sess.run(
[boxes, scores, classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
category_index,
use_normalized_coordinates=True,
line_thickness=8)
# plt.figure(figsize=IMAGE_SIZE)
# plt.imshow(image_np)
# i=0
# plt.imsave(str(i)+'image',image_np )
# In[ ]:
# In[ ]:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment