Skip to content

Commit e6598d1

Browse files
philtradetanakataiki
authored andcommitted
Added command line option parsing
Added command option parsing, and --model, --anchors, --classes, and --gpu_num, with default values.
1 parent da7d756 commit e6598d1

3 files changed

Lines changed: 121 additions & 47 deletions

File tree

README.md

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,36 @@ A Keras implementation of YOLOv3 (Tensorflow backend) inspired by [allanzelener/
1818
```
1919
wget https://pjreddie.com/media/files/yolov3.weights
2020
python convert.py yolov3.cfg yolov3.weights model_data/yolo.h5
21-
python yolo.py OR python yolo_video.py [video_path] [output_path(optional)]
21+
python yolo_video.py [OPTIONS...] --image, for image detection mode, OR
22+
python yolo_video.py [video_path] [output_path (optional)]
2223
```
2324

24-
For Tiny YOLOv3, just do in a similar way. And modify model path and anchor path in yolo.py.
25+
For Tiny YOLOv3, just do in a similar way, just specify model path and anchor path with `--model model_file` and `--anchors anchor_file`.
2526

27+
### Usage
28+
Use --help to see usage of yolo_video.py:
29+
```
30+
usage: yolo_video.py [-h] [--model MODEL] [--anchors ANCHORS]
31+
[--classes CLASSES] [--gpu_num GPU_NUM] [--image]
32+
[--input] [--output]
33+
34+
positional arguments:
35+
--input Video input path
36+
--output Video output path
37+
38+
optional arguments:
39+
-h, --help show this help message and exit
40+
--model MODEL path to model weight file, default model_data/yolo.h5
41+
--anchors ANCHORS path to anchor definitions, default
42+
model_data/yolo_anchors.txt
43+
--classes CLASSES path to class definitions, default
44+
model_data/coco_classes.txt
45+
--gpu_num GPU_NUM Number of GPU to use, default 1
46+
--image Image detection mode, will ignore all positional arguments
47+
```
2648
---
2749

28-
4. MultiGPU usage is an optinal. Change the number of gpu and add gpu device id
50+
4. MultiGPU usage: use `--gpu_num N` to use N GPUs. It is passed to the [Keras multi_gpu_model()](https://keras.io/utils/#multi_gpu_model).
2951

3052
## Training
3153

@@ -46,8 +68,8 @@ For Tiny YOLOv3, just do in a similar way. And modify model path and anchor path
4668
4769
3. Modify train.py and start training.
4870
`python train.py`
49-
Use your trained weights or checkpoint weights in yolo.py.
50-
Remember to modify class path or anchor path.
71+
Use your trained weights or checkpoint weights with command line option `--model model_file` when using yolo_video.py
72+
Remember to modify class path or anchor path, with `--classes class_file` and `--anchors anchor_file`.
5173
5274
If you want to use original pretrained weights for YOLOv3:
5375
1. `wget https://pjreddie.com/media/files/darknet53.conv.74`

yolo.py

Lines changed: 23 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
#! /usr/bin/env python
21
# -*- coding: utf-8 -*-
32
"""
4-
Run a YOLO_v3 style detection model on test images.
3+
Class definition of YOLO_v3 style detection model on image and video
54
"""
65

76
import colorsys
@@ -17,21 +16,32 @@
1716
from yolo3.model import yolo_eval, yolo_body, tiny_yolo_body
1817
from yolo3.utils import letterbox_image
1918
import os
20-
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
2119
from keras.utils import multi_gpu_model
22-
gpu_num=1
2320

2421
class YOLO(object):
25-
def __init__(self):
26-
self.model_path = 'model_data/yolo.h5' # model path or trained weights path
27-
self.anchors_path = 'model_data/yolo_anchors.txt'
28-
self.classes_path = 'model_data/coco_classes.txt'
29-
self.score = 0.3
30-
self.iou = 0.45
22+
_defaults = {
23+
"model_path": 'model_data/yolo.h5',
24+
"anchors_path": 'model_data/yolo_anchors.txt',
25+
"classes_path": 'model_data/coco_classes.txt',
26+
"score" : 0.3,
27+
"iou" : 0.45,
28+
"model_image_size" : (416, 416),
29+
"gpu_num" : 1,
30+
}
31+
32+
@classmethod
33+
def get_defaults(cls, n):
34+
if n in cls._defaults:
35+
return cls._defaults[n]
36+
else:
37+
return "Unrecognized attribute name '" + n + "'"
38+
39+
def __init__(self, **kwargs):
40+
self.__dict__.update(self._defaults) # set up default values
41+
self.__dict__.update(kwargs) # and update with user overrides
3142
self.class_names = self._get_class()
3243
self.anchors = self._get_anchors()
3344
self.sess = K.get_session()
34-
self.model_image_size = (416, 416) # fixed size or (None, None), hw
3545
self.boxes, self.scores, self.classes = self.generate()
3646

3747
def _get_class(self):
@@ -82,8 +92,8 @@ def generate(self):
8292

8393
# Generate output tensor targets for filtered bounding boxes.
8494
self.input_image_shape = K.placeholder(shape=(2, ))
85-
if gpu_num>=2:
86-
self.yolo_model = multi_gpu_model(self.yolo_model, gpus=gpu_num)
95+
if self.gpu_num>=2:
96+
self.yolo_model = multi_gpu_model(self.yolo_model, gpus=self.gpu_num)
8797
boxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors,
8898
len(self.class_names), self.input_image_shape,
8999
score_threshold=self.score, iou_threshold=self.iou)
@@ -159,7 +169,6 @@ def detect_image(self, image):
159169
def close_session(self):
160170
self.sess.close()
161171

162-
163172
def detect_video(yolo, video_path, output_path=""):
164173
import cv2
165174
vid = cv2.VideoCapture(video_path)
@@ -201,21 +210,3 @@ def detect_video(yolo, video_path, output_path=""):
201210
break
202211
yolo.close_session()
203212

204-
205-
def detect_img(yolo):
206-
while True:
207-
img = input('Input image filename:')
208-
try:
209-
image = Image.open(img)
210-
except:
211-
print('Open Error! Try again!')
212-
continue
213-
else:
214-
r_image = yolo.detect_image(image)
215-
r_image.show()
216-
yolo.close_session()
217-
218-
219-
220-
if __name__ == '__main__':
221-
detect_img(YOLO())

yolo_video.py

Lines changed: 71 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,77 @@
11
import sys
2+
import argparse
3+
from yolo import YOLO, detect_video
4+
from PIL import Image
25

3-
if len(sys.argv) < 2:
4-
print("Usage: $ python {0} [video_path] [output_path(optional)]", sys.argv[0])
5-
exit()
6+
def detect_img(yolo):
7+
while True:
8+
img = input('Input image filename:')
9+
try:
10+
image = Image.open(img)
11+
except:
12+
print('Open Error! Try again!')
13+
continue
14+
else:
15+
r_image = yolo.detect_image(image)
16+
r_image.show()
17+
yolo.close_session()
618

7-
from yolo import YOLO
8-
from yolo import detect_video
19+
FLAGS = None
920

1021
if __name__ == '__main__':
11-
video_path = sys.argv[1]
12-
if len(sys.argv) > 2:
13-
output_path = sys.argv[2]
14-
detect_video(YOLO(), video_path, output_path)
22+
# class YOLO defines the default value, so suppress any default here
23+
parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
24+
'''
25+
Command line options
26+
'''
27+
parser.add_argument(
28+
'--model', type=str,
29+
help='path to model weight file, default ' + YOLO.get_defaults("model_path")
30+
)
31+
32+
parser.add_argument(
33+
'--anchors', type=str,
34+
help='path to anchor definitions, default ' + YOLO.get_defaults("anchors_path")
35+
)
36+
37+
parser.add_argument(
38+
'--classes', type=str,
39+
help='path to class definitions, default ' + YOLO.get_defaults("classes_path")
40+
)
41+
42+
parser.add_argument(
43+
'--gpu_num', type=int,
44+
help='Number of GPU to use, default ' + str(YOLO.get_defaults("gpu_num"))
45+
)
46+
47+
parser.add_argument(
48+
'--image', default=False, action="store_true",
49+
help='Image detection mode, will ignore all positional arguments'
50+
)
51+
'''
52+
Command line positional arguments -- for video detection mode
53+
'''
54+
parser.add_argument(
55+
"--input", nargs='?', type=str,required=False,default='./path2your_video',
56+
help = "Video input path"
57+
)
58+
59+
parser.add_argument(
60+
"--output", nargs='?', type=str, default="",
61+
help = "[Optional] Video output path"
62+
)
63+
64+
FLAGS = parser.parse_args()
65+
66+
if FLAGS.image:
67+
"""
68+
Image detection mode, disregard any remaining command line arguments
69+
"""
70+
print("Image detection mode")
71+
if "input" in FLAGS:
72+
print(" Ignoring remaining command line arguments: " + FLAGS.input + "," + FLAGS.output)
73+
detect_img(YOLO(**vars(FLAGS)))
74+
elif "input" in FLAGS:
75+
detect_video(YOLO(**vars(FLAGS)), FLAGS.input, FLAGS.output)
1576
else:
16-
detect_video(YOLO(), video_path)
77+
print("Must specify at least video_input_path. See usage with --help.")

0 commit comments

Comments
 (0)