We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
There is a small error in face_detection reader
https://github.com/PaddlePaddle/models/blob/55138a40a219975bcbbeb6c1edef5284de721f72/PaddleCV/face_detection/reader.py#L312

the code should be 
```
 img = img.convert('RGB')
```


--- 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/face_detection/reader.py`
Content:
```
1 # Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 from __future__ import absolute_import
16 from __future__ import division
17 from __future__ import print_function
18 
19 from PIL import Image
20 from PIL import ImageDraw
21 import numpy as np
22 import xml.etree.ElementTree
23 import os
24 import time
25 import copy
26 import random
27 import cv2
28 import six
29 import math
30 from itertools import islice
31 import paddle
32 import image_util
33 
34 
35 class Settings(object):
36     def __init__(self,
37                  dataset=None,
38                  data_dir=None,
39                  label_file=None,
40                  resize_h=None,
41                  resize_w=None,
42                  mean_value=[104., 117., 123.],
43                  apply_distort=True,
44                  apply_expand=True,
45                  ap_version='11point',
46                  toy=0):
47         self.dataset = dataset
48         self.ap_version = ap_version
49         self.toy = toy
50         self.data_dir = data_dir
51         self.apply_distort = apply_distort
52         self.apply_expand = apply_expand
53         self.resize_height = resize_h
54         self.resize_width = resize_w
55         self.img_mean = np.array(mean_value)[:, np.newaxis, np.newaxis].astype(
56             'float32')
57         self.expand_prob = 0.5
58         self.expand_max_ratio = 4
59         self.hue_prob = 0.5
60         self.hue_delta = 18
61         self.contrast_prob = 0.5
62         self.contrast_delta = 0.5
63         self.saturation_prob = 0.5
64         self.saturation_delta = 0.5
65         self.brightness_prob = 0.5
66         # _brightness_delta is the normalized value by 256
67         self.brightness_delta = 0.125
68         self.scale = 0.007843  # 1 / 127.5
69         self.data_anchor_sampling_prob = 0.5
70         self.min_face_size = 8.0
71 
72 
73 def to_chw_bgr(image):
74     """
75     Transpose image from HWC to CHW and from RBG to BGR.
76     Args:
77         image (np.array): an image with HWC and RBG layout.
78     """
79     # HWC to CHW
80     if len(image.shape) == 3:
81         image = np.swapaxes(image, 1, 2)
82         image = np.swapaxes(image, 1, 0)
83     # RBG to BGR
84     image = image[[2, 1, 0], :, :]
85     return image
86 
87 
88 def preprocess(img, bbox_labels, mode, settings, image_path):
89     img_width, img_height = img.size
90     sampled_labels = bbox_labels
91     if mode == 'train':
92         if settings.apply_distort:
93             img = image_util.distort_image(img, settings)
94         if settings.apply_expand:
95             img, bbox_labels, img_width, img_height = image_util.expand_image(
96                 img, bbox_labels, img_width, img_height, settings)
97 
98         # sampling
99         batch_sampler = []
100 
101         prob = np.random.uniform(0., 1.)
102         if prob > settings.data_anchor_sampling_prob:
103             scale_array = np.array([16, 32, 64, 128, 256, 512])
104             batch_sampler.append(
105                 image_util.sampler(1, 10, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.2,
106                                    0.0, True))
107             sampled_bbox = image_util.generate_batch_random_samples(
108                 batch_sampler, bbox_labels, img_width, img_height, scale_array,
109                 settings.resize_width, settings.resize_height)
110             img = np.array(img)
111             if len(sampled_bbox) > 0:
112                 idx = int(np.random.uniform(0, len(sampled_bbox)))
113                 img, sampled_labels = image_util.crop_image_sampling(
114                     img, bbox_labels, sampled_bbox[idx], img_width, img_height,
115                     settings.resize_width, settings.resize_height,
116                     settings.min_face_size)
117 
118             img = img.astype('uint8')
119             img = Image.fromarray(img)
120 
121         else:
122             # hard-code here
123             batch_sampler.append(
124                 image_util.sampler(1, 50, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,
125                                    0.0, True))
126             batch_sampler.append(
127                 image_util.sampler(1, 50, 0.3, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,
128                                    0.0, True))
129             batch_sampler.append(
130                 image_util.sampler(1, 50, 0.3, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,
131                                    0.0, True))
132             batch_sampler.append(
133                 image_util.sampler(1, 50, 0.3, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,
134                                    0.0, True))
135             batch_sampler.append(
136                 image_util.sampler(1, 50, 0.3, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,
137                                    0.0, True))
138             sampled_bbox = image_util.generate_batch_samples(
139                 batch_sampler, bbox_labels, img_width, img_height)
140 
141             img = np.array(img)
142             if len(sampled_bbox) > 0:
143                 idx = int(np.random.uniform(0, len(sampled_bbox)))
144                 img, sampled_labels = image_util.crop_image(
145                     img, bbox_labels, sampled_bbox[idx], img_width, img_height,
146                     settings.resize_width, settings.resize_height,
147                     settings.min_face_size)
148 
149             img = Image.fromarray(img)
150     interp_mode = [
151         Image.BILINEAR, Image.HAMMING, Image.NEAREST, Image.BICUBIC,
152         Image.LANCZOS
153     ]
154     interp_indx = np.random.randint(0, 5)
155 
156     img = img.resize(
157         (settings.resize_width, settings.resize_height),
158         resample=interp_mode[interp_indx])
159     img = np.array(img)
160 
161     if mode == 'train':
162         mirror = int(np.random.uniform(0, 2))
163         if mirror == 1:
164             img = img[:, ::-1, :]
165             for i in six.moves.xrange(len(sampled_labels)):
166                 tmp = sampled_labels[i][1]
167                 sampled_labels[i][1] = 1 - sampled_labels[i][3]
168                 sampled_labels[i][3] = 1 - tmp
169 
170     img = to_chw_bgr(img)
171     img = img.astype('float32')
172     img -= settings.img_mean
173     img = img * settings.scale
174     return img, sampled_labels
175 
176 
177 def load_file_list(input_txt):
178     with open(input_txt, 'r') as f_dir:
179         lines_input_txt = f_dir.readlines()
180 
181     file_dict = {}
182     num_class = 0
183     for i in range(len(lines_input_txt)):
184         line_txt = lines_input_txt[i].strip('\n\t\r')
185         if '--' in line_txt:
186             if i != 0:
187                 num_class += 1
188             file_dict[num_class] = []
189             file_dict[num_class].append(line_txt)
190         if '--' not in line_txt:
191             if len(line_txt) > 6:
192                 split_str = line_txt.split(' ')
193                 x1_min = float(split_str[0])
194                 y1_min = float(split_str[1])
195                 x2_max = float(split_str[2])
196                 y2_max = float(split_str[3])
197                 line_txt = str(x1_min) + ' ' + str(y1_min) + ' ' + str(
198                     x2_max) + ' ' + str(y2_max)
199                 file_dict[num_class].append(line_txt)
200             else:
201                 file_dict[num_class].append(line_txt)
202 
203     return list(file_dict.values())
204 
205 
206 def expand_bboxes(bboxes,
207                   expand_left=2.,
208                   expand_up=2.,
209                   expand_right=2.,
210                   expand_down=2.):
211     """
212     Expand bboxes, expand 2 times by defalut.
213     """
214     expand_boxes = []
215     for bbox in bboxes:
216         xmin = bbox[0]
217         ymin = bbox[1]
218         xmax = bbox[2]
219         ymax = bbox[3]
220         w = xmax - xmin
221         h = ymax - ymin
222         ex_xmin = max(xmin - w / expand_left, 0.)
223         ex_ymin = max(ymin - h / expand_up, 0.)
224         ex_xmax = min(xmax + w / expand_right, 1.)
225         ex_ymax = min(ymax + h / expand_down, 1.)
226         expand_boxes.append([ex_xmin, ex_ymin, ex_xmax, ex_ymax])
227     return expand_boxes
228 
229 
230 def train_generator(settings, file_list, batch_size, shuffle=True):
231     def reader():
232         if shuffle:
233             np.random.shuffle(file_list)
234         batch_out = []
235         for item in file_list:
236             image_name = item[0]
237             image_path = os.path.join(settings.data_dir, image_name)
238             im = Image.open(image_path)
239             if im.mode == 'L':
240                 im = im.convert('RGB')
241             im_width, im_height = im.size
242 
243             # layout: label | xmin | ymin | xmax | ymax
244             bbox_labels = []
245             for index_box in range(len(item)):
246                 if index_box >= 2:
247                     bbox_sample = []
248                     temp_info_box = item[index_box].split(' ')
249                     xmin = float(temp_info_box[0])
250                     ymin = float(temp_info_box[1])
251                     w = float(temp_info_box[2])
252                     h = float(temp_info_box[3])
253 
254                     # Filter out wrong labels
255                     if w < 0 or h < 0:
256                         continue
257                     xmax = xmin + w
258                     ymax = ymin + h
259 
260                     bbox_sample.append(1)
261                     bbox_sample.append(float(xmin) / im_width)
262                     bbox_sample.append(float(ymin) / im_height)
263                     bbox_sample.append(float(xmax) / im_width)
264                     bbox_sample.append(float(ymax) / im_height)
265                     bbox_labels.append(bbox_sample)
266             im, sample_labels = preprocess(im, bbox_labels, "train", settings,
267                                            image_path)
268             sample_labels = np.array(sample_labels)
269             if len(sample_labels) == 0: continue
270 
271             im = im.astype('float32')
272             face_box = sample_labels[:, 1:5]
273             head_box = expand_bboxes(face_box)
274             label = [1] * len(face_box)
275             batch_out.append((im, face_box, head_box, label))
276             if len(batch_out) == batch_size:
277                 yield batch_out
278                 batch_out = []
279 
280     return reader
281 
282 
283 def train(settings, file_list, batch_size, shuffle=True, num_workers=8):
284     file_lists = load_file_list(file_list)
285     n = int(math.ceil(len(file_lists) // num_workers))
286     split_lists = [file_lists[i:i + n] for i in range(0, len(file_lists), n)]
287     readers = []
288     for iterm in split_lists:
289         readers.append(train_generator(settings, iterm, batch_size, shuffle))
290     return paddle.reader.multiprocess_reader(readers, False)
291 
292 
293 def test(settings, file_list):
294     file_lists = load_file_list(file_list)
295 
296     def reader():
297         for image in file_lists:
298             image_name = image[0]
299             image_path = os.path.join(settings.data_dir, image_name)
300             im = Image.open(image_path)
301             if im.mode == 'L':
302                 im = im.convert('RGB')
303             yield im, image_path
304 
305     return reader
306 
307 
308 def infer(settings, image_path):
309     def batch_reader():
310         img = Image.open(image_path)
311         if img.mode == 'L':
312             img = im.convert('RGB')
313         im_width, im_height = img.size
314         if settings.resize_width and settings.resize_height:
315             img = img.resize((settings.resize_width, settings.resize_height),
316                              Image.ANTIALIAS)
317         img = np.array(img)
318         img = to_chw_bgr(img)
319         img = img.astype('float32')
320         img -= settings.img_mean
321         img = img * settings.scale
322         return np.array([img])
323 
324     return batch_reader
325
```
--- 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/face_detection/reader.py b/PaddleCV/face_detection/reader.py
--- a/PaddleCV/face_detection/reader.py
+++ b/PaddleCV/face_detection/reader.py
@@ -309,7 +309,7 @@
     def batch_reader():
         img = Image.open(image_path)
         if img.mode == 'L':
-            img = im.convert('RGB')
+            img = img.convert('RGB')
         im_width, im_height = img.size
         if settings.resize_width and settings.resize_height:
             img = img.resize((settings.resize_width, settings.resize_height),

{"golden_diff": "diff --git a/PaddleCV/face_detection/reader.py b/PaddleCV/face_detection/reader.py\n--- a/PaddleCV/face_detection/reader.py\n+++ b/PaddleCV/face_detection/reader.py\n@@ -309,7 +309,7 @@\n     def batch_reader():\n         img = Image.open(image_path)\n         if img.mode == 'L':\n-            img = im.convert('RGB')\n+            img = img.convert('RGB')\n         im_width, im_height = img.size\n         if settings.resize_width and settings.resize_height:\n             img = img.resize((settings.resize_width, settings.resize_height),\n", "issue": "There is a small error in face_detection reader\nhttps://github.com/PaddlePaddle/models/blob/55138a40a219975bcbbeb6c1edef5284de721f72/PaddleCV/face_detection/reader.py#L312\r\n\r\nthe code should be \r\n```\r\n img = img.convert('RGB')\r\n```\r\n\n", "before_files": [{"content": "# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom PIL import Image\nfrom PIL import ImageDraw\nimport numpy as np\nimport xml.etree.ElementTree\nimport os\nimport time\nimport copy\nimport random\nimport cv2\nimport six\nimport math\nfrom itertools import islice\nimport paddle\nimport image_util\n\n\nclass Settings(object):\n    def __init__(self,\n                 dataset=None,\n                 data_dir=None,\n                 label_file=None,\n                 resize_h=None,\n                 resize_w=None,\n                 mean_value=[104., 117., 123.],\n                 apply_distort=True,\n                 apply_expand=True,\n                 ap_version='11point',\n                 toy=0):\n        self.dataset = dataset\n        self.ap_version = ap_version\n        self.toy = toy\n        self.data_dir = data_dir\n        self.apply_distort = apply_distort\n        self.apply_expand = apply_expand\n        self.resize_height = resize_h\n        self.resize_width = resize_w\n        self.img_mean = np.array(mean_value)[:, np.newaxis, np.newaxis].astype(\n            'float32')\n        self.expand_prob = 0.5\n        self.expand_max_ratio = 4\n        self.hue_prob = 0.5\n        self.hue_delta = 18\n        self.contrast_prob = 0.5\n        self.contrast_delta = 0.5\n        self.saturation_prob = 0.5\n        self.saturation_delta = 0.5\n        self.brightness_prob = 0.5\n        # _brightness_delta is the normalized value by 256\n        self.brightness_delta = 0.125\n        self.scale = 0.007843  # 1 / 127.5\n        self.data_anchor_sampling_prob = 0.5\n        self.min_face_size = 8.0\n\n\ndef to_chw_bgr(image):\n    \"\"\"\n    Transpose image from HWC to CHW and from RBG to BGR.\n    Args:\n        image (np.array): an image with HWC and RBG layout.\n    \"\"\"\n    # HWC to CHW\n    if len(image.shape) == 3:\n        image = np.swapaxes(image, 1, 2)\n        image = np.swapaxes(image, 1, 0)\n    # RBG to BGR\n    image = image[[2, 1, 0], :, :]\n    return image\n\n\ndef preprocess(img, bbox_labels, mode, settings, image_path):\n    img_width, img_height = img.size\n    sampled_labels = bbox_labels\n    if mode == 'train':\n        if settings.apply_distort:\n            img = image_util.distort_image(img, settings)\n        if settings.apply_expand:\n            img, bbox_labels, img_width, img_height = image_util.expand_image(\n                img, bbox_labels, img_width, img_height, settings)\n\n        # sampling\n        batch_sampler = []\n\n        prob = np.random.uniform(0., 1.)\n        if prob > settings.data_anchor_sampling_prob:\n            scale_array = np.array([16, 32, 64, 128, 256, 512])\n            batch_sampler.append(\n                image_util.sampler(1, 10, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.2,\n                                   0.0, True))\n            sampled_bbox = image_util.generate_batch_random_samples(\n                batch_sampler, bbox_labels, img_width, img_height, scale_array,\n                settings.resize_width, settings.resize_height)\n            img = np.array(img)\n            if len(sampled_bbox) > 0:\n                idx = int(np.random.uniform(0, len(sampled_bbox)))\n                img, sampled_labels = image_util.crop_image_sampling(\n                    img, bbox_labels, sampled_bbox[idx], img_width, img_height,\n                    settings.resize_width, settings.resize_height,\n                    settings.min_face_size)\n\n            img = img.astype('uint8')\n            img = Image.fromarray(img)\n\n        else:\n            # hard-code here\n            batch_sampler.append(\n                image_util.sampler(1, 50, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,\n                                   0.0, True))\n            batch_sampler.append(\n                image_util.sampler(1, 50, 0.3, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,\n                                   0.0, True))\n            batch_sampler.append(\n                image_util.sampler(1, 50, 0.3, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,\n                                   0.0, True))\n            batch_sampler.append(\n                image_util.sampler(1, 50, 0.3, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,\n                                   0.0, True))\n            batch_sampler.append(\n                image_util.sampler(1, 50, 0.3, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,\n                                   0.0, True))\n            sampled_bbox = image_util.generate_batch_samples(\n                batch_sampler, bbox_labels, img_width, img_height)\n\n            img = np.array(img)\n            if len(sampled_bbox) > 0:\n                idx = int(np.random.uniform(0, len(sampled_bbox)))\n                img, sampled_labels = image_util.crop_image(\n                    img, bbox_labels, sampled_bbox[idx], img_width, img_height,\n                    settings.resize_width, settings.resize_height,\n                    settings.min_face_size)\n\n            img = Image.fromarray(img)\n    interp_mode = [\n        Image.BILINEAR, Image.HAMMING, Image.NEAREST, Image.BICUBIC,\n        Image.LANCZOS\n    ]\n    interp_indx = np.random.randint(0, 5)\n\n    img = img.resize(\n        (settings.resize_width, settings.resize_height),\n        resample=interp_mode[interp_indx])\n    img = np.array(img)\n\n    if mode == 'train':\n        mirror = int(np.random.uniform(0, 2))\n        if mirror == 1:\n            img = img[:, ::-1, :]\n            for i in six.moves.xrange(len(sampled_labels)):\n                tmp = sampled_labels[i][1]\n                sampled_labels[i][1] = 1 - sampled_labels[i][3]\n                sampled_labels[i][3] = 1 - tmp\n\n    img = to_chw_bgr(img)\n    img = img.astype('float32')\n    img -= settings.img_mean\n    img = img * settings.scale\n    return img, sampled_labels\n\n\ndef load_file_list(input_txt):\n    with open(input_txt, 'r') as f_dir:\n        lines_input_txt = f_dir.readlines()\n\n    file_dict = {}\n    num_class = 0\n    for i in range(len(lines_input_txt)):\n        line_txt = lines_input_txt[i].strip('\\n\\t\\r')\n        if '--' in line_txt:\n            if i != 0:\n                num_class += 1\n            file_dict[num_class] = []\n            file_dict[num_class].append(line_txt)\n        if '--' not in line_txt:\n            if len(line_txt) > 6:\n                split_str = line_txt.split(' ')\n                x1_min = float(split_str[0])\n                y1_min = float(split_str[1])\n                x2_max = float(split_str[2])\n                y2_max = float(split_str[3])\n                line_txt = str(x1_min) + ' ' + str(y1_min) + ' ' + str(\n                    x2_max) + ' ' + str(y2_max)\n                file_dict[num_class].append(line_txt)\n            else:\n                file_dict[num_class].append(line_txt)\n\n    return list(file_dict.values())\n\n\ndef expand_bboxes(bboxes,\n                  expand_left=2.,\n                  expand_up=2.,\n                  expand_right=2.,\n                  expand_down=2.):\n    \"\"\"\n    Expand bboxes, expand 2 times by defalut.\n    \"\"\"\n    expand_boxes = []\n    for bbox in bboxes:\n        xmin = bbox[0]\n        ymin = bbox[1]\n        xmax = bbox[2]\n        ymax = bbox[3]\n        w = xmax - xmin\n        h = ymax - ymin\n        ex_xmin = max(xmin - w / expand_left, 0.)\n        ex_ymin = max(ymin - h / expand_up, 0.)\n        ex_xmax = min(xmax + w / expand_right, 1.)\n        ex_ymax = min(ymax + h / expand_down, 1.)\n        expand_boxes.append([ex_xmin, ex_ymin, ex_xmax, ex_ymax])\n    return expand_boxes\n\n\ndef train_generator(settings, file_list, batch_size, shuffle=True):\n    def reader():\n        if shuffle:\n            np.random.shuffle(file_list)\n        batch_out = []\n        for item in file_list:\n            image_name = item[0]\n            image_path = os.path.join(settings.data_dir, image_name)\n            im = Image.open(image_path)\n            if im.mode == 'L':\n                im = im.convert('RGB')\n            im_width, im_height = im.size\n\n            # layout: label | xmin | ymin | xmax | ymax\n            bbox_labels = []\n            for index_box in range(len(item)):\n                if index_box >= 2:\n                    bbox_sample = []\n                    temp_info_box = item[index_box].split(' ')\n                    xmin = float(temp_info_box[0])\n                    ymin = float(temp_info_box[1])\n                    w = float(temp_info_box[2])\n                    h = float(temp_info_box[3])\n\n                    # Filter out wrong labels\n                    if w < 0 or h < 0:\n                        continue\n                    xmax = xmin + w\n                    ymax = ymin + h\n\n                    bbox_sample.append(1)\n                    bbox_sample.append(float(xmin) / im_width)\n                    bbox_sample.append(float(ymin) / im_height)\n                    bbox_sample.append(float(xmax) / im_width)\n                    bbox_sample.append(float(ymax) / im_height)\n                    bbox_labels.append(bbox_sample)\n            im, sample_labels = preprocess(im, bbox_labels, \"train\", settings,\n                                           image_path)\n            sample_labels = np.array(sample_labels)\n            if len(sample_labels) == 0: continue\n\n            im = im.astype('float32')\n            face_box = sample_labels[:, 1:5]\n            head_box = expand_bboxes(face_box)\n            label = [1] * len(face_box)\n            batch_out.append((im, face_box, head_box, label))\n            if len(batch_out) == batch_size:\n                yield batch_out\n                batch_out = []\n\n    return reader\n\n\ndef train(settings, file_list, batch_size, shuffle=True, num_workers=8):\n    file_lists = load_file_list(file_list)\n    n = int(math.ceil(len(file_lists) // num_workers))\n    split_lists = [file_lists[i:i + n] for i in range(0, len(file_lists), n)]\n    readers = []\n    for iterm in split_lists:\n        readers.append(train_generator(settings, iterm, batch_size, shuffle))\n    return paddle.reader.multiprocess_reader(readers, False)\n\n\ndef test(settings, file_list):\n    file_lists = load_file_list(file_list)\n\n    def reader():\n        for image in file_lists:\n            image_name = image[0]\n            image_path = os.path.join(settings.data_dir, image_name)\n            im = Image.open(image_path)\n            if im.mode == 'L':\n                im = im.convert('RGB')\n            yield im, image_path\n\n    return reader\n\n\ndef infer(settings, image_path):\n    def batch_reader():\n        img = Image.open(image_path)\n        if img.mode == 'L':\n            img = im.convert('RGB')\n        im_width, im_height = img.size\n        if settings.resize_width and settings.resize_height:\n            img = img.resize((settings.resize_width, settings.resize_height),\n                             Image.ANTIALIAS)\n        img = np.array(img)\n        img = to_chw_bgr(img)\n        img = img.astype('float32')\n        img -= settings.img_mean\n        img = img * settings.scale\n        return np.array([img])\n\n    return batch_reader\n", "path": "PaddleCV/face_detection/reader.py"}], "after_files": [{"content": "# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom PIL import Image\nfrom PIL import ImageDraw\nimport numpy as np\nimport xml.etree.ElementTree\nimport os\nimport time\nimport copy\nimport random\nimport cv2\nimport six\nimport math\nfrom itertools import islice\nimport paddle\nimport image_util\n\n\nclass Settings(object):\n    def __init__(self,\n                 dataset=None,\n                 data_dir=None,\n                 label_file=None,\n                 resize_h=None,\n                 resize_w=None,\n                 mean_value=[104., 117., 123.],\n                 apply_distort=True,\n                 apply_expand=True,\n                 ap_version='11point',\n                 toy=0):\n        self.dataset = dataset\n        self.ap_version = ap_version\n        self.toy = toy\n        self.data_dir = data_dir\n        self.apply_distort = apply_distort\n        self.apply_expand = apply_expand\n        self.resize_height = resize_h\n        self.resize_width = resize_w\n        self.img_mean = np.array(mean_value)[:, np.newaxis, np.newaxis].astype(\n            'float32')\n        self.expand_prob = 0.5\n        self.expand_max_ratio = 4\n        self.hue_prob = 0.5\n        self.hue_delta = 18\n        self.contrast_prob = 0.5\n        self.contrast_delta = 0.5\n        self.saturation_prob = 0.5\n        self.saturation_delta = 0.5\n        self.brightness_prob = 0.5\n        # _brightness_delta is the normalized value by 256\n        self.brightness_delta = 0.125\n        self.scale = 0.007843  # 1 / 127.5\n        self.data_anchor_sampling_prob = 0.5\n        self.min_face_size = 8.0\n\n\ndef to_chw_bgr(image):\n    \"\"\"\n    Transpose image from HWC to CHW and from RBG to BGR.\n    Args:\n        image (np.array): an image with HWC and RBG layout.\n    \"\"\"\n    # HWC to CHW\n    if len(image.shape) == 3:\n        image = np.swapaxes(image, 1, 2)\n        image = np.swapaxes(image, 1, 0)\n    # RBG to BGR\n    image = image[[2, 1, 0], :, :]\n    return image\n\n\ndef preprocess(img, bbox_labels, mode, settings, image_path):\n    img_width, img_height = img.size\n    sampled_labels = bbox_labels\n    if mode == 'train':\n        if settings.apply_distort:\n            img = image_util.distort_image(img, settings)\n        if settings.apply_expand:\n            img, bbox_labels, img_width, img_height = image_util.expand_image(\n                img, bbox_labels, img_width, img_height, settings)\n\n        # sampling\n        batch_sampler = []\n\n        prob = np.random.uniform(0., 1.)\n        if prob > settings.data_anchor_sampling_prob:\n            scale_array = np.array([16, 32, 64, 128, 256, 512])\n            batch_sampler.append(\n                image_util.sampler(1, 10, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.2,\n                                   0.0, True))\n            sampled_bbox = image_util.generate_batch_random_samples(\n                batch_sampler, bbox_labels, img_width, img_height, scale_array,\n                settings.resize_width, settings.resize_height)\n            img = np.array(img)\n            if len(sampled_bbox) > 0:\n                idx = int(np.random.uniform(0, len(sampled_bbox)))\n                img, sampled_labels = image_util.crop_image_sampling(\n                    img, bbox_labels, sampled_bbox[idx], img_width, img_height,\n                    settings.resize_width, settings.resize_height,\n                    settings.min_face_size)\n\n            img = img.astype('uint8')\n            img = Image.fromarray(img)\n\n        else:\n            # hard-code here\n            batch_sampler.append(\n                image_util.sampler(1, 50, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,\n                                   0.0, True))\n            batch_sampler.append(\n                image_util.sampler(1, 50, 0.3, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,\n                                   0.0, True))\n            batch_sampler.append(\n                image_util.sampler(1, 50, 0.3, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,\n                                   0.0, True))\n            batch_sampler.append(\n                image_util.sampler(1, 50, 0.3, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,\n                                   0.0, True))\n            batch_sampler.append(\n                image_util.sampler(1, 50, 0.3, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0,\n                                   0.0, True))\n            sampled_bbox = image_util.generate_batch_samples(\n                batch_sampler, bbox_labels, img_width, img_height)\n\n            img = np.array(img)\n            if len(sampled_bbox) > 0:\n                idx = int(np.random.uniform(0, len(sampled_bbox)))\n                img, sampled_labels = image_util.crop_image(\n                    img, bbox_labels, sampled_bbox[idx], img_width, img_height,\n                    settings.resize_width, settings.resize_height,\n                    settings.min_face_size)\n\n            img = Image.fromarray(img)\n    interp_mode = [\n        Image.BILINEAR, Image.HAMMING, Image.NEAREST, Image.BICUBIC,\n        Image.LANCZOS\n    ]\n    interp_indx = np.random.randint(0, 5)\n\n    img = img.resize(\n        (settings.resize_width, settings.resize_height),\n        resample=interp_mode[interp_indx])\n    img = np.array(img)\n\n    if mode == 'train':\n        mirror = int(np.random.uniform(0, 2))\n        if mirror == 1:\n            img = img[:, ::-1, :]\n            for i in six.moves.xrange(len(sampled_labels)):\n                tmp = sampled_labels[i][1]\n                sampled_labels[i][1] = 1 - sampled_labels[i][3]\n                sampled_labels[i][3] = 1 - tmp\n\n    img = to_chw_bgr(img)\n    img = img.astype('float32')\n    img -= settings.img_mean\n    img = img * settings.scale\n    return img, sampled_labels\n\n\ndef load_file_list(input_txt):\n    with open(input_txt, 'r') as f_dir:\n        lines_input_txt = f_dir.readlines()\n\n    file_dict = {}\n    num_class = 0\n    for i in range(len(lines_input_txt)):\n        line_txt = lines_input_txt[i].strip('\\n\\t\\r')\n        if '--' in line_txt:\n            if i != 0:\n                num_class += 1\n            file_dict[num_class] = []\n            file_dict[num_class].append(line_txt)\n        if '--' not in line_txt:\n            if len(line_txt) > 6:\n                split_str = line_txt.split(' ')\n                x1_min = float(split_str[0])\n                y1_min = float(split_str[1])\n                x2_max = float(split_str[2])\n                y2_max = float(split_str[3])\n                line_txt = str(x1_min) + ' ' + str(y1_min) + ' ' + str(\n                    x2_max) + ' ' + str(y2_max)\n                file_dict[num_class].append(line_txt)\n            else:\n                file_dict[num_class].append(line_txt)\n\n    return list(file_dict.values())\n\n\ndef expand_bboxes(bboxes,\n                  expand_left=2.,\n                  expand_up=2.,\n                  expand_right=2.,\n                  expand_down=2.):\n    \"\"\"\n    Expand bboxes, expand 2 times by defalut.\n    \"\"\"\n    expand_boxes = []\n    for bbox in bboxes:\n        xmin = bbox[0]\n        ymin = bbox[1]\n        xmax = bbox[2]\n        ymax = bbox[3]\n        w = xmax - xmin\n        h = ymax - ymin\n        ex_xmin = max(xmin - w / expand_left, 0.)\n        ex_ymin = max(ymin - h / expand_up, 0.)\n        ex_xmax = min(xmax + w / expand_right, 1.)\n        ex_ymax = min(ymax + h / expand_down, 1.)\n        expand_boxes.append([ex_xmin, ex_ymin, ex_xmax, ex_ymax])\n    return expand_boxes\n\n\ndef train_generator(settings, file_list, batch_size, shuffle=True):\n    def reader():\n        if shuffle:\n            np.random.shuffle(file_list)\n        batch_out = []\n        for item in file_list:\n            image_name = item[0]\n            image_path = os.path.join(settings.data_dir, image_name)\n            im = Image.open(image_path)\n            if im.mode == 'L':\n                im = im.convert('RGB')\n            im_width, im_height = im.size\n\n            # layout: label | xmin | ymin | xmax | ymax\n            bbox_labels = []\n            for index_box in range(len(item)):\n                if index_box >= 2:\n                    bbox_sample = []\n                    temp_info_box = item[index_box].split(' ')\n                    xmin = float(temp_info_box[0])\n                    ymin = float(temp_info_box[1])\n                    w = float(temp_info_box[2])\n                    h = float(temp_info_box[3])\n\n                    # Filter out wrong labels\n                    if w < 0 or h < 0:\n                        continue\n                    xmax = xmin + w\n                    ymax = ymin + h\n\n                    bbox_sample.append(1)\n                    bbox_sample.append(float(xmin) / im_width)\n                    bbox_sample.append(float(ymin) / im_height)\n                    bbox_sample.append(float(xmax) / im_width)\n                    bbox_sample.append(float(ymax) / im_height)\n                    bbox_labels.append(bbox_sample)\n            im, sample_labels = preprocess(im, bbox_labels, \"train\", settings,\n                                           image_path)\n            sample_labels = np.array(sample_labels)\n            if len(sample_labels) == 0: continue\n\n            im = im.astype('float32')\n            face_box = sample_labels[:, 1:5]\n            head_box = expand_bboxes(face_box)\n            label = [1] * len(face_box)\n            batch_out.append((im, face_box, head_box, label))\n            if len(batch_out) == batch_size:\n                yield batch_out\n                batch_out = []\n\n    return reader\n\n\ndef train(settings, file_list, batch_size, shuffle=True, num_workers=8):\n    file_lists = load_file_list(file_list)\n    n = int(math.ceil(len(file_lists) // num_workers))\n    split_lists = [file_lists[i:i + n] for i in range(0, len(file_lists), n)]\n    readers = []\n    for iterm in split_lists:\n        readers.append(train_generator(settings, iterm, batch_size, shuffle))\n    return paddle.reader.multiprocess_reader(readers, False)\n\n\ndef test(settings, file_list):\n    file_lists = load_file_list(file_list)\n\n    def reader():\n        for image in file_lists:\n            image_name = image[0]\n            image_path = os.path.join(settings.data_dir, image_name)\n            im = Image.open(image_path)\n            if im.mode == 'L':\n                im = im.convert('RGB')\n            yield im, image_path\n\n    return reader\n\n\ndef infer(settings, image_path):\n    def batch_reader():\n        img = Image.open(image_path)\n        if img.mode == 'L':\n            img = img.convert('RGB')\n        im_width, im_height = img.size\n        if settings.resize_width and settings.resize_height:\n            img = img.resize((settings.resize_width, settings.resize_height),\n                             Image.ANTIALIAS)\n        img = np.array(img)\n        img = to_chw_bgr(img)\n        img = img.astype('float32')\n        img -= settings.img_mean\n        img = img * settings.scale\n        return np.array([img])\n\n    return batch_reader\n", "path": "PaddleCV/face_detection/reader.py"}]}