We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
object detection eval&infer报错
对object detection训练出的模型进行eval&infer报错信息如下：
![3](https://user-images.githubusercontent.com/37854899/57436444-43275480-7272-11e9-9536-c99ab5ec00ba.PNG)
mobilenet_ssd.py文件中并没有eval和infer中需要的mobile_net函数，可能需将eval.py&infer.py中的mobile_net修改为build_mobilenet_ssd

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `PaddleCV/object_detection/eval.py`
Content:
```
1 import os
2 import time
3 import numpy as np
4 import argparse
5 import functools
6 import math
7 
8 import paddle
9 import paddle.fluid as fluid
10 import reader
11 from mobilenet_ssd import mobile_net
12 from utility import add_arguments, print_arguments
13 
14 parser = argparse.ArgumentParser(description=__doc__)
15 add_arg = functools.partial(add_arguments, argparser=parser)
16 # yapf: disable
17 add_arg('dataset',          str,   'pascalvoc',  "coco2014, coco2017, and pascalvoc.")
18 add_arg('batch_size',       int,   32,        "Minibatch size.")
19 add_arg('use_gpu',          bool,  True,      "Whether use GPU.")
20 add_arg('data_dir',         str,   '',        "The data root path.")
21 add_arg('test_list',        str,   '',        "The testing data lists.")
22 add_arg('model_dir',        str,   '',     "The model path.")
23 add_arg('nms_threshold',    float, 0.45,   "NMS threshold.")
24 add_arg('ap_version',       str,   '11point',   "integral, 11point.")
25 add_arg('resize_h',         int,   300,    "The resized image height.")
26 add_arg('resize_w',         int,   300,    "The resized image height.")
27 add_arg('mean_value_B',     float, 127.5,  "Mean value for B channel which will be subtracted.")  #123.68
28 add_arg('mean_value_G',     float, 127.5,  "Mean value for G channel which will be subtracted.")  #116.78
29 add_arg('mean_value_R',     float, 127.5,  "Mean value for R channel which will be subtracted.")  #103.94
30 # yapf: enable
31 
32 
33 def build_program(main_prog, startup_prog, args, data_args):
34     image_shape = [3, data_args.resize_h, data_args.resize_w]
35     if 'coco' in data_args.dataset:
36         num_classes = 91
37     elif 'pascalvoc' in data_args.dataset:
38         num_classes = 21
39 
40     with fluid.program_guard(main_prog, startup_prog):
41         py_reader = fluid.layers.py_reader(
42             capacity=64,
43             shapes=[[-1] + image_shape, [-1, 4], [-1, 1], [-1, 1]],
44             lod_levels=[0, 1, 1, 1],
45             dtypes=["float32", "float32", "int32", "int32"],
46             use_double_buffer=True)
47         with fluid.unique_name.guard():
48             image, gt_box, gt_label, difficult = fluid.layers.read_file(
49                 py_reader)
50             locs, confs, box, box_var = mobile_net(num_classes, image,
51                                                    image_shape)
52             nmsed_out = fluid.layers.detection_output(
53                 locs, confs, box, box_var, nms_threshold=args.nms_threshold)
54             with fluid.program_guard(main_prog):
55                 map = fluid.metrics.DetectionMAP(
56                     nmsed_out,
57                     gt_label,
58                     gt_box,
59                     difficult,
60                     num_classes,
61                     overlap_threshold=0.5,
62                     evaluate_difficult=False,
63                     ap_version=args.ap_version)
64     return py_reader, map
65 
66 
67 def eval(args, data_args, test_list, batch_size, model_dir=None):
68     startup_prog = fluid.Program()
69     test_prog = fluid.Program()
70 
71     test_py_reader, map_eval = build_program(
72         main_prog=test_prog,
73         startup_prog=startup_prog,
74         args=args,
75         data_args=data_args)
76     test_prog = test_prog.clone(for_test=True)
77     place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()
78     exe = fluid.Executor(place)
79     exe.run(startup_prog)
80 
81     def if_exist(var):
82         return os.path.exists(os.path.join(model_dir, var.name))
83 
84     fluid.io.load_vars(
85         exe, model_dir, main_program=test_prog, predicate=if_exist)
86 
87     test_reader = reader.test(data_args, test_list, batch_size=batch_size)
88     test_py_reader.decorate_paddle_reader(test_reader)
89 
90     _, accum_map = map_eval.get_map_var()
91     map_eval.reset(exe)
92     test_py_reader.start()
93     try:
94         batch_id = 0
95         while True:
96             test_map, = exe.run(test_prog, fetch_list=[accum_map])
97             if batch_id % 10 == 0:
98                 print("Batch {0}, map {1}".format(batch_id, test_map))
99             batch_id += 1
100     except (fluid.core.EOFException, StopIteration):
101         test_py_reader.reset()
102     print("Test model {0}, map {1}".format(model_dir, test_map))
103 
104 
105 if __name__ == '__main__':
106     args = parser.parse_args()
107     print_arguments(args)
108 
109     data_dir = 'data/pascalvoc'
110     test_list = 'test.txt'
111     label_file = 'label_list'
112 
113     if not os.path.exists(args.model_dir):
114         raise ValueError("The model path [%s] does not exist." %
115                          (args.model_dir))
116     if 'coco' in args.dataset:
117         data_dir = 'data/coco'
118         if '2014' in args.dataset:
119             test_list = 'annotations/instances_val2014.json'
120         elif '2017' in args.dataset:
121             test_list = 'annotations/instances_val2017.json'
122 
123     data_args = reader.Settings(
124         dataset=args.dataset,
125         data_dir=args.data_dir if len(args.data_dir) > 0 else data_dir,
126         label_file=label_file,
127         resize_h=args.resize_h,
128         resize_w=args.resize_w,
129         mean_value=[args.mean_value_B, args.mean_value_G, args.mean_value_R],
130         apply_distort=False,
131         apply_expand=False,
132         ap_version=args.ap_version)
133     eval(
134         args,
135         data_args=data_args,
136         test_list=args.test_list if len(args.test_list) > 0 else test_list,
137         batch_size=args.batch_size,
138         model_dir=args.model_dir)
139
```

Path: `PaddleCV/object_detection/infer.py`
Content:
```
1 import os
2 import time
3 import numpy as np
4 import argparse
5 import functools
6 from PIL import Image
7 from PIL import ImageDraw
8 from PIL import ImageFont
9 
10 import paddle
11 import paddle.fluid as fluid
12 import reader
13 from mobilenet_ssd import mobile_net
14 from utility import add_arguments, print_arguments
15 
16 parser = argparse.ArgumentParser(description=__doc__)
17 add_arg = functools.partial(add_arguments, argparser=parser)
18 # yapf: disable
19 add_arg('dataset',          str,   'pascalvoc',    "coco and pascalvoc.")
20 add_arg('use_gpu',          bool,  True,      "Whether use GPU.")
21 add_arg('image_path',       str,   '',        "The image used to inference and visualize.")
22 add_arg('model_dir',        str,   '',     "The model path.")
23 add_arg('nms_threshold',    float, 0.45,   "NMS threshold.")
24 add_arg('confs_threshold',  float, 0.5,    "Confidence threshold to draw bbox.")
25 add_arg('resize_h',         int,   300,    "The resized image height.")
26 add_arg('resize_w',         int,   300,    "The resized image height.")
27 add_arg('mean_value_B',     float, 127.5,  "Mean value for B channel which will be subtracted.")  #123.68
28 add_arg('mean_value_G',     float, 127.5,  "Mean value for G channel which will be subtracted.")  #116.78
29 add_arg('mean_value_R',     float, 127.5,  "Mean value for R channel which will be subtracted.")  #103.94
30 # yapf: enable
31 
32 
33 def infer(args, data_args, image_path, model_dir):
34     image_shape = [3, data_args.resize_h, data_args.resize_w]
35     if 'coco' in data_args.dataset:
36         num_classes = 91
37         # cocoapi
38         from pycocotools.coco import COCO
39         from pycocotools.cocoeval import COCOeval
40         label_fpath = os.path.join(data_dir, label_file)
41         coco = COCO(label_fpath)
42         category_ids = coco.getCatIds()
43         label_list = {
44             item['id']: item['name']
45             for item in coco.loadCats(category_ids)
46         }
47         label_list[0] = ['background']
48     elif 'pascalvoc' in data_args.dataset:
49         num_classes = 21
50         label_list = data_args.label_list
51 
52     image = fluid.layers.data(name='image', shape=image_shape, dtype='float32')
53     locs, confs, box, box_var = mobile_net(num_classes, image, image_shape)
54     nmsed_out = fluid.layers.detection_output(
55         locs, confs, box, box_var, nms_threshold=args.nms_threshold)
56 
57     place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()
58     exe = fluid.Executor(place)
59     # yapf: disable
60     if model_dir:
61         def if_exist(var):
62             return os.path.exists(os.path.join(model_dir, var.name))
63         fluid.io.load_vars(exe, model_dir, predicate=if_exist)
64     # yapf: enable
65     infer_reader = reader.infer(data_args, image_path)
66     feeder = fluid.DataFeeder(place=place, feed_list=[image])
67 
68     data = infer_reader()
69 
70     # switch network to test mode (i.e. batch norm test mode)
71     test_program = fluid.default_main_program().clone(for_test=True)
72     nmsed_out_v, = exe.run(test_program,
73                            feed=feeder.feed([[data]]),
74                            fetch_list=[nmsed_out],
75                            return_numpy=False)
76     nmsed_out_v = np.array(nmsed_out_v)
77     draw_bounding_box_on_image(image_path, nmsed_out_v, args.confs_threshold,
78                                label_list)
79 
80 
81 def draw_bounding_box_on_image(image_path, nms_out, confs_threshold,
82                                label_list):
83     image = Image.open(image_path)
84     draw = ImageDraw.Draw(image)
85     im_width, im_height = image.size
86 
87     for dt in nms_out:
88         if dt[1] < confs_threshold:
89             continue
90         category_id = dt[0]
91         bbox = dt[2:]
92         xmin, ymin, xmax, ymax = clip_bbox(dt[2:])
93         (left, right, top, bottom) = (xmin * im_width, xmax * im_width,
94                                       ymin * im_height, ymax * im_height)
95         draw.line(
96             [(left, top), (left, bottom), (right, bottom), (right, top),
97              (left, top)],
98             width=4,
99             fill='red')
100         if image.mode == 'RGB':
101             draw.text((left, top), label_list[int(category_id)], (255, 255, 0))
102     image_name = image_path.split('/')[-1]
103     print("image with bbox drawed saved as {}".format(image_name))
104     image.save(image_name)
105 
106 
107 def clip_bbox(bbox):
108     xmin = max(min(bbox[0], 1.), 0.)
109     ymin = max(min(bbox[1], 1.), 0.)
110     xmax = max(min(bbox[2], 1.), 0.)
111     ymax = max(min(bbox[3], 1.), 0.)
112     return xmin, ymin, xmax, ymax
113 
114 
115 if __name__ == '__main__':
116     args = parser.parse_args()
117     print_arguments(args)
118 
119     data_dir = 'data/pascalvoc'
120     label_file = 'label_list'
121 
122     if not os.path.exists(args.model_dir):
123         raise ValueError("The model path [%s] does not exist." %
124                          (args.model_dir))
125     if 'coco' in args.dataset:
126         data_dir = 'data/coco'
127         label_file = 'annotations/instances_val2014.json'
128 
129     data_args = reader.Settings(
130         dataset=args.dataset,
131         data_dir=data_dir,
132         label_file=label_file,
133         resize_h=args.resize_h,
134         resize_w=args.resize_w,
135         mean_value=[args.mean_value_B, args.mean_value_G, args.mean_value_R],
136         apply_distort=False,
137         apply_expand=False,
138         ap_version='')
139     infer(
140         args,
141         data_args=data_args,
142         image_path=args.image_path,
143         model_dir=args.model_dir)
144
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/PaddleCV/object_detection/eval.py b/PaddleCV/object_detection/eval.py
--- a/PaddleCV/object_detection/eval.py
+++ b/PaddleCV/object_detection/eval.py
@@ -8,7 +8,7 @@
 import paddle
 import paddle.fluid as fluid
 import reader
-from mobilenet_ssd import mobile_net
+from mobilenet_ssd import build_mobilenet_ssd
 from utility import add_arguments, print_arguments
 
 parser = argparse.ArgumentParser(description=__doc__)
@@ -47,8 +47,8 @@
         with fluid.unique_name.guard():
             image, gt_box, gt_label, difficult = fluid.layers.read_file(
                 py_reader)
-            locs, confs, box, box_var = mobile_net(num_classes, image,
-                                                   image_shape)
+            locs, confs, box, box_var = build_mobilenet_ssd(image, num_classes,
+                                                            image_shape)
             nmsed_out = fluid.layers.detection_output(
                 locs, confs, box, box_var, nms_threshold=args.nms_threshold)
             with fluid.program_guard(main_prog):
@@ -67,7 +67,6 @@
 def eval(args, data_args, test_list, batch_size, model_dir=None):
     startup_prog = fluid.Program()
     test_prog = fluid.Program()
-
     test_py_reader, map_eval = build_program(
         main_prog=test_prog,
         startup_prog=startup_prog,
diff --git a/PaddleCV/object_detection/infer.py b/PaddleCV/object_detection/infer.py
--- a/PaddleCV/object_detection/infer.py
+++ b/PaddleCV/object_detection/infer.py
@@ -10,7 +10,7 @@
 import paddle
 import paddle.fluid as fluid
 import reader
-from mobilenet_ssd import mobile_net
+from mobilenet_ssd import build_mobilenet_ssd
 from utility import add_arguments, print_arguments
 
 parser = argparse.ArgumentParser(description=__doc__)
@@ -50,7 +50,8 @@
         label_list = data_args.label_list
 
     image = fluid.layers.data(name='image', shape=image_shape, dtype='float32')
-    locs, confs, box, box_var = mobile_net(num_classes, image, image_shape)
+    locs, confs, box, box_var = build_mobilenet_ssd(image, num_classes,
+                                                    image_shape)
     nmsed_out = fluid.layers.detection_output(
         locs, confs, box, box_var, nms_threshold=args.nms_threshold)

{"golden_diff": "diff --git a/PaddleCV/object_detection/eval.py b/PaddleCV/object_detection/eval.py\n--- a/PaddleCV/object_detection/eval.py\n+++ b/PaddleCV/object_detection/eval.py\n@@ -8,7 +8,7 @@\n import paddle\n import paddle.fluid as fluid\n import reader\n-from mobilenet_ssd import mobile_net\n+from mobilenet_ssd import build_mobilenet_ssd\n from utility import add_arguments, print_arguments\n \n parser = argparse.ArgumentParser(description=__doc__)\n@@ -47,8 +47,8 @@\n         with fluid.unique_name.guard():\n             image, gt_box, gt_label, difficult = fluid.layers.read_file(\n                 py_reader)\n-            locs, confs, box, box_var = mobile_net(num_classes, image,\n-                                                   image_shape)\n+            locs, confs, box, box_var = build_mobilenet_ssd(image, num_classes,\n+                                                            image_shape)\n             nmsed_out = fluid.layers.detection_output(\n                 locs, confs, box, box_var, nms_threshold=args.nms_threshold)\n             with fluid.program_guard(main_prog):\n@@ -67,7 +67,6 @@\n def eval(args, data_args, test_list, batch_size, model_dir=None):\n     startup_prog = fluid.Program()\n     test_prog = fluid.Program()\n-\n     test_py_reader, map_eval = build_program(\n         main_prog=test_prog,\n         startup_prog=startup_prog,\ndiff --git a/PaddleCV/object_detection/infer.py b/PaddleCV/object_detection/infer.py\n--- a/PaddleCV/object_detection/infer.py\n+++ b/PaddleCV/object_detection/infer.py\n@@ -10,7 +10,7 @@\n import paddle\n import paddle.fluid as fluid\n import reader\n-from mobilenet_ssd import mobile_net\n+from mobilenet_ssd import build_mobilenet_ssd\n from utility import add_arguments, print_arguments\n \n parser = argparse.ArgumentParser(description=__doc__)\n@@ -50,7 +50,8 @@\n         label_list = data_args.label_list\n \n     image = fluid.layers.data(name='image', shape=image_shape, dtype='float32')\n-    locs, confs, box, box_var = mobile_net(num_classes, image, image_shape)\n+    locs, confs, box, box_var = build_mobilenet_ssd(image, num_classes,\n+                                                    image_shape)\n     nmsed_out = fluid.layers.detection_output(\n         locs, confs, box, box_var, nms_threshold=args.nms_threshold)\n", "issue": "object detection eval&infer\u62a5\u9519\n\u5bf9object detection\u8bad\u7ec3\u51fa\u7684\u6a21\u578b\u8fdb\u884ceval&infer\u62a5\u9519\u4fe1\u606f\u5982\u4e0b\uff1a\r\n![3](https://user-images.githubusercontent.com/37854899/57436444-43275480-7272-11e9-9536-c99ab5ec00ba.PNG)\r\nmobilenet_ssd.py\u6587\u4ef6\u4e2d\u5e76\u6ca1\u6709eval\u548cinfer\u4e2d\u9700\u8981\u7684mobile_net\u51fd\u6570\uff0c\u53ef\u80fd\u9700\u5c06eval.py&infer.py\u4e2d\u7684mobile_net\u4fee\u6539\u4e3abuild_mobilenet_ssd\n", "before_files": [{"content": "import os\nimport time\nimport numpy as np\nimport argparse\nimport functools\nimport math\n\nimport paddle\nimport paddle.fluid as fluid\nimport reader\nfrom mobilenet_ssd import mobile_net\nfrom utility import add_arguments, print_arguments\n\nparser = argparse.ArgumentParser(description=__doc__)\nadd_arg = functools.partial(add_arguments, argparser=parser)\n# yapf: disable\nadd_arg('dataset',          str,   'pascalvoc',  \"coco2014, coco2017, and pascalvoc.\")\nadd_arg('batch_size',       int,   32,        \"Minibatch size.\")\nadd_arg('use_gpu',          bool,  True,      \"Whether use GPU.\")\nadd_arg('data_dir',         str,   '',        \"The data root path.\")\nadd_arg('test_list',        str,   '',        \"The testing data lists.\")\nadd_arg('model_dir',        str,   '',     \"The model path.\")\nadd_arg('nms_threshold',    float, 0.45,   \"NMS threshold.\")\nadd_arg('ap_version',       str,   '11point',   \"integral, 11point.\")\nadd_arg('resize_h',         int,   300,    \"The resized image height.\")\nadd_arg('resize_w',         int,   300,    \"The resized image height.\")\nadd_arg('mean_value_B',     float, 127.5,  \"Mean value for B channel which will be subtracted.\")  #123.68\nadd_arg('mean_value_G',     float, 127.5,  \"Mean value for G channel which will be subtracted.\")  #116.78\nadd_arg('mean_value_R',     float, 127.5,  \"Mean value for R channel which will be subtracted.\")  #103.94\n# yapf: enable\n\n\ndef build_program(main_prog, startup_prog, args, data_args):\n    image_shape = [3, data_args.resize_h, data_args.resize_w]\n    if 'coco' in data_args.dataset:\n        num_classes = 91\n    elif 'pascalvoc' in data_args.dataset:\n        num_classes = 21\n\n    with fluid.program_guard(main_prog, startup_prog):\n        py_reader = fluid.layers.py_reader(\n            capacity=64,\n            shapes=[[-1] + image_shape, [-1, 4], [-1, 1], [-1, 1]],\n            lod_levels=[0, 1, 1, 1],\n            dtypes=[\"float32\", \"float32\", \"int32\", \"int32\"],\n            use_double_buffer=True)\n        with fluid.unique_name.guard():\n            image, gt_box, gt_label, difficult = fluid.layers.read_file(\n                py_reader)\n            locs, confs, box, box_var = mobile_net(num_classes, image,\n                                                   image_shape)\n            nmsed_out = fluid.layers.detection_output(\n                locs, confs, box, box_var, nms_threshold=args.nms_threshold)\n            with fluid.program_guard(main_prog):\n                map = fluid.metrics.DetectionMAP(\n                    nmsed_out,\n                    gt_label,\n                    gt_box,\n                    difficult,\n                    num_classes,\n                    overlap_threshold=0.5,\n                    evaluate_difficult=False,\n                    ap_version=args.ap_version)\n    return py_reader, map\n\n\ndef eval(args, data_args, test_list, batch_size, model_dir=None):\n    startup_prog = fluid.Program()\n    test_prog = fluid.Program()\n\n    test_py_reader, map_eval = build_program(\n        main_prog=test_prog,\n        startup_prog=startup_prog,\n        args=args,\n        data_args=data_args)\n    test_prog = test_prog.clone(for_test=True)\n    place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()\n    exe = fluid.Executor(place)\n    exe.run(startup_prog)\n\n    def if_exist(var):\n        return os.path.exists(os.path.join(model_dir, var.name))\n\n    fluid.io.load_vars(\n        exe, model_dir, main_program=test_prog, predicate=if_exist)\n\n    test_reader = reader.test(data_args, test_list, batch_size=batch_size)\n    test_py_reader.decorate_paddle_reader(test_reader)\n\n    _, accum_map = map_eval.get_map_var()\n    map_eval.reset(exe)\n    test_py_reader.start()\n    try:\n        batch_id = 0\n        while True:\n            test_map, = exe.run(test_prog, fetch_list=[accum_map])\n            if batch_id % 10 == 0:\n                print(\"Batch {0}, map {1}\".format(batch_id, test_map))\n            batch_id += 1\n    except (fluid.core.EOFException, StopIteration):\n        test_py_reader.reset()\n    print(\"Test model {0}, map {1}\".format(model_dir, test_map))\n\n\nif __name__ == '__main__':\n    args = parser.parse_args()\n    print_arguments(args)\n\n    data_dir = 'data/pascalvoc'\n    test_list = 'test.txt'\n    label_file = 'label_list'\n\n    if not os.path.exists(args.model_dir):\n        raise ValueError(\"The model path [%s] does not exist.\" %\n                         (args.model_dir))\n    if 'coco' in args.dataset:\n        data_dir = 'data/coco'\n        if '2014' in args.dataset:\n            test_list = 'annotations/instances_val2014.json'\n        elif '2017' in args.dataset:\n            test_list = 'annotations/instances_val2017.json'\n\n    data_args = reader.Settings(\n        dataset=args.dataset,\n        data_dir=args.data_dir if len(args.data_dir) > 0 else data_dir,\n        label_file=label_file,\n        resize_h=args.resize_h,\n        resize_w=args.resize_w,\n        mean_value=[args.mean_value_B, args.mean_value_G, args.mean_value_R],\n        apply_distort=False,\n        apply_expand=False,\n        ap_version=args.ap_version)\n    eval(\n        args,\n        data_args=data_args,\n        test_list=args.test_list if len(args.test_list) > 0 else test_list,\n        batch_size=args.batch_size,\n        model_dir=args.model_dir)\n", "path": "PaddleCV/object_detection/eval.py"}, {"content": "import os\nimport time\nimport numpy as np\nimport argparse\nimport functools\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\n\nimport paddle\nimport paddle.fluid as fluid\nimport reader\nfrom mobilenet_ssd import mobile_net\nfrom utility import add_arguments, print_arguments\n\nparser = argparse.ArgumentParser(description=__doc__)\nadd_arg = functools.partial(add_arguments, argparser=parser)\n# yapf: disable\nadd_arg('dataset',          str,   'pascalvoc',    \"coco and pascalvoc.\")\nadd_arg('use_gpu',          bool,  True,      \"Whether use GPU.\")\nadd_arg('image_path',       str,   '',        \"The image used to inference and visualize.\")\nadd_arg('model_dir',        str,   '',     \"The model path.\")\nadd_arg('nms_threshold',    float, 0.45,   \"NMS threshold.\")\nadd_arg('confs_threshold',  float, 0.5,    \"Confidence threshold to draw bbox.\")\nadd_arg('resize_h',         int,   300,    \"The resized image height.\")\nadd_arg('resize_w',         int,   300,    \"The resized image height.\")\nadd_arg('mean_value_B',     float, 127.5,  \"Mean value for B channel which will be subtracted.\")  #123.68\nadd_arg('mean_value_G',     float, 127.5,  \"Mean value for G channel which will be subtracted.\")  #116.78\nadd_arg('mean_value_R',     float, 127.5,  \"Mean value for R channel which will be subtracted.\")  #103.94\n# yapf: enable\n\n\ndef infer(args, data_args, image_path, model_dir):\n    image_shape = [3, data_args.resize_h, data_args.resize_w]\n    if 'coco' in data_args.dataset:\n        num_classes = 91\n        # cocoapi\n        from pycocotools.coco import COCO\n        from pycocotools.cocoeval import COCOeval\n        label_fpath = os.path.join(data_dir, label_file)\n        coco = COCO(label_fpath)\n        category_ids = coco.getCatIds()\n        label_list = {\n            item['id']: item['name']\n            for item in coco.loadCats(category_ids)\n        }\n        label_list[0] = ['background']\n    elif 'pascalvoc' in data_args.dataset:\n        num_classes = 21\n        label_list = data_args.label_list\n\n    image = fluid.layers.data(name='image', shape=image_shape, dtype='float32')\n    locs, confs, box, box_var = mobile_net(num_classes, image, image_shape)\n    nmsed_out = fluid.layers.detection_output(\n        locs, confs, box, box_var, nms_threshold=args.nms_threshold)\n\n    place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()\n    exe = fluid.Executor(place)\n    # yapf: disable\n    if model_dir:\n        def if_exist(var):\n            return os.path.exists(os.path.join(model_dir, var.name))\n        fluid.io.load_vars(exe, model_dir, predicate=if_exist)\n    # yapf: enable\n    infer_reader = reader.infer(data_args, image_path)\n    feeder = fluid.DataFeeder(place=place, feed_list=[image])\n\n    data = infer_reader()\n\n    # switch network to test mode (i.e. batch norm test mode)\n    test_program = fluid.default_main_program().clone(for_test=True)\n    nmsed_out_v, = exe.run(test_program,\n                           feed=feeder.feed([[data]]),\n                           fetch_list=[nmsed_out],\n                           return_numpy=False)\n    nmsed_out_v = np.array(nmsed_out_v)\n    draw_bounding_box_on_image(image_path, nmsed_out_v, args.confs_threshold,\n                               label_list)\n\n\ndef draw_bounding_box_on_image(image_path, nms_out, confs_threshold,\n                               label_list):\n    image = Image.open(image_path)\n    draw = ImageDraw.Draw(image)\n    im_width, im_height = image.size\n\n    for dt in nms_out:\n        if dt[1] < confs_threshold:\n            continue\n        category_id = dt[0]\n        bbox = dt[2:]\n        xmin, ymin, xmax, ymax = clip_bbox(dt[2:])\n        (left, right, top, bottom) = (xmin * im_width, xmax * im_width,\n                                      ymin * im_height, ymax * im_height)\n        draw.line(\n            [(left, top), (left, bottom), (right, bottom), (right, top),\n             (left, top)],\n            width=4,\n            fill='red')\n        if image.mode == 'RGB':\n            draw.text((left, top), label_list[int(category_id)], (255, 255, 0))\n    image_name = image_path.split('/')[-1]\n    print(\"image with bbox drawed saved as {}\".format(image_name))\n    image.save(image_name)\n\n\ndef clip_bbox(bbox):\n    xmin = max(min(bbox[0], 1.), 0.)\n    ymin = max(min(bbox[1], 1.), 0.)\n    xmax = max(min(bbox[2], 1.), 0.)\n    ymax = max(min(bbox[3], 1.), 0.)\n    return xmin, ymin, xmax, ymax\n\n\nif __name__ == '__main__':\n    args = parser.parse_args()\n    print_arguments(args)\n\n    data_dir = 'data/pascalvoc'\n    label_file = 'label_list'\n\n    if not os.path.exists(args.model_dir):\n        raise ValueError(\"The model path [%s] does not exist.\" %\n                         (args.model_dir))\n    if 'coco' in args.dataset:\n        data_dir = 'data/coco'\n        label_file = 'annotations/instances_val2014.json'\n\n    data_args = reader.Settings(\n        dataset=args.dataset,\n        data_dir=data_dir,\n        label_file=label_file,\n        resize_h=args.resize_h,\n        resize_w=args.resize_w,\n        mean_value=[args.mean_value_B, args.mean_value_G, args.mean_value_R],\n        apply_distort=False,\n        apply_expand=False,\n        ap_version='')\n    infer(\n        args,\n        data_args=data_args,\n        image_path=args.image_path,\n        model_dir=args.model_dir)\n", "path": "PaddleCV/object_detection/infer.py"}], "after_files": [{"content": "import os\nimport time\nimport numpy as np\nimport argparse\nimport functools\nimport math\n\nimport paddle\nimport paddle.fluid as fluid\nimport reader\nfrom mobilenet_ssd import build_mobilenet_ssd\nfrom utility import add_arguments, print_arguments\n\nparser = argparse.ArgumentParser(description=__doc__)\nadd_arg = functools.partial(add_arguments, argparser=parser)\n# yapf: disable\nadd_arg('dataset',          str,   'pascalvoc',  \"coco2014, coco2017, and pascalvoc.\")\nadd_arg('batch_size',       int,   32,        \"Minibatch size.\")\nadd_arg('use_gpu',          bool,  True,      \"Whether use GPU.\")\nadd_arg('data_dir',         str,   '',        \"The data root path.\")\nadd_arg('test_list',        str,   '',        \"The testing data lists.\")\nadd_arg('model_dir',        str,   '',     \"The model path.\")\nadd_arg('nms_threshold',    float, 0.45,   \"NMS threshold.\")\nadd_arg('ap_version',       str,   '11point',   \"integral, 11point.\")\nadd_arg('resize_h',         int,   300,    \"The resized image height.\")\nadd_arg('resize_w',         int,   300,    \"The resized image height.\")\nadd_arg('mean_value_B',     float, 127.5,  \"Mean value for B channel which will be subtracted.\")  #123.68\nadd_arg('mean_value_G',     float, 127.5,  \"Mean value for G channel which will be subtracted.\")  #116.78\nadd_arg('mean_value_R',     float, 127.5,  \"Mean value for R channel which will be subtracted.\")  #103.94\n# yapf: enable\n\n\ndef build_program(main_prog, startup_prog, args, data_args):\n    image_shape = [3, data_args.resize_h, data_args.resize_w]\n    if 'coco' in data_args.dataset:\n        num_classes = 91\n    elif 'pascalvoc' in data_args.dataset:\n        num_classes = 21\n\n    with fluid.program_guard(main_prog, startup_prog):\n        py_reader = fluid.layers.py_reader(\n            capacity=64,\n            shapes=[[-1] + image_shape, [-1, 4], [-1, 1], [-1, 1]],\n            lod_levels=[0, 1, 1, 1],\n            dtypes=[\"float32\", \"float32\", \"int32\", \"int32\"],\n            use_double_buffer=True)\n        with fluid.unique_name.guard():\n            image, gt_box, gt_label, difficult = fluid.layers.read_file(\n                py_reader)\n            locs, confs, box, box_var = build_mobilenet_ssd(image, num_classes,\n                                                            image_shape)\n            nmsed_out = fluid.layers.detection_output(\n                locs, confs, box, box_var, nms_threshold=args.nms_threshold)\n            with fluid.program_guard(main_prog):\n                map = fluid.metrics.DetectionMAP(\n                    nmsed_out,\n                    gt_label,\n                    gt_box,\n                    difficult,\n                    num_classes,\n                    overlap_threshold=0.5,\n                    evaluate_difficult=False,\n                    ap_version=args.ap_version)\n    return py_reader, map\n\n\ndef eval(args, data_args, test_list, batch_size, model_dir=None):\n    startup_prog = fluid.Program()\n    test_prog = fluid.Program()\n    test_py_reader, map_eval = build_program(\n        main_prog=test_prog,\n        startup_prog=startup_prog,\n        args=args,\n        data_args=data_args)\n    test_prog = test_prog.clone(for_test=True)\n    place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()\n    exe = fluid.Executor(place)\n    exe.run(startup_prog)\n\n    def if_exist(var):\n        return os.path.exists(os.path.join(model_dir, var.name))\n\n    fluid.io.load_vars(\n        exe, model_dir, main_program=test_prog, predicate=if_exist)\n\n    test_reader = reader.test(data_args, test_list, batch_size=batch_size)\n    test_py_reader.decorate_paddle_reader(test_reader)\n\n    _, accum_map = map_eval.get_map_var()\n    map_eval.reset(exe)\n    test_py_reader.start()\n    try:\n        batch_id = 0\n        while True:\n            test_map, = exe.run(test_prog, fetch_list=[accum_map])\n            if batch_id % 10 == 0:\n                print(\"Batch {0}, map {1}\".format(batch_id, test_map))\n            batch_id += 1\n    except (fluid.core.EOFException, StopIteration):\n        test_py_reader.reset()\n    print(\"Test model {0}, map {1}\".format(model_dir, test_map))\n\n\nif __name__ == '__main__':\n    args = parser.parse_args()\n    print_arguments(args)\n\n    data_dir = 'data/pascalvoc'\n    test_list = 'test.txt'\n    label_file = 'label_list'\n\n    if not os.path.exists(args.model_dir):\n        raise ValueError(\"The model path [%s] does not exist.\" %\n                         (args.model_dir))\n    if 'coco' in args.dataset:\n        data_dir = 'data/coco'\n        if '2014' in args.dataset:\n            test_list = 'annotations/instances_val2014.json'\n        elif '2017' in args.dataset:\n            test_list = 'annotations/instances_val2017.json'\n\n    data_args = reader.Settings(\n        dataset=args.dataset,\n        data_dir=args.data_dir if len(args.data_dir) > 0 else data_dir,\n        label_file=label_file,\n        resize_h=args.resize_h,\n        resize_w=args.resize_w,\n        mean_value=[args.mean_value_B, args.mean_value_G, args.mean_value_R],\n        apply_distort=False,\n        apply_expand=False,\n        ap_version=args.ap_version)\n    eval(\n        args,\n        data_args=data_args,\n        test_list=args.test_list if len(args.test_list) > 0 else test_list,\n        batch_size=args.batch_size,\n        model_dir=args.model_dir)\n", "path": "PaddleCV/object_detection/eval.py"}, {"content": "import os\nimport time\nimport numpy as np\nimport argparse\nimport functools\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\n\nimport paddle\nimport paddle.fluid as fluid\nimport reader\nfrom mobilenet_ssd import build_mobilenet_ssd\nfrom utility import add_arguments, print_arguments\n\nparser = argparse.ArgumentParser(description=__doc__)\nadd_arg = functools.partial(add_arguments, argparser=parser)\n# yapf: disable\nadd_arg('dataset',          str,   'pascalvoc',    \"coco and pascalvoc.\")\nadd_arg('use_gpu',          bool,  True,      \"Whether use GPU.\")\nadd_arg('image_path',       str,   '',        \"The image used to inference and visualize.\")\nadd_arg('model_dir',        str,   '',     \"The model path.\")\nadd_arg('nms_threshold',    float, 0.45,   \"NMS threshold.\")\nadd_arg('confs_threshold',  float, 0.5,    \"Confidence threshold to draw bbox.\")\nadd_arg('resize_h',         int,   300,    \"The resized image height.\")\nadd_arg('resize_w',         int,   300,    \"The resized image height.\")\nadd_arg('mean_value_B',     float, 127.5,  \"Mean value for B channel which will be subtracted.\")  #123.68\nadd_arg('mean_value_G',     float, 127.5,  \"Mean value for G channel which will be subtracted.\")  #116.78\nadd_arg('mean_value_R',     float, 127.5,  \"Mean value for R channel which will be subtracted.\")  #103.94\n# yapf: enable\n\n\ndef infer(args, data_args, image_path, model_dir):\n    image_shape = [3, data_args.resize_h, data_args.resize_w]\n    if 'coco' in data_args.dataset:\n        num_classes = 91\n        # cocoapi\n        from pycocotools.coco import COCO\n        from pycocotools.cocoeval import COCOeval\n        label_fpath = os.path.join(data_dir, label_file)\n        coco = COCO(label_fpath)\n        category_ids = coco.getCatIds()\n        label_list = {\n            item['id']: item['name']\n            for item in coco.loadCats(category_ids)\n        }\n        label_list[0] = ['background']\n    elif 'pascalvoc' in data_args.dataset:\n        num_classes = 21\n        label_list = data_args.label_list\n\n    image = fluid.layers.data(name='image', shape=image_shape, dtype='float32')\n    locs, confs, box, box_var = build_mobilenet_ssd(image, num_classes,\n                                                    image_shape)\n    nmsed_out = fluid.layers.detection_output(\n        locs, confs, box, box_var, nms_threshold=args.nms_threshold)\n\n    place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()\n    exe = fluid.Executor(place)\n    # yapf: disable\n    if model_dir:\n        def if_exist(var):\n            return os.path.exists(os.path.join(model_dir, var.name))\n        fluid.io.load_vars(exe, model_dir, predicate=if_exist)\n    # yapf: enable\n    infer_reader = reader.infer(data_args, image_path)\n    feeder = fluid.DataFeeder(place=place, feed_list=[image])\n\n    data = infer_reader()\n\n    # switch network to test mode (i.e. batch norm test mode)\n    test_program = fluid.default_main_program().clone(for_test=True)\n    nmsed_out_v, = exe.run(test_program,\n                           feed=feeder.feed([[data]]),\n                           fetch_list=[nmsed_out],\n                           return_numpy=False)\n    nmsed_out_v = np.array(nmsed_out_v)\n    draw_bounding_box_on_image(image_path, nmsed_out_v, args.confs_threshold,\n                               label_list)\n\n\ndef draw_bounding_box_on_image(image_path, nms_out, confs_threshold,\n                               label_list):\n    image = Image.open(image_path)\n    draw = ImageDraw.Draw(image)\n    im_width, im_height = image.size\n\n    for dt in nms_out:\n        if dt[1] < confs_threshold:\n            continue\n        category_id = dt[0]\n        bbox = dt[2:]\n        xmin, ymin, xmax, ymax = clip_bbox(dt[2:])\n        (left, right, top, bottom) = (xmin * im_width, xmax * im_width,\n                                      ymin * im_height, ymax * im_height)\n        draw.line(\n            [(left, top), (left, bottom), (right, bottom), (right, top),\n             (left, top)],\n            width=4,\n            fill='red')\n        if image.mode == 'RGB':\n            draw.text((left, top), label_list[int(category_id)], (255, 255, 0))\n    image_name = image_path.split('/')[-1]\n    print(\"image with bbox drawed saved as {}\".format(image_name))\n    image.save(image_name)\n\n\ndef clip_bbox(bbox):\n    xmin = max(min(bbox[0], 1.), 0.)\n    ymin = max(min(bbox[1], 1.), 0.)\n    xmax = max(min(bbox[2], 1.), 0.)\n    ymax = max(min(bbox[3], 1.), 0.)\n    return xmin, ymin, xmax, ymax\n\n\nif __name__ == '__main__':\n    args = parser.parse_args()\n    print_arguments(args)\n\n    data_dir = 'data/pascalvoc'\n    label_file = 'label_list'\n\n    if not os.path.exists(args.model_dir):\n        raise ValueError(\"The model path [%s] does not exist.\" %\n                         (args.model_dir))\n    if 'coco' in args.dataset:\n        data_dir = 'data/coco'\n        label_file = 'annotations/instances_val2014.json'\n\n    data_args = reader.Settings(\n        dataset=args.dataset,\n        data_dir=data_dir,\n        label_file=label_file,\n        resize_h=args.resize_h,\n        resize_w=args.resize_w,\n        mean_value=[args.mean_value_B, args.mean_value_G, args.mean_value_R],\n        apply_distort=False,\n        apply_expand=False,\n        ap_version='')\n    infer(\n        args,\n        data_args=data_args,\n        image_path=args.image_path,\n        model_dir=args.model_dir)\n", "path": "PaddleCV/object_detection/infer.py"}]}