Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TinyYOLOv3 Finetuning #613

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 97 additions & 21 deletions imageai/Detection/Custom/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
import numpy as np
import json
from imageai.Detection.Custom.voc import parse_voc_annotation
from imageai.Detection.Custom.yolo import create_yolov3_model, dummy_loss
from imageai.Detection.YOLOv3.models import yolo_main
from imageai.Detection.Custom.yolo import create_yolov3_model, create_tinyyolov3_model, dummy_loss
from imageai.Detection.YOLOv3.models import yolo_main, tiny_yolo_main
from imageai.Detection.Custom.generator import BatchGenerator
from imageai.Detection.Custom.tinyyolov3_generator import TinyYOLOv3BatchGenerator
from imageai.Detection.Custom.utils.utils import normalize, evaluate, makedirs
from keras.callbacks import ReduceLROnPlateau
from keras.optimizers import Adam
Expand Down Expand Up @@ -74,6 +75,14 @@ def setModelTypeAsYOLOv3(self):
"""
self.__model_type = "yolov3"

def setModelTypeAsTinyYOLOv3(self):
"""
'setModelTypeAsTinyYOLOv3()' is used to set the model type to the TinyYOLOv3 model
for the training instance object .
:return:
"""
self.__model_type = "tinyyolov3"

def setDataDirectory(self, data_directory):

"""
Expand Down Expand Up @@ -166,9 +175,16 @@ def setTrainConfig(self, object_names_array, batch_size=4, num_experiments=100,
:return:
"""

if self.__model_type == "tinyyolov3":
num_anchors = 6
elif self.__model_type == "yolov3":
num_anchors = 9
else:
raise ValueError(f'Unsupported model type: {self.__model_type}')
self.__model_anchors, self.__inference_anchors = generateAnchors(self.__train_annotations_folder,
self.__train_images_folder,
self.__train_cache_file, self.__model_labels)
self.__train_cache_file, self.__model_labels,
num_anchors)

self.__model_labels = sorted(object_names_array)
self.__num_objects = len(object_names_array)
Expand Down Expand Up @@ -220,6 +236,8 @@ def trainModel(self):
###############################
# Create the generators
###############################
if self.__model_type == "tinyyolov3":
BatchGenerator = TinyYOLOv3BatchGenerator
train_generator = BatchGenerator(
instances=train_ints,
anchors=self.__model_anchors,
Expand Down Expand Up @@ -527,12 +545,47 @@ def _create_model(
):
if len(multi_gpu) > 1:
with tf.device('/cpu:0'):
if self.__model_type == "yolov3":
template_model, infer_model = create_yolov3_model(
nb_class=nb_class,
anchors=anchors,
max_box_per_image=max_box_per_image,
max_grid=max_grid,
batch_size=batch_size // len(multi_gpu),
warmup_batches=warmup_batches,
ignore_thresh=ignore_thresh,
grid_scales=grid_scales,
obj_scale=obj_scale,
noobj_scale=noobj_scale,
xywh_scale=xywh_scale,
class_scale=class_scale
)
elif self.__model_type == "tinyyolov3":
template_model, infer_model = create_tinyyolov3_model(
nb_class=nb_class,
anchors=anchors,
max_box_per_image=max_box_per_image,
max_grid=max_grid,
batch_size=batch_size // len(multi_gpu),
warmup_batches=warmup_batches,
ignore_thresh=ignore_thresh,
grid_scales=grid_scales,
obj_scale=obj_scale,
noobj_scale=noobj_scale,
xywh_scale=xywh_scale,
class_scale=class_scale
)
else:
raise ValueError(f'Unsupported model type: {self.__model_type}')
else:
print('Hello world\n\n\n\n\n', self.__model_type)
if self.__model_type == "yolov3":
template_model, infer_model = create_yolov3_model(
nb_class=nb_class,
anchors=anchors,
max_box_per_image=max_box_per_image,
max_grid=max_grid,
batch_size=batch_size // len(multi_gpu),
batch_size=batch_size,
warmup_batches=warmup_batches,
ignore_thresh=ignore_thresh,
grid_scales=grid_scales,
Expand All @@ -541,21 +594,23 @@ def _create_model(
xywh_scale=xywh_scale,
class_scale=class_scale
)
else:
template_model, infer_model = create_yolov3_model(
nb_class=nb_class,
anchors=anchors,
max_box_per_image=max_box_per_image,
max_grid=max_grid,
batch_size=batch_size,
warmup_batches=warmup_batches,
ignore_thresh=ignore_thresh,
grid_scales=grid_scales,
obj_scale=obj_scale,
noobj_scale=noobj_scale,
xywh_scale=xywh_scale,
class_scale=class_scale
)
elif self.__model_type == "tinyyolov3":
template_model, infer_model = create_tinyyolov3_model(
nb_class=nb_class,
anchors=anchors,
max_box_per_image=max_box_per_image,
max_grid=max_grid,
batch_size=batch_size,
warmup_batches=warmup_batches,
ignore_thresh=ignore_thresh,
grid_scales=grid_scales,
obj_scale=obj_scale,
noobj_scale=noobj_scale,
xywh_scale=xywh_scale,
class_scale=class_scale
)
else:
raise ValueError(f'Unsupported model type: {self.__model_type}')

# load the pretrained weight if exists, otherwise load the backend weight only

Expand Down Expand Up @@ -639,6 +694,18 @@ def loadModel(self):
self.__model = yolo_main(Input(shape=(None, None, 3)), 3, len(self.__model_labels))

self.__model.load_weights(self.__model_path)
elif self.__model_type == "tinyyolov3":
detection_model_json = json.load(open(self.__detection_config_json_path))

self.__model_labels = detection_model_json["labels"]
self.__model_anchors = detection_model_json["anchors"]

self.__detection_utils = CustomDetectionUtils(labels=self.__model_labels)

self.__model = tiny_yolo_main(Input(shape=(None, None, 3)), 3, len(self.__model_labels))

self.__model.load_weights(self.__model_path)


def detectObjectsFromImage(self, input_image="", output_image_path="", input_type="file", output_type="file",
extract_detected_objects=False, minimum_percentage_probability=50, nms_treshold=0.4,
Expand Down Expand Up @@ -762,7 +829,7 @@ def detectObjectsFromImage(self, input_image="", output_image_path="", input_typ
# expand the image to batch
image = np.expand_dims(image, 0)

if self.__model_type == "yolov3":
if self.__model_type == "yolov3" or self.__model_type == "tinyyolov3":
if thread_safe == True:
with K.get_session().graph.as_default():
yolo_results = self.__model.predict(image)
Expand Down Expand Up @@ -901,6 +968,15 @@ def loadModel(self):

self.__detector = detector
self.__model_loaded = True
elif(self.__model_type == "tinyyolov3"):
detector = CustomObjectDetection()
detector.setModelTypeAsTinyYOLOv3()
detector.setModelPath(self.__model_path)
detector.setJsonPath(self.__detection_config_json_path)
detector.loadModel()

self.__detector = detector
self.__model_loaded = True


def detectObjectsFromVideo(self, input_file_path="", camera_input=None, output_file_path="", frames_per_second=20,
Expand Down Expand Up @@ -1015,7 +1091,7 @@ def detectObjectsFromVideo(self, input_file_path="", camera_input=None, output_f
video_frames_count = 0


if(self.__model_type == "yolov3"):
if(self.__model_type == "yolov3" or self.__model_type == "tinyyolov3"):



Expand Down
4 changes: 2 additions & 2 deletions imageai/Detection/Custom/gen_anchors.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,10 @@ def run_kmeans(ann_dims, anchor_num):
old_distances = distances.copy()


def generateAnchors(train_annotation_folder, train_image_folder, train_cache_file, model_labels):
def generateAnchors(train_annotation_folder, train_image_folder, train_cache_file, model_labels,
num_anchors=9):

print("Generating anchor boxes for training images and annotation...")
num_anchors = 9

train_imgs, train_labels = parse_voc_annotation(
train_annotation_folder,
Expand Down
Loading