code
stringlengths 66
870k
| docstring
stringlengths 19
26.7k
| func_name
stringlengths 1
138
| language
stringclasses 1
value | repo
stringlengths 7
68
| path
stringlengths 5
324
| url
stringlengths 46
389
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def _download(url, path, md5sum=None):
"""
Download from url, save to path.
url (str): download url
path (str): download to given path
"""
if not osp.exists(path):
os.makedirs(path)
fname = osp.split(url)[-1]
fullname = osp.join(path, fname)
retry_cnt = 0
while not (osp.exists(fullname) and _check_exist_file_md5(fullname, md5sum,
url)):
if retry_cnt < DOWNLOAD_RETRY_LIMIT:
retry_cnt += 1
else:
raise RuntimeError("Download from {} failed. "
"Retry limit reached".format(url))
# NOTE: windows path join may incur \, which is invalid in url
if sys.platform == "win32":
url = url.replace('\\', '/')
req = requests.get(url, stream=True)
if req.status_code != 200:
raise RuntimeError("Downloading from {} failed with code "
"{}!".format(url, req.status_code))
# For protecting download interupted, download to
# tmp_fullname firstly, move tmp_fullname to fullname
# after download finished
tmp_fullname = fullname + "_tmp"
total_size = req.headers.get('content-length')
with open(tmp_fullname, 'wb') as f:
if total_size:
for chunk in tqdm.tqdm(
req.iter_content(chunk_size=1024),
total=(int(total_size) + 1023) // 1024,
unit='KB'):
f.write(chunk)
else:
for chunk in req.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
shutil.move(tmp_fullname, fullname)
return fullname |
Download from url, save to path.
url (str): download url
path (str): download to given path
| _download | python | PaddlePaddle/models | modelcenter/PP-YOLOv2/APP/src/download.py | https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-YOLOv2/APP/src/download.py | Apache-2.0 |
def decode_image(im_file, im_info):
"""read rgb image
Args:
im_file (str|np.ndarray): input can be image path or np.ndarray
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
if isinstance(im_file, str):
with open(im_file, 'rb') as f:
im_read = f.read()
data = np.frombuffer(im_read, dtype='uint8')
im = cv2.imdecode(data, 1) # BGR mode, but need RGB mode
im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
else:
im = im_file
im_info['im_shape'] = np.array(im.shape[:2], dtype=np.float32)
im_info['scale_factor'] = np.array([1., 1.], dtype=np.float32)
return im, im_info | read rgb image
Args:
im_file (str|np.ndarray): input can be image path or np.ndarray
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| decode_image | python | PaddlePaddle/models | modelcenter/PP-YOLOv2/APP/src/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-YOLOv2/APP/src/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
assert len(self.target_size) == 2
assert self.target_size[0] > 0 and self.target_size[1] > 0
im_channel = im.shape[2]
im_scale_y, im_scale_x = self.generate_scale(im)
im = cv2.resize(
im,
None,
None,
fx=im_scale_x,
fy=im_scale_y,
interpolation=self.interp)
im_info['im_shape'] = np.array(im.shape[:2]).astype('float32')
im_info['scale_factor'] = np.array(
[im_scale_y, im_scale_x]).astype('float32')
return im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | modelcenter/PP-YOLOv2/APP/src/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-YOLOv2/APP/src/preprocess.py | Apache-2.0 |
def generate_scale(self, im):
"""
Args:
im (np.ndarray): image (np.ndarray)
Returns:
im_scale_x: the resize ratio of X
im_scale_y: the resize ratio of Y
"""
origin_shape = im.shape[:2]
im_c = im.shape[2]
if self.keep_ratio:
im_size_min = np.min(origin_shape)
im_size_max = np.max(origin_shape)
target_size_min = np.min(self.target_size)
target_size_max = np.max(self.target_size)
im_scale = float(target_size_min) / float(im_size_min)
if np.round(im_scale * im_size_max) > target_size_max:
im_scale = float(target_size_max) / float(im_size_max)
im_scale_x = im_scale
im_scale_y = im_scale
else:
resize_h, resize_w = self.target_size
im_scale_y = resize_h / float(origin_shape[0])
im_scale_x = resize_w / float(origin_shape[1])
return im_scale_y, im_scale_x |
Args:
im (np.ndarray): image (np.ndarray)
Returns:
im_scale_x: the resize ratio of X
im_scale_y: the resize ratio of Y
| generate_scale | python | PaddlePaddle/models | modelcenter/PP-YOLOv2/APP/src/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-YOLOv2/APP/src/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
im = im.astype(np.float32, copy=False)
if self.is_scale:
scale = 1.0 / 255.0
im *= scale
if self.norm_type == 'mean_std':
mean = np.array(self.mean)[np.newaxis, np.newaxis, :]
std = np.array(self.std)[np.newaxis, np.newaxis, :]
im -= mean
im /= std
return im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | modelcenter/PP-YOLOv2/APP/src/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-YOLOv2/APP/src/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
im = im.transpose((2, 0, 1)).copy()
return im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | modelcenter/PP-YOLOv2/APP/src/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-YOLOv2/APP/src/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
coarsest_stride = self.coarsest_stride
if coarsest_stride <= 0:
return im, im_info
im_c, im_h, im_w = im.shape
pad_h = int(np.ceil(float(im_h) / coarsest_stride) * coarsest_stride)
pad_w = int(np.ceil(float(im_w) / coarsest_stride) * coarsest_stride)
padding_im = np.zeros((im_c, pad_h, pad_w), dtype=np.float32)
padding_im[:, :im_h, :im_w] = im
return padding_im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | modelcenter/PP-YOLOv2/APP/src/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-YOLOv2/APP/src/preprocess.py | Apache-2.0 |
def get_color_map_list(num_classes):
"""
Args:
num_classes (int): number of class
Returns:
color_map (list): RGB color list
"""
color_map = num_classes * [0, 0, 0]
for i in range(0, num_classes):
j = 0
lab = i
while lab:
color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j))
color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j))
color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j))
j += 1
lab >>= 3
color_map = [color_map[i:i + 3] for i in range(0, len(color_map), 3)]
return color_map |
Args:
num_classes (int): number of class
Returns:
color_map (list): RGB color list
| get_color_map_list | python | PaddlePaddle/models | modelcenter/PP-YOLOv2/APP/src/visualize.py | https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-YOLOv2/APP/src/visualize.py | Apache-2.0 |
def get_package_data_files(package, data, package_dir=None):
"""
Helps to list all specified files in package including files in directories
since `package_data` ignores directories.
"""
if package_dir is None:
package_dir = os.path.join(*package.split('.'))
all_files = []
for f in data:
path = os.path.join(package_dir, f)
if os.path.isfile(path):
all_files.append(f)
continue
for root, _dirs, files in os.walk(path, followlinks=True):
root = os.path.relpath(root, package_dir)
for file in files:
file = os.path.join(root, file)
if file not in all_files:
all_files.append(file)
return all_files |
Helps to list all specified files in package including files in directories
since `package_data` ignores directories.
| get_package_data_files | python | PaddlePaddle/models | paddlecv/setup.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/setup.py | Apache-2.0 |
def __call__(self, inputs):
"""
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
"""
# for the input_keys as list
# inputs = [pipe_input[key] for pipe_input in pipe_inputs for key in self.input_keys]
key = self.input_keys[0]
if isinstance(inputs[0][key], (list, tuple)):
inputs = [input[key] for input in inputs]
else:
inputs = [[input[key]] for input in inputs]
sub_index_list = [len(input) for input in inputs]
inputs = reduce(lambda x, y: x.extend(y) or x, inputs)
# step2: run
outputs, bbox_nums = self.infer(inputs)
# step3: merge
curr_offsef_id = 0
pipe_outputs = []
for i, bbox_num in enumerate(bbox_nums):
output = outputs[i]
start_id = 0
for num in bbox_num:
end_id = start_id + num
out = {k: v[start_id:end_id] for k, v in output.items()}
pipe_outputs.append(out)
start_id = end_id
return pipe_outputs |
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
| __call__ | python | PaddlePaddle/models | paddlecv/custom_op/inference.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/custom_op/inference.py | Apache-2.0 |
def hard_nms(box_scores, iou_threshold, top_k=-1, candidate_size=200):
"""
Args:
box_scores (N, 5): boxes in corner-form and probabilities.
iou_threshold: intersection over union threshold.
top_k: keep top_k results. If k <= 0, keep all the results.
candidate_size: only consider the candidates with the highest scores.
Returns:
picked: a list of indexes of the kept boxes
"""
scores = box_scores[:, -1]
boxes = box_scores[:, :-1]
picked = []
indexes = np.argsort(scores)
indexes = indexes[-candidate_size:]
while len(indexes) > 0:
current = indexes[-1]
picked.append(current)
if 0 < top_k == len(picked) or len(indexes) == 1:
break
current_box = boxes[current, :]
indexes = indexes[:-1]
rest_boxes = boxes[indexes, :]
iou = iou_of(
rest_boxes,
np.expand_dims(
current_box, axis=0), )
indexes = indexes[iou <= iou_threshold]
return box_scores[picked, :] |
Args:
box_scores (N, 5): boxes in corner-form and probabilities.
iou_threshold: intersection over union threshold.
top_k: keep top_k results. If k <= 0, keep all the results.
candidate_size: only consider the candidates with the highest scores.
Returns:
picked: a list of indexes of the kept boxes
| hard_nms | python | PaddlePaddle/models | paddlecv/custom_op/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/custom_op/postprocess.py | Apache-2.0 |
def iou_of(boxes0, boxes1, eps=1e-5):
"""Return intersection-over-union (Jaccard index) of boxes.
Args:
boxes0 (N, 4): ground truth boxes.
boxes1 (N or 1, 4): predicted boxes.
eps: a small number to avoid 0 as denominator.
Returns:
iou (N): IoU values.
"""
overlap_left_top = np.maximum(boxes0[..., :2], boxes1[..., :2])
overlap_right_bottom = np.minimum(boxes0[..., 2:], boxes1[..., 2:])
overlap_area = area_of(overlap_left_top, overlap_right_bottom)
area0 = area_of(boxes0[..., :2], boxes0[..., 2:])
area1 = area_of(boxes1[..., :2], boxes1[..., 2:])
return overlap_area / (area0 + area1 - overlap_area + eps) | Return intersection-over-union (Jaccard index) of boxes.
Args:
boxes0 (N, 4): ground truth boxes.
boxes1 (N or 1, 4): predicted boxes.
eps: a small number to avoid 0 as denominator.
Returns:
iou (N): IoU values.
| iou_of | python | PaddlePaddle/models | paddlecv/custom_op/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/custom_op/postprocess.py | Apache-2.0 |
def area_of(left_top, right_bottom):
"""Compute the areas of rectangles given two corners.
Args:
left_top (N, 2): left top corner.
right_bottom (N, 2): right bottom corner.
Returns:
area (N): return the area.
"""
hw = np.clip(right_bottom - left_top, 0.0, None)
return hw[..., 0] * hw[..., 1] | Compute the areas of rectangles given two corners.
Args:
left_top (N, 2): left top corner.
right_bottom (N, 2): right bottom corner.
Returns:
area (N): return the area.
| area_of | python | PaddlePaddle/models | paddlecv/custom_op/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/custom_op/postprocess.py | Apache-2.0 |
def decode_image(im_file, im_info):
"""read rgb image
Args:
im_file (str|np.ndarray): input can be image path or np.ndarray
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
if isinstance(im_file, str):
with open(im_file, 'rb') as f:
im_read = f.read()
data = np.frombuffer(im_read, dtype='uint8')
im = cv2.imdecode(data, 1) # BGR mode, but need RGB mode
im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
else:
im = im_file
im_info['im_shape'] = np.array(im.shape[:2], dtype=np.float32)
im_info['scale_factor'] = np.array([1., 1.], dtype=np.float32)
return im, im_info | read rgb image
Args:
im_file (str|np.ndarray): input can be image path or np.ndarray
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| decode_image | python | PaddlePaddle/models | paddlecv/custom_op/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/custom_op/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
assert len(self.target_size) == 2
assert self.target_size[0] > 0 and self.target_size[1] > 0
im_channel = im.shape[2]
im_scale_y, im_scale_x = self.generate_scale(im)
# set image_shape
im_info['input_shape'][1] = int(im_scale_y * im.shape[0])
im_info['input_shape'][2] = int(im_scale_x * im.shape[1])
im = cv2.resize(
im,
None,
None,
fx=im_scale_x,
fy=im_scale_y,
interpolation=self.interp)
im_info['im_shape'] = np.array(im.shape[:2]).astype('float32')
im_info['scale_factor'] = np.array(
[im_scale_y, im_scale_x]).astype('float32')
return im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | paddlecv/custom_op/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/custom_op/preprocess.py | Apache-2.0 |
def generate_scale(self, im):
"""
Args:
im (np.ndarray): image (np.ndarray)
Returns:
im_scale_x: the resize ratio of X
im_scale_y: the resize ratio of Y
"""
origin_shape = im.shape[:2]
im_c = im.shape[2]
if self.keep_ratio:
im_size_min = np.min(origin_shape)
im_size_max = np.max(origin_shape)
target_size_min = np.min(self.target_size)
target_size_max = np.max(self.target_size)
im_scale = float(target_size_min) / float(im_size_min)
if np.round(im_scale * im_size_max) > target_size_max:
im_scale = float(target_size_max) / float(im_size_max)
im_scale_x = im_scale
im_scale_y = im_scale
else:
resize_h, resize_w = self.target_size
im_scale_y = resize_h / float(origin_shape[0])
im_scale_x = resize_w / float(origin_shape[1])
return im_scale_y, im_scale_x |
Args:
im (np.ndarray): image (np.ndarray)
Returns:
im_scale_x: the resize ratio of X
im_scale_y: the resize ratio of Y
| generate_scale | python | PaddlePaddle/models | paddlecv/custom_op/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/custom_op/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
im = im.astype(np.float32, copy=False)
if self.is_scale:
scale = 1.0 / 255.0
im *= scale
if self.norm_type == 'mean_std':
mean = np.array(self.mean)[np.newaxis, np.newaxis, :]
std = np.array(self.std)[np.newaxis, np.newaxis, :]
im -= mean
im /= std
return im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | paddlecv/custom_op/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/custom_op/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
im = im.transpose((2, 0, 1)).copy()
return im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | paddlecv/custom_op/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/custom_op/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
coarsest_stride = self.coarsest_stride
if coarsest_stride <= 0:
return im, im_info
im_c, im_h, im_w = im.shape
pad_h = int(np.ceil(float(im_h) / coarsest_stride) * coarsest_stride)
pad_w = int(np.ceil(float(im_w) / coarsest_stride) * coarsest_stride)
padding_im = np.zeros((im_c, pad_h, pad_w), dtype=np.float32)
padding_im[:, :im_h, :im_w] = im
return padding_im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | paddlecv/custom_op/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/custom_op/preprocess.py | Apache-2.0 |
def topo_sort(self):
"""
Topological sort of DAG, creates inverted multi-layers views.
Args:
graph (dict): the DAG stucture
in_degrees (dict): Next op list for each op
Returns:
sort_result: the hierarchical topology list. examples:
DAG :[A -> B -> C -> E]
\-> D /
sort_result: [A, B, C, D, E]
"""
# Select vertices with in_degree = 0
Q = [u for u in self.in_degrees if self.in_degrees[u] == 0]
sort_result = []
while Q:
u = Q.pop()
sort_result.append(u)
for v in self.graph[u]:
# remove output degrees
self.in_degrees[v] -= 1
# re-select vertices with in_degree = 0
if self.in_degrees[v] == 0:
Q.append(v)
if len(sort_result) == self.num:
return sort_result
else:
return None |
Topological sort of DAG, creates inverted multi-layers views.
Args:
graph (dict): the DAG stucture
in_degrees (dict): Next op list for each op
Returns:
sort_result: the hierarchical topology list. examples:
DAG :[A -> B -> C -> E]
\-> D /
sort_result: [A, B, C, D, E]
| topo_sort | python | PaddlePaddle/models | paddlecv/ppcv/core/framework.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/core/framework.py | Apache-2.0 |
def register(cls):
"""
Register a given module class.
Args:
cls (type): Module class to be registered.
Returns: cls
"""
if cls.__name__ in global_config:
raise ValueError("Module class already registered: {}".format(
cls.__name__))
global_config[cls.__name__] = cls
return cls |
Register a given module class.
Args:
cls (type): Module class to be registered.
Returns: cls
| register | python | PaddlePaddle/models | paddlecv/ppcv/core/workspace.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/core/workspace.py | Apache-2.0 |
def create(cls_name, op_cfg, env_cfg):
"""
Create an instance of given module class.
Args:
cls_name(str): Class of which to create instnce.
Return: instance of type `cls_or_name`
"""
assert type(cls_name) == str, "should be a name of class"
if cls_name not in global_config:
raise ValueError("The module {} is not registered".format(cls_name))
cls = global_config[cls_name]
return cls(op_cfg, env_cfg) |
Create an instance of given module class.
Args:
cls_name(str): Class of which to create instnce.
Return: instance of type `cls_or_name`
| create | python | PaddlePaddle/models | paddlecv/ppcv/core/workspace.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/core/workspace.py | Apache-2.0 |
def create_operators(params, mod):
"""
create operators based on the config
Args:
params(list): a dict list, used to create some operators
mod(module) : a module that can import single ops
"""
assert isinstance(params, list), ('operator config should be a list')
if mod is None:
mod = importlib.import_module(__name__)
ops = []
for operator in params:
if isinstance(operator, str):
op_name = operator
param = {}
else:
assert isinstance(operator,
dict) and len(operator) == 1, "yaml format error"
op_name = list(operator)[0]
param = {} if operator[op_name] is None else operator[op_name]
op = getattr(mod, op_name)(**param)
ops.append(op)
return ops |
create operators based on the config
Args:
params(list): a dict list, used to create some operators
mod(module) : a module that can import single ops
| create_operators | python | PaddlePaddle/models | paddlecv/ppcv/ops/base.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/base.py | Apache-2.0 |
def get(self, key):
"""
key can be one of [list, tuple, str]
"""
if isinstance(key, (list, tuple)):
return [self.data_dict[k] for k in key]
elif isinstance(key, (str)):
return self.data_dict[key]
else:
assert False, f"key({key}) type must be in on of [list, tuple, str] but got {type(key)}" |
key can be one of [list, tuple, str]
| get | python | PaddlePaddle/models | paddlecv/ppcv/ops/general_data_obj.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/general_data_obj.py | Apache-2.0 |
def get_rotate_crop_image(self, img, points):
'''
img_height, img_width = img.shape[0:2]
left = int(np.min(points[:, 0]))
right = int(np.max(points[:, 0]))
top = int(np.min(points[:, 1]))
bottom = int(np.max(points[:, 1]))
img_crop = img[top:bottom, left:right, :].copy()
points[:, 0] = points[:, 0] - left
points[:, 1] = points[:, 1] - top
'''
assert len(points) == 4, "shape of points must be 4*2"
img_crop_width = int(
max(
np.linalg.norm(points[0] - points[1]),
np.linalg.norm(points[2] - points[3])))
img_crop_height = int(
max(
np.linalg.norm(points[0] - points[3]),
np.linalg.norm(points[1] - points[2])))
pts_std = np.float32([[0, 0], [img_crop_width, 0],
[img_crop_width, img_crop_height],
[0, img_crop_height]])
M = cv2.getPerspectiveTransform(points.astype(np.float32), pts_std)
dst_img = cv2.warpPerspective(
img,
M, (img_crop_width, img_crop_height),
borderMode=cv2.BORDER_REPLICATE,
flags=cv2.INTER_CUBIC)
dst_img_height, dst_img_width = dst_img.shape[0:2]
if dst_img_height * 1.0 / dst_img_width >= 1.5:
dst_img = np.rot90(dst_img)
return dst_img |
img_height, img_width = img.shape[0:2]
left = int(np.min(points[:, 0]))
right = int(np.max(points[:, 0]))
top = int(np.min(points[:, 1]))
bottom = int(np.max(points[:, 1]))
img_crop = img[top:bottom, left:right, :].copy()
points[:, 0] = points[:, 0] - left
points[:, 1] = points[:, 1] - top
| get_rotate_crop_image | python | PaddlePaddle/models | paddlecv/ppcv/ops/connector/op_connector.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/connector/op_connector.py | Apache-2.0 |
def sorted_boxes(self, dt_boxes):
"""
Sort text boxes in order from top to bottom, left to right
args:
dt_boxes(array):detected text boxes with shape [4, 2]
return:
sorted boxes(array) with shape [4, 2]
"""
num_boxes = dt_boxes.shape[0]
sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0]))
_boxes = list(sorted_boxes)
for i in range(num_boxes - 1):
for j in range(i, 0, -1):
if abs(_boxes[j + 1][0][1] - _boxes[j][0][1]) < 10 and \
(_boxes[j + 1][0][0] < _boxes[j][0][0]):
tmp = _boxes[j]
_boxes[j] = _boxes[j + 1]
_boxes[j + 1] = tmp
else:
break
return _boxes |
Sort text boxes in order from top to bottom, left to right
args:
dt_boxes(array):detected text boxes with shape [4, 2]
return:
sorted boxes(array) with shape [4, 2]
| sorted_boxes | python | PaddlePaddle/models | paddlecv/ppcv/ops/connector/op_connector.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/connector/op_connector.py | Apache-2.0 |
def compute_iou(rec1, rec2):
"""
computing IoU
:param rec1: (y0, x0, y1, x1), which reflects
(top, left, bottom, right)
:param rec2: (y0, x0, y1, x1)
:return: scala value of IoU
"""
# computing area of each rectangles
S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1])
S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1])
# computing the sum_area
sum_area = S_rec1 + S_rec2
# find the each edge of intersect rectangle
left_line = max(rec1[1], rec2[1])
right_line = min(rec1[3], rec2[3])
top_line = max(rec1[0], rec2[0])
bottom_line = min(rec1[2], rec2[2])
# judge if there is an intersect
if left_line >= right_line or top_line >= bottom_line:
return 0.0
else:
intersect = (right_line - left_line) * (bottom_line - top_line)
return (intersect / (sum_area - intersect)) * 1.0 |
computing IoU
:param rec1: (y0, x0, y1, x1), which reflects
(top, left, bottom, right)
:param rec2: (y0, x0, y1, x1)
:return: scala value of IoU
| compute_iou | python | PaddlePaddle/models | paddlecv/ppcv/ops/connector/table_matcher.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/connector/table_matcher.py | Apache-2.0 |
def convert_bbox_to_z(bbox):
"""
Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form
[x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is
the aspect ratio
"""
w = bbox[2] - bbox[0]
h = bbox[3] - bbox[1]
x = bbox[0] + w / 2.
y = bbox[1] + h / 2.
s = w * h # scale is just area
r = w / float(h + 1e-6)
return np.array([x, y, s, r]).reshape((4, 1)) |
Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form
[x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is
the aspect ratio
| convert_bbox_to_z | python | PaddlePaddle/models | paddlecv/ppcv/ops/connector/tracker/tracker.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/connector/tracker/tracker.py | Apache-2.0 |
def convert_x_to_bbox(x, score=None):
"""
Takes a bounding box in the centre form [x,y,s,r] and returns it in the form
[x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right
"""
w = np.sqrt(x[2] * x[3])
h = x[2] / w
if (score == None):
return np.array(
[x[0] - w / 2., x[1] - h / 2., x[0] + w / 2.,
x[1] + h / 2.]).reshape((1, 4))
else:
score = np.array([score])
return np.array([
x[0] - w / 2., x[1] - h / 2., x[0] + w / 2., x[1] + h / 2., score
]).reshape((1, 5)) |
Takes a bounding box in the centre form [x,y,s,r] and returns it in the form
[x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right
| convert_x_to_bbox | python | PaddlePaddle/models | paddlecv/ppcv/ops/connector/tracker/tracker.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/connector/tracker/tracker.py | Apache-2.0 |
def update(self, bbox):
"""
Updates the state vector with observed bbox.
"""
if bbox is not None:
if self.last_observation.sum() >= 0: # no previous observation
previous_box = None
for i in range(self.delta_t):
dt = self.delta_t - i
if self.age - dt in self.observations:
previous_box = self.observations[self.age - dt]
break
if previous_box is None:
previous_box = self.last_observation
"""
Estimate the track speed direction with observations \Delta t steps away
"""
self.velocity = speed_direction(previous_box, bbox)
"""
Insert new observations. This is a ugly way to maintain both self.observations
and self.history_observations. Bear it for the moment.
"""
self.last_observation = bbox
self.observations[self.age] = bbox
self.history_observations.append(bbox)
self.time_since_update = 0
self.history = []
self.hits += 1
self.hit_streak += 1
self.kf.update(convert_bbox_to_z(bbox))
else:
self.kf.update(bbox) |
Updates the state vector with observed bbox.
| update | python | PaddlePaddle/models | paddlecv/ppcv/ops/connector/tracker/tracker.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/connector/tracker/tracker.py | Apache-2.0 |
def predict(self):
"""
Advances the state vector and returns the predicted bounding box estimate.
"""
if ((self.kf.x[6] + self.kf.x[2]) <= 0):
self.kf.x[6] *= 0.0
self.kf.predict()
self.age += 1
if (self.time_since_update > 0):
self.hit_streak = 0
self.time_since_update += 1
self.history.append(convert_x_to_bbox(self.kf.x, score=self.score))
return self.history[-1] |
Advances the state vector and returns the predicted bounding box estimate.
| predict | python | PaddlePaddle/models | paddlecv/ppcv/ops/connector/tracker/tracker.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/connector/tracker/tracker.py | Apache-2.0 |
def update(self, pred_dets, pred_embs=None):
"""
Args:
pred_dets (np.array): Detection results of the image, the shape is
[N, 6], means 'cls_id, score, x0, y0, x1, y1'.
pred_embs (np.array): Embedding results of the image, the shape is
[N, 128] or [N, 512], default as None.
Return:
tracking boxes (np.array): [M, 6], means 'x0, y0, x1, y1, score, id'.
"""
if pred_dets is None:
return np.empty((0, 6))
self.frame_count += 1
bboxes = pred_dets[:, 2:]
scores = pred_dets[:, 1:2]
dets = np.concatenate((bboxes, scores), axis=1)
scores = scores.squeeze(-1)
inds_low = scores > 0.1
inds_high = scores < self.det_thresh
inds_second = np.logical_and(inds_low, inds_high)
# self.det_thresh > score > 0.1, for second matching
dets_second = dets[inds_second] # detections for second matching
remain_inds = scores > self.det_thresh
dets = dets[remain_inds]
# get predicted locations from existing trackers.
trks = np.zeros((len(self.trackers), 5))
to_del = []
ret = []
for t, trk in enumerate(trks):
pos = self.trackers[t].predict()[0]
trk[:] = [pos[0], pos[1], pos[2], pos[3], 0]
if np.any(np.isnan(pos)):
to_del.append(t)
trks = np.ma.compress_rows(np.ma.masked_invalid(trks))
for t in reversed(to_del):
self.trackers.pop(t)
velocities = np.array([
trk.velocity if trk.velocity is not None else np.array((0, 0))
for trk in self.trackers
])
last_boxes = np.array([trk.last_observation for trk in self.trackers])
k_observations = np.array([
k_previous_obs(trk.observations, trk.age, self.delta_t)
for trk in self.trackers
])
"""
First round of association
"""
matched, unmatched_dets, unmatched_trks = associate(
dets, trks, self.iou_threshold, velocities, k_observations,
self.inertia)
for m in matched:
self.trackers[m[1]].update(dets[m[0], :])
"""
Second round of associaton by OCR
"""
# BYTE association
if self.use_byte and len(dets_second) > 0 and unmatched_trks.shape[
0] > 0:
u_trks = trks[unmatched_trks]
iou_left = iou_batch(
dets_second,
u_trks) # iou between low score detections and unmatched tracks
iou_left = np.array(iou_left)
if iou_left.max() > self.iou_threshold:
"""
NOTE: by using a lower threshold, e.g., self.iou_threshold - 0.1, you may
get a higher performance especially on MOT17/MOT20 datasets. But we keep it
uniform here for simplicity
"""
matched_indices = linear_assignment(-iou_left)
to_remove_trk_indices = []
for m in matched_indices:
det_ind, trk_ind = m[0], unmatched_trks[m[1]]
if iou_left[m[0], m[1]] < self.iou_threshold:
continue
self.trackers[trk_ind].update(dets_second[det_ind, :])
to_remove_trk_indices.append(trk_ind)
unmatched_trks = np.setdiff1d(unmatched_trks,
np.array(to_remove_trk_indices))
if unmatched_dets.shape[0] > 0 and unmatched_trks.shape[0] > 0:
left_dets = dets[unmatched_dets]
left_trks = last_boxes[unmatched_trks]
iou_left = iou_batch(left_dets, left_trks)
iou_left = np.array(iou_left)
if iou_left.max() > self.iou_threshold:
"""
NOTE: by using a lower threshold, e.g., self.iou_threshold - 0.1, you may
get a higher performance especially on MOT17/MOT20 datasets. But we keep it
uniform here for simplicity
"""
rematched_indices = linear_assignment(-iou_left)
to_remove_det_indices = []
to_remove_trk_indices = []
for m in rematched_indices:
det_ind, trk_ind = unmatched_dets[m[0]], unmatched_trks[m[
1]]
if iou_left[m[0], m[1]] < self.iou_threshold:
continue
self.trackers[trk_ind].update(dets[det_ind, :])
to_remove_det_indices.append(det_ind)
to_remove_trk_indices.append(trk_ind)
unmatched_dets = np.setdiff1d(unmatched_dets,
np.array(to_remove_det_indices))
unmatched_trks = np.setdiff1d(unmatched_trks,
np.array(to_remove_trk_indices))
for m in unmatched_trks:
self.trackers[m].update(None)
# create and initialise new trackers for unmatched detections
for i in unmatched_dets:
trk = KalmanBoxTracker(dets[i, :], delta_t=self.delta_t)
self.trackers.append(trk)
i = len(self.trackers)
for trk in reversed(self.trackers):
if trk.last_observation.sum() < 0:
d = trk.get_state()[0]
else:
d = trk.last_observation # tlbr + score
if (trk.time_since_update < 1) and (
trk.hit_streak >= self.min_hits or
self.frame_count <= self.min_hits):
# +1 as MOT benchmark requires positive
ret.append(np.concatenate((d, [trk.id + 1])).reshape(1, -1))
i -= 1
# remove dead tracklet
if (trk.time_since_update > self.max_age):
self.trackers.pop(i)
if (len(ret) > 0):
return np.concatenate(ret)
return np.empty((0, 6)) |
Args:
pred_dets (np.array): Detection results of the image, the shape is
[N, 6], means 'cls_id, score, x0, y0, x1, y1'.
pred_embs (np.array): Embedding results of the image, the shape is
[N, 128] or [N, 512], default as None.
Return:
tracking boxes (np.array): [M, 6], means 'x0, y0, x1, y1, score, id'.
| update | python | PaddlePaddle/models | paddlecv/ppcv/ops/connector/tracker/tracker.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/connector/tracker/tracker.py | Apache-2.0 |
def __call__(self, inputs):
"""
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
"""
key = self.input_keys[0]
is_list = False
if isinstance(inputs[0][key], (list, tuple)):
inputs = [input[key] for input in inputs]
is_list = True
else:
inputs = [[input[key]] for input in inputs]
sub_index_list = [len(input) for input in inputs]
inputs = reduce(lambda x, y: x.extend(y) or x, inputs)
# step2: run
outputs = self.infer(inputs)
# step3: merge
curr_offsef_id = 0
pipe_outputs = []
for idx in range(len(sub_index_list)):
sub_start_idx = curr_offsef_id
sub_end_idx = curr_offsef_id + sub_index_list[idx]
output = outputs[sub_start_idx:sub_end_idx]
if len(output) > 0:
output = {k: [o[k] for o in output] for k in output[0]}
if is_list is not True:
output = {k: output[k][0] for k in output}
else:
output = {
self.output_keys[0]: [],
self.output_keys[1]: [],
self.output_keys[2]: []
}
pipe_outputs.append(output)
curr_offsef_id = sub_end_idx
return pipe_outputs |
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/classification/inference.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/classification/inference.py | Apache-2.0 |
def __call__(self, inputs):
"""
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
"""
# for the input_keys as list
# inputs = [pipe_input[key] for pipe_input in pipe_inputs for key in self.input_keys]
key = self.input_keys[0]
if isinstance(inputs[0][key], (list, tuple)):
inputs = [input[key] for input in inputs]
else:
inputs = [[input[key]] for input in inputs]
sub_index_list = [len(input) for input in inputs]
inputs = reduce(lambda x, y: x.extend(y) or x, inputs)
# step2: run
outputs, bbox_nums = self.infer(inputs)
# step3: merge
curr_offsef_id = 0
pipe_outputs = []
for i, bbox_num in enumerate(bbox_nums):
output = outputs[i]
start_id = 0
for num in bbox_num:
end_id = start_id + num
out = {k: v[start_id:end_id] for k, v in output.items()}
pipe_outputs.append(out)
start_id = end_id
return pipe_outputs |
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/detection/inference.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/detection/inference.py | Apache-2.0 |
def decode_image(im_file, im_info):
"""read rgb image
Args:
im_file (str|np.ndarray): input can be image path or np.ndarray
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
if isinstance(im_file, str):
with open(im_file, 'rb') as f:
im_read = f.read()
data = np.frombuffer(im_read, dtype='uint8')
im = cv2.imdecode(data, 1) # BGR mode, but need RGB mode
im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
else:
im = im_file
im_info['im_shape'] = np.array(im.shape[:2], dtype=np.float32)
im_info['scale_factor'] = np.array([1., 1.], dtype=np.float32)
return im, im_info | read rgb image
Args:
im_file (str|np.ndarray): input can be image path or np.ndarray
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| decode_image | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/detection/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/detection/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
assert len(self.target_size) == 2
assert self.target_size[0] > 0 and self.target_size[1] > 0
im_channel = im.shape[2]
im_scale_y, im_scale_x = self.generate_scale(im)
# set image_shape
im_info['input_shape'][1] = int(im_scale_y * im.shape[0])
im_info['input_shape'][2] = int(im_scale_x * im.shape[1])
im = cv2.resize(
im,
None,
None,
fx=im_scale_x,
fy=im_scale_y,
interpolation=self.interp)
im_info['im_shape'] = np.array(im.shape[:2]).astype('float32')
im_info['scale_factor'] = np.array(
[im_scale_y, im_scale_x]).astype('float32')
return im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/detection/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/detection/preprocess.py | Apache-2.0 |
def generate_scale(self, im):
"""
Args:
im (np.ndarray): image (np.ndarray)
Returns:
im_scale_x: the resize ratio of X
im_scale_y: the resize ratio of Y
"""
origin_shape = im.shape[:2]
im_c = im.shape[2]
if self.keep_ratio:
im_size_min = np.min(origin_shape)
im_size_max = np.max(origin_shape)
target_size_min = np.min(self.target_size)
target_size_max = np.max(self.target_size)
im_scale = float(target_size_min) / float(im_size_min)
if np.round(im_scale * im_size_max) > target_size_max:
im_scale = float(target_size_max) / float(im_size_max)
im_scale_x = im_scale
im_scale_y = im_scale
else:
resize_h, resize_w = self.target_size
im_scale_y = resize_h / float(origin_shape[0])
im_scale_x = resize_w / float(origin_shape[1])
return im_scale_y, im_scale_x |
Args:
im (np.ndarray): image (np.ndarray)
Returns:
im_scale_x: the resize ratio of X
im_scale_y: the resize ratio of Y
| generate_scale | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/detection/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/detection/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
im = im.astype(np.float32, copy=False)
if self.is_scale:
scale = 1.0 / 255.0
im *= scale
if self.norm_type == 'mean_std':
mean = np.array(self.mean)[np.newaxis, np.newaxis, :]
std = np.array(self.std)[np.newaxis, np.newaxis, :]
im -= mean
im /= std
return im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/detection/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/detection/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
im = im.transpose((2, 0, 1)).copy()
return im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/detection/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/detection/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
coarsest_stride = self.coarsest_stride
if coarsest_stride <= 0:
return im, im_info
im_c, im_h, im_w = im.shape
pad_h = int(np.ceil(float(im_h) / coarsest_stride) * coarsest_stride)
pad_w = int(np.ceil(float(im_w) / coarsest_stride) * coarsest_stride)
padding_im = np.zeros((im_c, pad_h, pad_w), dtype=np.float32)
padding_im[:, :im_h, :im_w] = im
return padding_im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/detection/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/detection/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
im = im[:, :, ::-1]
return im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/detection/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/detection/preprocess.py | Apache-2.0 |
def __call__(self, inputs):
"""
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
"""
# for the input_keys as list
# inputs = [pipe_input[key] for pipe_input in pipe_inputs for key in self.input_keys]
# step1: for the input_keys as str
if len(self.input_keys) > 1:
tl_points = [input[self.input_keys[1]] for input in inputs]
tl_points = reduce(lambda x, y: x.extend(y) or x, tl_points)
else:
tl_points = None
key = self.input_keys[0]
if isinstance(inputs[0][key], (list, tuple)):
inputs = [input[key] for input in inputs]
else:
inputs = [[input[key]] for input in inputs]
sub_index_list = [len(input) for input in inputs]
inputs = reduce(lambda x, y: x.extend(y) or x, inputs)
# step2: run
outputs = self.infer(inputs, tl_points)
# step3: merge
curr_offsef_id = 0
pipe_outputs = []
for idx in range(len(sub_index_list)):
sub_start_idx = curr_offsef_id
sub_end_idx = curr_offsef_id + sub_index_list[idx]
output = outputs[sub_start_idx:sub_end_idx]
output = {k: [o[k] for o in output] for k in output[0]}
pipe_outputs.append(output)
curr_offsef_id = sub_end_idx
return pipe_outputs |
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/keypoint/inference.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/keypoint/inference.py | Apache-2.0 |
def warp_affine_joints(joints, mat):
"""Apply affine transformation defined by the transform matrix on the
joints.
Args:
joints (np.ndarray[..., 2]): Origin coordinate of joints.
mat (np.ndarray[3, 2]): The affine matrix.
Returns:
matrix (np.ndarray[..., 2]): Result coordinate of joints.
"""
joints = np.array(joints)
shape = joints.shape
joints = joints.reshape(-1, 2)
return np.dot(np.concatenate(
(joints, joints[:, 0:1] * 0 + 1), axis=1),
mat.T).reshape(shape) | Apply affine transformation defined by the transform matrix on the
joints.
Args:
joints (np.ndarray[..., 2]): Origin coordinate of joints.
mat (np.ndarray[3, 2]): The affine matrix.
Returns:
matrix (np.ndarray[..., 2]): Result coordinate of joints.
| warp_affine_joints | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/keypoint/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/keypoint/postprocess.py | Apache-2.0 |
def get_max_preds(self, heatmaps):
"""get predictions from score maps
Args:
heatmaps: numpy.ndarray([batch_size, num_joints, height, width])
Returns:
preds: numpy.ndarray([batch_size, num_joints, 2]), keypoints coords
maxvals: numpy.ndarray([batch_size, num_joints, 2]), the maximum confidence of the keypoints
"""
assert isinstance(heatmaps,
np.ndarray), 'heatmaps should be numpy.ndarray'
assert heatmaps.ndim == 4, 'batch_images should be 4-ndim'
batch_size = heatmaps.shape[0]
num_joints = heatmaps.shape[1]
width = heatmaps.shape[3]
heatmaps_reshaped = heatmaps.reshape((batch_size, num_joints, -1))
idx = np.argmax(heatmaps_reshaped, 2)
maxvals = np.amax(heatmaps_reshaped, 2)
maxvals = maxvals.reshape((batch_size, num_joints, 1))
idx = idx.reshape((batch_size, num_joints, 1))
preds = np.tile(idx, (1, 1, 2)).astype(np.float32)
preds[:, :, 0] = (preds[:, :, 0]) % width
preds[:, :, 1] = np.floor((preds[:, :, 1]) / width)
pred_mask = np.tile(np.greater(maxvals, 0.0), (1, 1, 2))
pred_mask = pred_mask.astype(np.float32)
preds *= pred_mask
return preds, maxvals | get predictions from score maps
Args:
heatmaps: numpy.ndarray([batch_size, num_joints, height, width])
Returns:
preds: numpy.ndarray([batch_size, num_joints, 2]), keypoints coords
maxvals: numpy.ndarray([batch_size, num_joints, 2]), the maximum confidence of the keypoints
| get_max_preds | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/keypoint/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/keypoint/postprocess.py | Apache-2.0 |
def dark_postprocess(self, hm, coords, kernelsize):
"""
refer to https://github.com/ilovepose/DarkPose/lib/core/inference.py
"""
hm = self.gaussian_blur(hm, kernelsize)
hm = np.maximum(hm, 1e-10)
hm = np.log(hm)
for n in range(coords.shape[0]):
for p in range(coords.shape[1]):
coords[n, p] = self.dark_parse(hm[n][p], coords[n][p])
return coords |
refer to https://github.com/ilovepose/DarkPose/lib/core/inference.py
| dark_postprocess | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/keypoint/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/keypoint/postprocess.py | Apache-2.0 |
def get_final_preds(self, heatmaps, center, scale, kernelsize=3):
"""the highest heatvalue location with a quarter offset in the
direction from the highest response to the second highest response.
Args:
heatmaps (numpy.ndarray): The predicted heatmaps
center (numpy.ndarray): The boxes center
scale (numpy.ndarray): The scale factor
Returns:
preds: numpy.ndarray([batch_size, num_joints, 2]), keypoints coords
maxvals: numpy.ndarray([batch_size, num_joints, 1]), the maximum confidence of the keypoints
"""
coords, maxvals = self.get_max_preds(heatmaps)
heatmap_height = heatmaps.shape[2]
heatmap_width = heatmaps.shape[3]
if self.use_dark:
coords = self.dark_postprocess(heatmaps, coords, kernelsize)
else:
for n in range(coords.shape[0]):
for p in range(coords.shape[1]):
hm = heatmaps[n][p]
px = int(math.floor(coords[n][p][0] + 0.5))
py = int(math.floor(coords[n][p][1] + 0.5))
if 1 < px < heatmap_width - 1 and 1 < py < heatmap_height - 1:
diff = np.array([
hm[py][px + 1] - hm[py][px - 1],
hm[py + 1][px] - hm[py - 1][px]
])
coords[n][p] += np.sign(diff) * .25
preds = coords.copy()
# Transform back
for i in range(coords.shape[0]):
preds[i] = transform_preds(coords[i], center[i], scale[i],
[heatmap_width, heatmap_height])
return preds, maxvals | the highest heatvalue location with a quarter offset in the
direction from the highest response to the second highest response.
Args:
heatmaps (numpy.ndarray): The predicted heatmaps
center (numpy.ndarray): The boxes center
scale (numpy.ndarray): The scale factor
Returns:
preds: numpy.ndarray([batch_size, num_joints, 2]), keypoints coords
maxvals: numpy.ndarray([batch_size, num_joints, 1]), the maximum confidence of the keypoints
| get_final_preds | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/keypoint/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/keypoint/postprocess.py | Apache-2.0 |
def get_affine_transform(center,
input_size,
rot,
output_size,
shift=(0., 0.),
inv=False):
"""Get the affine transform matrix, given the center/scale/rot/output_size.
Args:
center (np.ndarray[2, ]): Center of the bounding box (x, y).
scale (np.ndarray[2, ]): Scale of the bounding box
wrt [width, height].
rot (float): Rotation angle (degree).
output_size (np.ndarray[2, ]): Size of the destination heatmaps.
shift (0-100%): Shift translation ratio wrt the width/height.
Default (0., 0.).
inv (bool): Option to inverse the affine transform direction.
(inv=False: src->dst or inv=True: dst->src)
Returns:
np.ndarray: The transform matrix.
"""
assert len(center) == 2
assert len(output_size) == 2
assert len(shift) == 2
if not isinstance(input_size, (np.ndarray, list)):
input_size = np.array([input_size, input_size], dtype=np.float32)
scale_tmp = input_size
shift = np.array(shift)
src_w = scale_tmp[0]
dst_w = output_size[0]
dst_h = output_size[1]
rot_rad = np.pi * rot / 180
src_dir = rotate_point([0., src_w * -0.5], rot_rad)
dst_dir = np.array([0., dst_w * -0.5])
src = np.zeros((3, 2), dtype=np.float32)
src[0, :] = center + scale_tmp * shift
src[1, :] = center + src_dir + scale_tmp * shift
src[2, :] = _get_3rd_point(src[0, :], src[1, :])
dst = np.zeros((3, 2), dtype=np.float32)
dst[0, :] = [dst_w * 0.5, dst_h * 0.5]
dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5]) + dst_dir
dst[2, :] = _get_3rd_point(dst[0, :], dst[1, :])
if inv:
trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))
else:
trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))
return trans | Get the affine transform matrix, given the center/scale/rot/output_size.
Args:
center (np.ndarray[2, ]): Center of the bounding box (x, y).
scale (np.ndarray[2, ]): Scale of the bounding box
wrt [width, height].
rot (float): Rotation angle (degree).
output_size (np.ndarray[2, ]): Size of the destination heatmaps.
shift (0-100%): Shift translation ratio wrt the width/height.
Default (0., 0.).
inv (bool): Option to inverse the affine transform direction.
(inv=False: src->dst or inv=True: dst->src)
Returns:
np.ndarray: The transform matrix.
| get_affine_transform | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/keypoint/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/keypoint/preprocess.py | Apache-2.0 |
def rotate_point(pt, angle_rad):
"""Rotate a point by an angle.
Args:
pt (list[float]): 2 dimensional point to be rotated
angle_rad (float): rotation angle by radian
Returns:
list[float]: Rotated point.
"""
assert len(pt) == 2
sn, cs = np.sin(angle_rad), np.cos(angle_rad)
new_x = pt[0] * cs - pt[1] * sn
new_y = pt[0] * sn + pt[1] * cs
rotated_pt = [new_x, new_y]
return rotated_pt | Rotate a point by an angle.
Args:
pt (list[float]): 2 dimensional point to be rotated
angle_rad (float): rotation angle by radian
Returns:
list[float]: Rotated point.
| rotate_point | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/keypoint/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/keypoint/preprocess.py | Apache-2.0 |
def _get_3rd_point(a, b):
"""To calculate the affine matrix, three pairs of points are required. This
function is used to get the 3rd point, given 2D points a & b.
The 3rd point is defined by rotating vector `a - b` by 90 degrees
anticlockwise, using b as the rotation center.
Args:
a (np.ndarray): point(x,y)
b (np.ndarray): point(x,y)
Returns:
np.ndarray: The 3rd point.
"""
assert len(a) == 2
assert len(b) == 2
direction = a - b
third_pt = b + np.array([-direction[1], direction[0]], dtype=np.float32)
return third_pt | To calculate the affine matrix, three pairs of points are required. This
function is used to get the 3rd point, given 2D points a & b.
The 3rd point is defined by rotating vector `a - b` by 90 degrees
anticlockwise, using b as the rotation center.
Args:
a (np.ndarray): point(x,y)
b (np.ndarray): point(x,y)
Returns:
np.ndarray: The 3rd point.
| _get_3rd_point | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/keypoint/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/keypoint/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
im = im.astype(np.float32, copy=False)
mean = np.array(self.mean)[np.newaxis, np.newaxis, :]
std = np.array(self.std)[np.newaxis, np.newaxis, :]
if self.is_scale:
im = im / 255.0
im -= mean
im /= std
return im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/keypoint/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/keypoint/preprocess.py | Apache-2.0 |
def __call__(self, im, im_info):
"""
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
"""
im = im.transpose((2, 0, 1)).copy()
return im, im_info |
Args:
im (np.ndarray): image (np.ndarray)
im_info (dict): info of image
Returns:
im (np.ndarray): processed image (np.ndarray)
im_info (dict): info of processed image
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/keypoint/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/keypoint/preprocess.py | Apache-2.0 |
def __call__(self, inputs):
"""
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
"""
key = self.input_keys[0]
is_list = False
if isinstance(inputs[0][key], (list, tuple)):
inputs = [input[key] for input in inputs]
is_list = True
else:
inputs = [[input[key]] for input in inputs]
sub_index_list = [len(input) for input in inputs]
inputs = reduce(lambda x, y: x.extend(y) or x, inputs)
# step2: run
outputs = self.infer(inputs)
# step3: merge
curr_offsef_id = 0
pipe_outputs = []
for idx in range(len(sub_index_list)):
sub_start_idx = curr_offsef_id
sub_end_idx = curr_offsef_id + sub_index_list[idx]
output = outputs[sub_start_idx:sub_end_idx]
output = {k: [o[k] for o in output] for k in output[0]}
if is_list is not True:
output = {k: output[k][0] for k in output}
pipe_outputs.append(output)
curr_offsef_id = sub_end_idx
return pipe_outputs |
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/nlp/inference.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/nlp/inference.py | Apache-2.0 |
def __call__(self, inputs):
"""
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
"""
key = self.input_keys[0]
is_list = False
if isinstance(inputs[0][key], (list, tuple)):
inputs = [input[key] for input in inputs]
is_list = True
else:
inputs = [[input[key]] for input in inputs]
# expand a dim to adjust [[image,iamge],[image,image]] format
expand_dim = False
if isinstance(inputs[0][0], np.ndarray):
inputs = [inputs]
expand_dim = True
pipe_outputs = []
for i, images in enumerate(inputs):
sub_index_list = [len(input) for input in images]
images = reduce(lambda x, y: x.extend(y) or x, images)
# step2: run
outputs = self.infer(images)
# step3: merge
curr_offsef_id = 0
results = []
for idx in range(len(sub_index_list)):
sub_start_idx = curr_offsef_id
sub_end_idx = curr_offsef_id + sub_index_list[idx]
output = outputs[sub_start_idx:sub_end_idx]
if len(output) > 0:
output = {k: [o[k] for o in output] for k in output[0]}
if is_list is not True:
output = {k: output[k][0] for k in output}
else:
output = {self.output_keys[0]: [], self.output_keys[1]: []}
results.append(output)
curr_offsef_id = sub_end_idx
pipe_outputs.append(results)
if expand_dim:
pipe_outputs = pipe_outputs[0]
else:
outputs = []
for pipe_output in pipe_outputs:
d = defaultdict(list)
for item in pipe_output:
for k in self.output_keys:
d[k].append(item[k])
outputs.append(d)
pipe_outputs = outputs
return pipe_outputs |
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_crnn_recognition/inference.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_crnn_recognition/inference.py | Apache-2.0 |
def decode(self, text_index, text_prob=None, is_remove_duplicate=False):
""" convert text-index into text-label. """
result_list = []
ignored_tokens = self.get_ignored_tokens()
batch_size = len(text_index)
for batch_idx in range(batch_size):
selection = np.ones(len(text_index[batch_idx]), dtype=bool)
if is_remove_duplicate:
selection[1:] = text_index[batch_idx][1:] != text_index[
batch_idx][:-1]
for ignored_token in ignored_tokens:
selection &= text_index[batch_idx] != ignored_token
char_list = [
self.character[text_id]
for text_id in text_index[batch_idx][selection]
]
if text_prob is not None:
conf_list = text_prob[batch_idx][selection]
else:
conf_list = [1] * len(selection)
if len(conf_list) == 0:
conf_list = [0]
text = ''.join(char_list)
if self.reverse: # for arabic rec
text = self.pred_reverse(text)
result_list.append((text, np.mean(conf_list).tolist()))
return result_list | convert text-index into text-label. | decode | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_crnn_recognition/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_crnn_recognition/postprocess.py | Apache-2.0 |
def __call__(self, inputs):
"""
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
"""
key = self.input_keys[0]
is_list = False
if isinstance(inputs[0][key], (list, tuple)):
inputs = [input[key] for input in inputs]
is_list = True
else:
inputs = [[input[key]] for input in inputs]
sub_index_list = [len(input) for input in inputs]
inputs = reduce(lambda x, y: x.extend(y) or x, inputs)
# step2: run
outputs = self.infer(inputs)
# step3: merge
curr_offsef_id = 0
pipe_outputs = []
for idx in range(len(sub_index_list)):
sub_start_idx = curr_offsef_id
sub_end_idx = curr_offsef_id + sub_index_list[idx]
output = outputs[sub_start_idx:sub_end_idx]
output = {k: [o[k] for o in output] for k in output[0]}
if is_list is not True:
output = {k: output[k][0] for k in output}
pipe_outputs.append(output)
curr_offsef_id = sub_end_idx
return pipe_outputs |
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_db_detection/inference.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_db_detection/inference.py | Apache-2.0 |
def polygons_from_bitmap(self, pred, _bitmap, dest_width, dest_height):
'''
_bitmap: single map with shape (1, H, W),
whose values are binarized as {0, 1}
'''
bitmap = _bitmap
height, width = bitmap.shape
boxes = []
scores = []
contours, _ = cv2.findContours((bitmap * 255).astype(np.uint8),
cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours[:self.max_candidates]:
epsilon = 0.002 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
points = approx.reshape((-1, 2))
if points.shape[0] < 4:
continue
score = self.box_score_fast(pred, points.reshape(-1, 2))
if self.box_thresh > score:
continue
if points.shape[0] > 2:
box = self.unclip(points, self.unclip_ratio)
if len(box) > 1:
continue
else:
continue
box = box.reshape(-1, 2)
_, sside = self.get_mini_boxes(box.reshape((-1, 1, 2)))
if sside < self.min_size + 2:
continue
box = np.array(box)
box[:, 0] = np.clip(
np.round(box[:, 0] / width * dest_width), 0, dest_width)
box[:, 1] = np.clip(
np.round(box[:, 1] / height * dest_height), 0, dest_height)
boxes.append(box.tolist())
scores.append(score)
return boxes, scores |
_bitmap: single map with shape (1, H, W),
whose values are binarized as {0, 1}
| polygons_from_bitmap | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_db_detection/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_db_detection/postprocess.py | Apache-2.0 |
def boxes_from_bitmap(self, pred, _bitmap, dest_width, dest_height):
'''
_bitmap: single map with shape (1, H, W),
whose values are binarized as {0, 1}
'''
bitmap = _bitmap
height, width = bitmap.shape
outs = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST,
cv2.CHAIN_APPROX_SIMPLE)
if len(outs) == 3:
img, contours, _ = outs[0], outs[1], outs[2]
elif len(outs) == 2:
contours, _ = outs[0], outs[1]
num_contours = min(len(contours), self.max_candidates)
boxes = []
scores = []
for index in range(num_contours):
contour = contours[index]
points, sside = self.get_mini_boxes(contour)
if sside < self.min_size:
continue
points = np.array(points)
if self.score_mode == "fast":
score = self.box_score_fast(pred, points.reshape(-1, 2))
else:
score = self.box_score_slow(pred, contour)
if self.box_thresh > score:
continue
box = self.unclip(points, self.unclip_ratio).reshape(-1, 1, 2)
box, sside = self.get_mini_boxes(box)
if sside < self.min_size + 2:
continue
box = np.array(box)
box[:, 0] = np.clip(
np.round(box[:, 0] / width * dest_width), 0, dest_width)
box[:, 1] = np.clip(
np.round(box[:, 1] / height * dest_height), 0, dest_height)
boxes.append(box.astype(np.int16))
scores.append(score)
return np.array(boxes, dtype=np.int16), scores |
_bitmap: single map with shape (1, H, W),
whose values are binarized as {0, 1}
| boxes_from_bitmap | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_db_detection/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_db_detection/postprocess.py | Apache-2.0 |
def box_score_fast(self, bitmap, _box):
'''
box_score_fast: use bbox mean score as the mean score
'''
h, w = bitmap.shape[:2]
box = _box.copy()
xmin = np.clip(np.floor(box[:, 0].min()).astype("int"), 0, w - 1)
xmax = np.clip(np.ceil(box[:, 0].max()).astype("int"), 0, w - 1)
ymin = np.clip(np.floor(box[:, 1].min()).astype("int"), 0, h - 1)
ymax = np.clip(np.ceil(box[:, 1].max()).astype("int"), 0, h - 1)
mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
box[:, 0] = box[:, 0] - xmin
box[:, 1] = box[:, 1] - ymin
cv2.fillPoly(mask, box.reshape(1, -1, 2).astype(np.int32), 1)
return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0] |
box_score_fast: use bbox mean score as the mean score
| box_score_fast | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_db_detection/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_db_detection/postprocess.py | Apache-2.0 |
def box_score_slow(self, bitmap, contour):
'''
box_score_slow: use polyon mean score as the mean score
'''
h, w = bitmap.shape[:2]
contour = contour.copy()
contour = np.reshape(contour, (-1, 2))
xmin = np.clip(np.min(contour[:, 0]), 0, w - 1)
xmax = np.clip(np.max(contour[:, 0]), 0, w - 1)
ymin = np.clip(np.min(contour[:, 1]), 0, h - 1)
ymax = np.clip(np.max(contour[:, 1]), 0, h - 1)
mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
contour[:, 0] = contour[:, 0] - xmin
contour[:, 1] = contour[:, 1] - ymin
cv2.fillPoly(mask, contour.reshape(1, -1, 2).astype(np.int32), 1)
return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0] |
box_score_slow: use polyon mean score as the mean score
| box_score_slow | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_db_detection/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_db_detection/postprocess.py | Apache-2.0 |
def sorted_boxes(dt_boxes):
"""
Sort text boxes in order from top to bottom, left to right
args:
dt_boxes(array):detected text boxes with shape [4, 2]
return:
sorted boxes(array) with shape [4, 2]
"""
num_boxes = dt_boxes.shape[0]
sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0]))
_boxes = list(sorted_boxes)
for i in range(num_boxes - 1):
for j in range(i, 0, -1):
if abs(_boxes[j + 1][0][1] - _boxes[j][0][1]) < 10 and \
(_boxes[j + 1][0][0] < _boxes[j][0][0]):
tmp = _boxes[j]
_boxes[j] = _boxes[j + 1]
_boxes[j + 1] = tmp
else:
break
return np.array(_boxes) |
Sort text boxes in order from top to bottom, left to right
args:
dt_boxes(array):detected text boxes with shape [4, 2]
return:
sorted boxes(array) with shape [4, 2]
| sorted_boxes | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_db_detection/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_db_detection/postprocess.py | Apache-2.0 |
def resize_image_type0(self, img):
"""
resize image to a size multiple of 32 which is required by the network
args:
img(array): array with shape [h, w, c]
return(tuple):
img, (ratio_h, ratio_w)
"""
limit_side_len = self.limit_side_len
h, w, c = img.shape
# limit the max side
if self.limit_type == 'max':
if max(h, w) > limit_side_len:
if h > w:
ratio = float(limit_side_len) / h
else:
ratio = float(limit_side_len) / w
else:
ratio = 1.
elif self.limit_type == 'min':
if min(h, w) < limit_side_len:
if h < w:
ratio = float(limit_side_len) / h
else:
ratio = float(limit_side_len) / w
else:
ratio = 1.
elif self.limit_type == 'resize_long':
ratio = float(limit_side_len) / max(h, w)
else:
raise Exception('not support limit type, image ')
resize_h = int(h * ratio)
resize_w = int(w * ratio)
resize_h = max(int(round(resize_h / 32) * 32), 32)
resize_w = max(int(round(resize_w / 32) * 32), 32)
try:
if int(resize_w) <= 0 or int(resize_h) <= 0:
return None, (None, None)
img = cv2.resize(img, (int(resize_w), int(resize_h)))
except:
print(img.shape, resize_w, resize_h)
sys.exit(0)
ratio_h = resize_h / float(h)
ratio_w = resize_w / float(w)
return img, [ratio_h, ratio_w] |
resize image to a size multiple of 32 which is required by the network
args:
img(array): array with shape [h, w, c]
return(tuple):
img, (ratio_h, ratio_w)
| resize_image_type0 | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_db_detection/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_db_detection/preprocess.py | Apache-2.0 |
def __call__(self, inputs):
"""
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
"""
# step2: run
outputs, ser_inputs = self.infer(inputs)
# step3: merge
pipe_outputs = []
for output, ser_input in zip(outputs, ser_inputs):
d = defaultdict(list)
for res in output:
d[self.output_keys[0]].append(res['pred_id'])
d[self.output_keys[1]].append(res['pred'])
d[self.output_keys[2]].append(res['points'])
d[self.output_keys[3]].append(res['transcription'])
d[self.output_keys[4]] = ser_input
pipe_outputs.append(d)
return pipe_outputs |
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_kie/inference.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_kie/inference.py | Apache-2.0 |
def __call__(self, inputs):
"""
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
"""
# step2: run
outputs = self.infer(inputs)
# step3: merge
pipe_outputs = []
for output in outputs:
d = defaultdict(list)
for res in output:
d[self.output_keys[0]].append(res[0])
d[self.output_keys[1]].append(res[1])
pipe_outputs.append(d)
return pipe_outputs |
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_kie/inference.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_kie/inference.py | Apache-2.0 |
def filter_empty_contents(self, ocr_info):
"""
find out the empty texts and remove the links
"""
new_ocr_info = []
empty_index = []
for idx, info in enumerate(ocr_info):
if len(info["transcription"]) > 0:
new_ocr_info.append(copy.deepcopy(info))
else:
empty_index.append(info["id"])
for idx, info in enumerate(new_ocr_info):
new_link = []
for link in info["linking"]:
if link[0] in empty_index or link[1] in empty_index:
continue
new_link.append(link)
new_ocr_info[idx]["linking"] = new_link
return new_ocr_info |
find out the empty texts and remove the links
| filter_empty_contents | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_kie/preprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_kie/preprocess.py | Apache-2.0 |
def __call__(self, inputs):
"""
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
"""
key = self.input_keys[0]
is_list = False
if isinstance(inputs[0][key], (list, tuple)):
inputs = [input[key] for input in inputs]
is_list = True
else:
inputs = [[input[key]] for input in inputs]
sub_index_list = [len(input) for input in inputs]
inputs = reduce(lambda x, y: x.extend(y) or x, inputs)
pipe_outputs = []
if len(inputs) == 0:
pipe_outputs.append({
self.output_keys[0]: [],
self.output_keys[1]: [],
self.output_keys[2]: [],
})
return pipe_outputs
# step2: run
outputs = self.infer(inputs)
# step3: merge
curr_offsef_id = 0
for idx in range(len(sub_index_list)):
sub_start_idx = curr_offsef_id
sub_end_idx = curr_offsef_id + sub_index_list[idx]
output = outputs[sub_start_idx:sub_end_idx]
output = {k: [o[k] for o in output] for k in output[0]}
if is_list is not True:
output = {k: output[k][0] for k in output}
pipe_outputs.append(output)
curr_offsef_id = sub_end_idx
return pipe_outputs |
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_table_recognition/inference.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_table_recognition/inference.py | Apache-2.0 |
def decode(self, structure_probs, bbox_preds, shape_list):
"""convert text-label into text-index.
"""
ignored_tokens = self.get_ignored_tokens()
end_idx = self.dict[self.end_str]
structure_idx = structure_probs.argmax(axis=2)
structure_probs = structure_probs.max(axis=2)
structure_batch_list = []
bbox_batch_list = []
batch_size = len(structure_idx)
for batch_idx in range(batch_size):
structure_list = []
bbox_list = []
score_list = []
for idx in range(len(structure_idx[batch_idx])):
char_idx = int(structure_idx[batch_idx][idx])
if idx > 0 and char_idx == end_idx:
break
if char_idx in ignored_tokens:
continue
text = self.character[char_idx]
if text in self.td_token:
bbox = bbox_preds[batch_idx, idx]
bbox = self._bbox_decode(bbox, shape_list[batch_idx])
bbox_list.append(bbox)
structure_list.append(text)
score_list.append(structure_probs[batch_idx, idx])
structure_batch_list.append(
[structure_list, np.mean(score_list).tolist()])
bbox_batch_list.append(np.array(bbox_list).tolist())
result = {
'bbox_batch_list': bbox_batch_list,
'structure_batch_list': structure_batch_list,
}
return result | convert text-label into text-index.
| decode | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_table_recognition/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_table_recognition/postprocess.py | Apache-2.0 |
def decode_label(self, batch):
"""convert text-label into text-index.
"""
structure_idx = batch[1]
gt_bbox_list = batch[2]
shape_list = batch[-1]
ignored_tokens = self.get_ignored_tokens()
end_idx = self.dict[self.end_str]
structure_batch_list = []
bbox_batch_list = []
batch_size = len(structure_idx)
for batch_idx in range(batch_size):
structure_list = []
bbox_list = []
for idx in range(len(structure_idx[batch_idx])):
char_idx = int(structure_idx[batch_idx][idx])
if idx > 0 and char_idx == end_idx:
break
if char_idx in ignored_tokens:
continue
structure_list.append(self.character[char_idx])
bbox = gt_bbox_list[batch_idx][idx]
if bbox.sum() != 0:
bbox = self._bbox_decode(bbox, shape_list[batch_idx])
bbox_list.append(bbox)
structure_batch_list.append(structure_list)
bbox_batch_list.append(bbox_list)
result = {
'bbox_batch_list': bbox_batch_list,
'structure_batch_list': structure_batch_list,
}
return result | convert text-label into text-index.
| decode_label | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/ocr/ocr_table_recognition/postprocess.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_table_recognition/postprocess.py | Apache-2.0 |
def __call__(self, inputs):
"""
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
"""
key = self.input_keys[0]
is_list = False
if isinstance(inputs[0][key], (list, tuple)):
inputs = [input[key] for input in inputs]
is_list = True
else:
inputs = [[input[key]] for input in inputs]
sub_index_list = [len(input) for input in inputs]
inputs = reduce(lambda x, y: x.extend(y) or x, inputs)
# step2: run
outputs = self.infer(inputs)
# step3: merge
curr_offsef_id = 0
pipe_outputs = []
for idx in range(len(sub_index_list)):
sub_start_idx = curr_offsef_id
sub_end_idx = curr_offsef_id + sub_index_list[idx]
output = outputs[sub_start_idx:sub_end_idx]
output = {k: [o[k] for o in output] for k in output[0]}
if is_list is not True:
output = {k: output[k][0] for k in output}
pipe_outputs.append(output)
curr_offsef_id = sub_end_idx
return pipe_outputs |
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/segmentation/inference.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/segmentation/inference.py | Apache-2.0 |
def __call__(self, inputs):
"""
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
"""
# step2: run
outputs = self.infer(inputs)
return outputs |
step1: parser inputs
step2: run
step3: merge results
input: a list of dict
| __call__ | python | PaddlePaddle/models | paddlecv/ppcv/ops/models/speech/inference.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/speech/inference.py | Apache-2.0 |
def get_color_map_list(num_classes):
"""
Args:
num_classes (int): number of class
Returns:
color_map (list): RGB color list
"""
color_map = num_classes * [0, 0, 0]
for i in range(0, num_classes):
j = 0
lab = i
while lab:
color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j))
color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j))
color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j))
j += 1
lab >>= 3
color_map = [color_map[i:i + 3] for i in range(0, len(color_map), 3)]
return color_map |
Args:
num_classes (int): number of class
Returns:
color_map (list): RGB color list
| get_color_map_list | python | PaddlePaddle/models | paddlecv/ppcv/ops/output/detection.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/output/detection.py | Apache-2.0 |
def get_pseudo_color_map(pred, color_map=None):
"""
Get the pseudo color image.
Args:
pred (numpy.ndarray): the origin predicted image.
color_map (list, optional): the palette color map. Default: None,
use paddleseg's default color map.
Returns:
(numpy.ndarray): the pseduo image.
"""
pred_mask = Image.fromarray(pred.astype(np.uint8), mode='P')
if color_map is None:
color_map = get_color_map_list(256)
pred_mask.putpalette(color_map)
return pred_mask |
Get the pseudo color image.
Args:
pred (numpy.ndarray): the origin predicted image.
color_map (list, optional): the palette color map. Default: None,
use paddleseg's default color map.
Returns:
(numpy.ndarray): the pseduo image.
| get_pseudo_color_map | python | PaddlePaddle/models | paddlecv/ppcv/ops/output/segmentation.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/output/segmentation.py | Apache-2.0 |
def get_color_map_list(num_classes, custom_color=None):
"""
Returns the color map for visualizing the segmentation mask,
which can support arbitrary number of classes.
Args:
num_classes (int): Number of classes.
custom_color (list, optional): Save images with a custom color map. Default: None, use paddleseg's default color map.
Returns:
(list). The color map.
"""
num_classes += 1
color_map = num_classes * [0, 0, 0]
for i in range(0, num_classes):
j = 0
lab = i
while lab:
color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j))
color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j))
color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j))
j += 1
lab >>= 3
color_map = color_map[3:]
if custom_color:
color_map[:len(custom_color)] = custom_color
return color_map |
Returns the color map for visualizing the segmentation mask,
which can support arbitrary number of classes.
Args:
num_classes (int): Number of classes.
custom_color (list, optional): Save images with a custom color map. Default: None, use paddleseg's default color map.
Returns:
(list). The color map.
| get_color_map_list | python | PaddlePaddle/models | paddlecv/ppcv/ops/output/segmentation.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/output/segmentation.py | Apache-2.0 |
def is_url(path):
"""
Whether path is URL.
Args:
path (string): URL string or not.
"""
return path.startswith('http://') \
or path.startswith('https://') \
or path.startswith('paddlecv://') |
Whether path is URL.
Args:
path (string): URL string or not.
| is_url | python | PaddlePaddle/models | paddlecv/ppcv/utils/download.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/utils/download.py | Apache-2.0 |
def get_model_path(path):
"""Get model path from WEIGHTS_HOME, if not exists,
download it from url.
"""
if not is_url(path):
return path
url = parse_url(path)
path, _ = get_path(url, WEIGHTS_HOME, path_depth=2)
logger.info("The model path is {}".format(path))
return path | Get model path from WEIGHTS_HOME, if not exists,
download it from url.
| get_model_path | python | PaddlePaddle/models | paddlecv/ppcv/utils/download.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/utils/download.py | Apache-2.0 |
def get_config_path(path):
"""Get config path from CONFIGS_HOME, if not exists,
download it from url.
"""
if not is_url(path):
return path
url = parse_url(path)
path, _ = get_path(url, CONFIGS_HOME)
logger.info("The config path is {}".format(path))
return path | Get config path from CONFIGS_HOME, if not exists,
download it from url.
| get_config_path | python | PaddlePaddle/models | paddlecv/ppcv/utils/download.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/utils/download.py | Apache-2.0 |
def get_dict_path(path):
"""Get dict path from DICTS_HOME, if not exists,
download it from url.
"""
if not is_url(path):
return path
url = parse_url(path)
path, _ = get_path(url, DICTS_HOME)
logger.info("The dict path is {}".format(path))
return path | Get dict path from DICTS_HOME, if not exists,
download it from url.
| get_dict_path | python | PaddlePaddle/models | paddlecv/ppcv/utils/download.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/utils/download.py | Apache-2.0 |
def get_font_path(path):
"""Get config path from CONFIGS_HOME, if not exists,
download it from url.
"""
if not is_url(path):
return path
url = parse_url(path)
path, _ = get_path(url, FONTS_HOME)
return path | Get config path from CONFIGS_HOME, if not exists,
download it from url.
| get_font_path | python | PaddlePaddle/models | paddlecv/ppcv/utils/download.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/utils/download.py | Apache-2.0 |
def get_path(url, root_dir, md5sum=None, check_exist=True, path_depth=1):
""" Download from given url to root_dir.
if file or directory specified by url is exists under
root_dir, return the path directly, otherwise download
from url, return the path.
url (str): download url
root_dir (str): root dir for downloading, it should be
WEIGHTS_HOME
md5sum (str): md5 sum of download package
"""
# parse path after download to decompress under root_dir
fullpath, dirname = map_path(url, root_dir, path_depth)
if osp.exists(fullpath) and check_exist:
if not osp.isfile(fullpath) or \
_check_exist_file_md5(fullpath, md5sum, url):
logger.debug("Found {}".format(fullpath))
return fullpath, True
else:
os.remove(fullpath)
fullname = _download(url, dirname, md5sum)
return fullpath, False | Download from given url to root_dir.
if file or directory specified by url is exists under
root_dir, return the path directly, otherwise download
from url, return the path.
url (str): download url
root_dir (str): root dir for downloading, it should be
WEIGHTS_HOME
md5sum (str): md5 sum of download package
| get_path | python | PaddlePaddle/models | paddlecv/ppcv/utils/download.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/utils/download.py | Apache-2.0 |
def _download(url, path, md5sum=None):
"""
Download from url, save to path.
url (str): download url
path (str): download to given path
"""
if not osp.exists(path):
os.makedirs(path)
fname = osp.split(url)[-1]
fullname = osp.join(path, fname)
retry_cnt = 0
while not (osp.exists(fullname) and _check_exist_file_md5(fullname, md5sum,
url)):
if retry_cnt < DOWNLOAD_RETRY_LIMIT:
retry_cnt += 1
else:
raise RuntimeError("Download from {} failed. "
"Retry limit reached".format(url))
logger.info("Downloading {} from {}".format(fname, url))
# NOTE: windows path join may incur \, which is invalid in url
if sys.platform == "win32":
url = url.replace('\\', '/')
req = requests.get(url, stream=True)
if req.status_code != 200:
raise RuntimeError("Downloading from {} failed with code "
"{}!".format(url, req.status_code))
# For protecting download interupted, download to
# tmp_fullname firstly, move tmp_fullname to fullname
# after download finished
tmp_fullname = fullname + "_tmp"
total_size = req.headers.get('content-length')
with open(tmp_fullname, 'wb') as f:
if total_size:
for chunk in tqdm.tqdm(
req.iter_content(chunk_size=1024),
total=(int(total_size) + 1023) // 1024,
unit='KB'):
f.write(chunk)
else:
for chunk in req.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
shutil.move(tmp_fullname, fullname)
return fullname |
Download from url, save to path.
url (str): download url
path (str): download to given path
| _download | python | PaddlePaddle/models | paddlecv/ppcv/utils/download.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/utils/download.py | Apache-2.0 |
def setup_logger(name="ppcv", output=None):
"""
Initialize logger and set its verbosity level to INFO.
Args:
name (str): the root module name of this logger
output (str): a file name or a directory to save log. If None, will not save log file.
If ends with ".txt" or ".log", assumed to be a file name.
Otherwise, logs will be saved to `output/log.txt`.
Returns:
logging.Logger: a logger
"""
logger = logging.getLogger(name)
if name in logger_initialized:
return logger
logger.setLevel(logging.INFO)
logger.propagate = False
formatter = logging.Formatter(
"[%(asctime)s] %(name)s %(levelname)s: %(message)s",
datefmt="%m/%d %H:%M:%S")
# stdout logging: master only
local_rank = dist.get_rank()
if local_rank == 0:
ch = logging.StreamHandler(stream=sys.stdout)
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)
# file logging: all workers
if output is not None:
if output.endswith(".txt") or output.endswith(".log"):
filename = output
else:
filename = os.path.join(output, "log.txt")
if local_rank > 0:
filename = filename + ".rank{}".format(local_rank)
os.makedirs(os.path.dirname(filename))
fh = logging.FileHandler(filename, mode='a')
fh.setLevel(logging.DEBUG)
fh.setFormatter(logging.Formatter())
logger.addHandler(fh)
logger_initialized.append(name)
return logger |
Initialize logger and set its verbosity level to INFO.
Args:
name (str): the root module name of this logger
output (str): a file name or a directory to save log. If None, will not save log file.
If ends with ".txt" or ".log", assumed to be a file name.
Otherwise, logs will be saved to `output/log.txt`.
Returns:
logging.Logger: a logger
| setup_logger | python | PaddlePaddle/models | paddlecv/ppcv/utils/logger.py | https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/utils/logger.py | Apache-2.0 |
def accuracy_paddle(output, target, topk=(1, )):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with paddle.no_grad():
maxk = max(topk)
batch_size = target.shape[0]
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.equal(target)
res = []
for k in topk:
correct_k = correct.astype(paddle.int32)[:k].flatten().sum(
dtype='float32')
res.append(correct_k * (100.0 / batch_size))
return res | Computes the accuracy over the k top predictions for the specified values of k | accuracy_paddle | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/metric.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/metric.py | Apache-2.0 |
def synchronize_between_processes(self):
"""
Warning: does not synchronize the deque!
"""
t = paddle.to_tensor([self.count, self.total], dtype='float64')
t = t.numpy().tolist()
self.count = int(t[0])
self.total = t[1] |
Warning: does not synchronize the deque!
| synchronize_between_processes | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/utils.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/utils.py | Apache-2.0 |
def accuracy(output, target, topk=(1, )):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with paddle.no_grad():
maxk = max(topk)
batch_size = target.shape[0]
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.equal(target)
res = []
for k in topk:
correct_k = correct.astype(paddle.int32)[:k].flatten().sum(
dtype='float32')
res.append(correct_k / batch_size)
return res | Computes the accuracy over the k top predictions for the specified values of k | accuracy | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/utils.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/utils.py | Apache-2.0 |
def has_file_allowed_extension(filename: str,
extensions: Tuple[str, ...]) -> bool:
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
extensions (tuple of strings): extensions to consider (lowercase)
Returns:
bool: True if the filename ends with one of given extensions
"""
return filename.lower().endswith(extensions) | Checks if a file is an allowed extension.
Args:
filename (string): path to a file
extensions (tuple of strings): extensions to consider (lowercase)
Returns:
bool: True if the filename ends with one of given extensions
| has_file_allowed_extension | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py | Apache-2.0 |
def find_classes(directory: str) -> Tuple[List[str], Dict[str, int]]:
"""Finds the class folders in a dataset.
See :class:`DatasetFolder` for details.
"""
classes = sorted(
entry.name for entry in os.scandir(directory) if entry.is_dir())
if not classes:
raise FileNotFoundError(
f"Couldn't find any class folder in {directory}.")
class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}
return classes, class_to_idx | Finds the class folders in a dataset.
See :class:`DatasetFolder` for details.
| find_classes | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py | Apache-2.0 |
def make_dataset(
directory: str,
class_to_idx: Optional[Dict[str, int]]=None,
extensions: Optional[Tuple[str, ...]]=None,
is_valid_file: Optional[Callable[[str], bool]]=None, ) -> List[Tuple[
str, int]]:
"""Generates a list of samples of a form (path_to_sample, class).
See :class:`DatasetFolder` for details.
Note: The class_to_idx parameter is here optional and will use the logic of the ``find_classes`` function
by default.
"""
directory = os.path.expanduser(directory)
if class_to_idx is None:
_, class_to_idx = find_classes(directory)
elif not class_to_idx:
raise ValueError(
"'class_to_index' must have at least one entry to collect any samples."
)
both_none = extensions is None and is_valid_file is None
both_something = extensions is not None and is_valid_file is not None
if both_none or both_something:
raise ValueError(
"Both extensions and is_valid_file cannot be None or not None at the same time"
)
if extensions is not None:
def is_valid_file(x: str) -> bool:
return has_file_allowed_extension(
x, cast(Tuple[str, ...], extensions))
is_valid_file = cast(Callable[[str], bool], is_valid_file)
instances = []
available_classes = set()
for target_class in sorted(class_to_idx.keys()):
class_index = class_to_idx[target_class]
target_dir = os.path.join(directory, target_class)
if not os.path.isdir(target_dir):
continue
for root, _, fnames in sorted(os.walk(target_dir, followlinks=True)):
for fname in sorted(fnames):
if is_valid_file(fname):
path = os.path.join(root, fname)
item = path, class_index
instances.append(item)
if target_class not in available_classes:
available_classes.add(target_class)
# print(fname)
# exit()
# empty_classes = set(class_to_idx.keys()) - available_classes
# if empty_classes:
# msg = f"Found no valid file for the classes {', '.join(sorted(empty_classes))}. "
# if extensions is not None:
# msg += f"Supported extensions are: {', '.join(extensions)}"
# raise FileNotFoundError(msg)
return instances | Generates a list of samples of a form (path_to_sample, class).
See :class:`DatasetFolder` for details.
Note: The class_to_idx parameter is here optional and will use the logic of the ``find_classes`` function
by default.
| make_dataset | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py | Apache-2.0 |
def make_dataset(
directory: str,
class_to_idx: Dict[str, int],
extensions: Optional[Tuple[str, ...]]=None,
is_valid_file: Optional[Callable[[str], bool]]=None, ) -> List[
Tuple[str, int]]:
"""Generates a list of samples of a form (path_to_sample, class).
This can be overridden to e.g. read files from a compressed zip file instead of from the disk.
Args:
directory (str): root dataset directory, corresponding to ``self.root``.
class_to_idx (Dict[str, int]): Dictionary mapping class name to class index.
extensions (optional): A list of allowed extensions.
Either extensions or is_valid_file should be passed. Defaults to None.
is_valid_file (optional): A function that takes path of a file
and checks if the file is a valid file
(used to check of corrupt files) both extensions and
is_valid_file should not be passed. Defaults to None.
Raises:
ValueError: In case ``class_to_idx`` is empty.
ValueError: In case ``extensions`` and ``is_valid_file`` are None or both are not None.
FileNotFoundError: In case no valid file was found for any class.
Returns:
List[Tuple[str, int]]: samples of a form (path_to_sample, class)
"""
if class_to_idx is None:
# prevent potential bug since make_dataset() would use the class_to_idx logic of the
# find_classes() function, instead of using that of the find_classes() method, which
# is potentially overridden and thus could have a different logic.
raise ValueError("The class_to_idx parameter cannot be None.")
return make_dataset(
directory,
class_to_idx,
extensions=extensions,
is_valid_file=is_valid_file) | Generates a list of samples of a form (path_to_sample, class).
This can be overridden to e.g. read files from a compressed zip file instead of from the disk.
Args:
directory (str): root dataset directory, corresponding to ``self.root``.
class_to_idx (Dict[str, int]): Dictionary mapping class name to class index.
extensions (optional): A list of allowed extensions.
Either extensions or is_valid_file should be passed. Defaults to None.
is_valid_file (optional): A function that takes path of a file
and checks if the file is a valid file
(used to check of corrupt files) both extensions and
is_valid_file should not be passed. Defaults to None.
Raises:
ValueError: In case ``class_to_idx`` is empty.
ValueError: In case ``extensions`` and ``is_valid_file`` are None or both are not None.
FileNotFoundError: In case no valid file was found for any class.
Returns:
List[Tuple[str, int]]: samples of a form (path_to_sample, class)
| make_dataset | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py | Apache-2.0 |
def __getitem__(self, index: int) -> Tuple[Any, Any]:
"""
Args:
index (int): Index
Returns:
tuple: (sample, target) where target is class_index of the target class.
"""
path, target = self.samples[index]
sample = self.loader(path)
if self.transform is not None:
sample = self.transform(sample)
if self.target_transform is not None:
target = self.target_transform(target)
return sample, target |
Args:
index (int): Index
Returns:
tuple: (sample, target) where target is class_index of the target class.
| __getitem__ | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py | Apache-2.0 |
def _make_divisible(v: float, divisor: int,
min_value: Optional[int]=None) -> int:
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
"""
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v |
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
| _make_divisible | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py | Apache-2.0 |
def __init__(
self,
inverted_residual_setting: List[InvertedResidualConfig],
last_channel: int,
num_classes: int=1000,
block: Optional[Callable[..., nn.Layer]]=None,
norm_layer: Optional[Callable[..., nn.Layer]]=None,
dropout: float=0.2,
**kwargs: Any, ) -> None:
"""
MobileNet V3 main class
Args:
inverted_residual_setting (List[InvertedResidualConfig]): Network structure
last_channel (int): The number of channels on the penultimate layer
num_classes (int): Number of classes
block (Optional[Callable[..., nn.Layer]]): Module specifying inverted residual building block for mobilenet
norm_layer (Optional[Callable[..., nn.Layer]]): Module specifying the normalization layer to use
dropout (float): The droupout probability
"""
super().__init__()
if not inverted_residual_setting:
raise ValueError(
"The inverted_residual_setting should not be empty")
elif not (isinstance(inverted_residual_setting, Sequence) and all([
isinstance(s, InvertedResidualConfig)
for s in inverted_residual_setting
])):
raise TypeError(
"The inverted_residual_setting should be List[InvertedResidualConfig]"
)
if block is None:
block = InvertedResidual
if norm_layer is None:
norm_layer = partial(nn.BatchNorm2D, epsilon=0.001, momentum=0.01)
layers: List[nn.Layer] = []
# building first layer
firstconv_output_channels = inverted_residual_setting[0].input_channels
layers.append(
ConvNormActivation(
3,
firstconv_output_channels,
kernel_size=3,
stride=2,
norm_layer=norm_layer,
activation_layer=nn.Hardswish, ))
# building inverted residual blocks
for cnf in inverted_residual_setting:
layers.append(block(cnf, norm_layer))
# building last several layers
lastconv_input_channels = inverted_residual_setting[-1].out_channels
lastconv_output_channels = 6 * lastconv_input_channels
layers.append(
ConvNormActivation(
lastconv_input_channels,
lastconv_output_channels,
kernel_size=1,
norm_layer=norm_layer,
activation_layer=nn.Hardswish, ))
self.features = nn.Sequential(*layers)
self.avgpool = nn.AdaptiveAvgPool2D(1)
self.classifier = nn.Sequential(
nn.Linear(lastconv_output_channels, last_channel),
nn.Hardswish(),
nn.Dropout(p=dropout),
nn.Linear(last_channel, num_classes), ) |
MobileNet V3 main class
Args:
inverted_residual_setting (List[InvertedResidualConfig]): Network structure
last_channel (int): The number of channels on the penultimate layer
num_classes (int): Number of classes
block (Optional[Callable[..., nn.Layer]]): Module specifying inverted residual building block for mobilenet
norm_layer (Optional[Callable[..., nn.Layer]]): Module specifying the normalization layer to use
dropout (float): The droupout probability
| __init__ | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py | Apache-2.0 |
def mobilenet_v3_large(pretrained: bool=False,
progress: bool=True,
**kwargs: Any) -> MobileNetV3:
"""
Constructs a large MobileNetV3 architecture from
`"Searching for MobileNetV3" <https://arxiv.org/abs/1905.02244>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
arch = "mobilenet_v3_large"
inverted_residual_setting, last_channel = _mobilenet_v3_conf(arch,
**kwargs)
return _mobilenet_v3(arch, inverted_residual_setting, last_channel,
pretrained, progress, **kwargs) |
Constructs a large MobileNetV3 architecture from
`"Searching for MobileNetV3" <https://arxiv.org/abs/1905.02244>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
| mobilenet_v3_large | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py | Apache-2.0 |
def mobilenet_v3_small(pretrained: bool=False,
progress: bool=True,
**kwargs: Any) -> MobileNetV3:
"""
Constructs a small MobileNetV3 architecture from
`"Searching for MobileNetV3" <https://arxiv.org/abs/1905.02244>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
"""
arch = "mobilenet_v3_small"
inverted_residual_setting, last_channel = _mobilenet_v3_conf(arch,
**kwargs)
return _mobilenet_v3(arch, inverted_residual_setting, last_channel,
pretrained, progress, **kwargs) |
Constructs a small MobileNetV3 architecture from
`"Searching for MobileNetV3" <https://arxiv.org/abs/1905.02244>`_.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
| mobilenet_v3_small | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py | Apache-2.0 |
def get_params(transform_num: int) -> Tuple[int, Tensor, Tensor]:
"""Get parameters for autoaugment transformation
Returns:
params required by the autoaugment transformation
"""
policy_id = int(paddle.randint(low=0, high=transform_num, shape=(1, )))
probs = paddle.rand((2, ))
signs = paddle.randint(low=0, high=2, shape=(2, ))
return policy_id, probs, signs | Get parameters for autoaugment transformation
Returns:
params required by the autoaugment transformation
| get_params | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/autoaugment.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/autoaugment.py | Apache-2.0 |
def forward(self, img: Tensor):
"""
img (PIL Image or Tensor): Image to be transformed.
Returns:
PIL Image or Tensor: AutoAugmented image.
"""
fill = self.fill
if isinstance(img, Tensor):
if isinstance(fill, (int, float)):
fill = [float(fill)] * F._get_image_num_channels(img)
elif fill is not None:
fill = [float(f) for f in fill]
transform_id, probs, signs = self.get_params(len(self.transforms))
for i, (op_name, p,
magnitude_id) in enumerate(self.transforms[transform_id]):
if probs[i] <= p:
magnitudes, signed = self._get_op_meta(op_name)
magnitude = float(magnitudes[magnitude_id].item()) \
if magnitudes is not None and magnitude_id is not None else 0.0
if signed is not None and signed and signs[i] == 0:
magnitude *= -1.0
if op_name == "ShearX":
img = F.affine(
img,
angle=0.0,
translate=[0, 0],
scale=1.0,
shear=[math.degrees(magnitude), 0.0],
interpolation=self.interpolation,
fill=fill)
elif op_name == "ShearY":
img = F.affine(
img,
angle=0.0,
translate=[0, 0],
scale=1.0,
shear=[0.0, math.degrees(magnitude)],
interpolation=self.interpolation,
fill=fill)
elif op_name == "TranslateX":
img = F.affine(
img,
angle=0.0,
translate=[
int(F._get_image_size(img)[0] * magnitude), 0
],
scale=1.0,
interpolation=self.interpolation,
shear=[0.0, 0.0],
fill=fill)
elif op_name == "TranslateY":
img = F.affine(
img,
angle=0.0,
translate=[
0, int(F._get_image_size(img)[1] * magnitude)
],
scale=1.0,
interpolation=self.interpolation,
shear=[0.0, 0.0],
fill=fill)
elif op_name == "Rotate":
img = F.rotate(
img,
magnitude,
interpolation=self.interpolation,
fill=fill)
elif op_name == "Brightness":
img = F.adjust_brightness(img, 1.0 + magnitude)
elif op_name == "Color":
img = F.adjust_saturation(img, 1.0 + magnitude)
elif op_name == "Contrast":
img = F.adjust_contrast(img, 1.0 + magnitude)
elif op_name == "Sharpness":
img = F.adjust_sharpness(img, 1.0 + magnitude)
elif op_name == "Posterize":
img = F.posterize(img, int(magnitude))
elif op_name == "Solarize":
img = F.solarize(img, magnitude)
elif op_name == "AutoContrast":
img = F.autocontrast(img)
elif op_name == "Equalize":
img = F.equalize(img)
elif op_name == "Invert":
img = F.invert(img)
else:
raise ValueError(
"The provided operator {} is not recognized.".format(
op_name))
return img |
img (PIL Image or Tensor): Image to be transformed.
Returns:
PIL Image or Tensor: AutoAugmented image.
| forward | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/autoaugment.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/autoaugment.py | Apache-2.0 |
def to_tensor(pic):
"""Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.
See :class:`~paddlevision.transforms.ToTensor` for more details.
Args:
pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
Returns:
Tensor: Converted image.
"""
if not (F_pil._is_pil_image(pic) or _is_numpy(pic)):
raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(
type(pic)))
if _is_numpy(pic) and not _is_numpy_image(pic):
raise ValueError('pic should be 2/3 dimensional. Got {} dimensions.'.
format(pic.ndim))
default_float_dtype = paddle.get_default_dtype()
if isinstance(pic, np.ndarray):
# handle numpy array
if pic.ndim == 2:
pic = pic[:, :, None]
img = paddle.to_tensor(pic.transpose((2, 0, 1)))
# backward compatibility
if not img.dtype == default_float_dtype:
img = img.astype(dtype=default_float_dtype)
return img.divide(paddle.full_like(img, 255))
else:
return img
if accimage is not None and isinstance(pic, accimage.Image):
nppic = np.zeros(
[pic.channels, pic.height, pic.width], dtype=np.float32)
pic.copyto(nppic)
return paddle.to_tensor(nppic).astype(dtype=default_float_dtype)
# handle PIL Image
mode_to_nptype = {'I': np.int32, 'I;16': np.int16, 'F': np.float32}
img = paddle.to_tensor(
np.array(
pic, mode_to_nptype.get(pic.mode, np.uint8), copy=True))
if pic.mode == '1':
img = 255 * img
img = img.reshape([pic.size[1], pic.size[0], len(pic.getbands())])
if not img.dtype == default_float_dtype:
img = img.astype(dtype=default_float_dtype)
# put it from HWC to CHW format
img = img.transpose((2, 0, 1))
return img.divide(paddle.full_like(img, 255))
else:
# put it from HWC to CHW format
img = img.transpose((2, 0, 1))
return img | Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.
See :class:`~paddlevision.transforms.ToTensor` for more details.
Args:
pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
Returns:
Tensor: Converted image.
| to_tensor | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py | Apache-2.0 |
def normalize(tensor: Tensor,
mean: List[float],
std: List[float],
inplace: bool=False) -> Tensor:
"""Normalize a float tensor image with mean and standard deviation.
This transform does not support PIL Image.
.. note::
This transform acts out of place by default, i.e., it does not mutates the input tensor.
See :class:`~paddlevision.transforms.Normalize` for more details.
Args:
tensor (Tensor): Float tensor image of size (C, H, W) or (B, C, H, W) to be normalized.
mean (sequence): Sequence of means for each channel.
std (sequence): Sequence of standard deviations for each channel.
inplace(bool,optional): Bool to make this operation inplace.
Returns:
Tensor: Normalized Tensor image.
"""
if not isinstance(tensor, paddle.Tensor):
raise TypeError('Input tensor should be a paddle tensor. Got {}.'.
format(type(tensor)))
if not tensor.dtype in (paddle.float16, paddle.float32, paddle.float64):
raise TypeError('Input tensor should be a float tensor. Got {}.'.
format(tensor.dtype))
if tensor.ndim < 3:
raise ValueError(
'Expected tensor to be a tensor image of size (..., C, H, W). Got tensor.shape() = '
'{}.'.format(tensor.shape))
if not inplace:
tensor = tensor.clone()
dtype = tensor.dtype
mean = paddle.to_tensor(mean, dtype=dtype, place=tensor.place)
std = paddle.to_tensor(std, dtype=dtype, place=tensor.place)
if (std == 0).any():
raise ValueError('std evaluated to zero, leading to division by zero.')
if mean.ndim == 1:
mean = mean.reshape((-1, 1, 1))
if std.ndim == 1:
std = std.reshape((-1, 1, 1))
tensor = tensor.subtract(mean).divide(std)
return tensor | Normalize a float tensor image with mean and standard deviation.
This transform does not support PIL Image.
.. note::
This transform acts out of place by default, i.e., it does not mutates the input tensor.
See :class:`~paddlevision.transforms.Normalize` for more details.
Args:
tensor (Tensor): Float tensor image of size (C, H, W) or (B, C, H, W) to be normalized.
mean (sequence): Sequence of means for each channel.
std (sequence): Sequence of standard deviations for each channel.
inplace(bool,optional): Bool to make this operation inplace.
Returns:
Tensor: Normalized Tensor image.
| normalize | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py | Apache-2.0 |
def resize(img: Tensor,
size: List[int],
interpolation: InterpolationMode=InterpolationMode.BILINEAR,
max_size: Optional[int]=None,
antialias: Optional[bool]=None) -> Tensor:
r"""Resize the input image to the given size.
If the image is paddle Tensor, it is expected
to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
.. warning::
The output image might be different depending on its type: when downsampling, the interpolation of PIL images
and tensors is slightly different, because PIL applies antialiasing. This may lead to significant differences
in the performance of a network. Therefore, it is preferable to train and serve a model with the same input
types. See also below the ``antialias`` parameter, which can help making the output of PIL images and tensors
closer.
Args:
img (PIL Image or Tensor): Image to be resized.
size (sequence or int): Desired output size. If size is a sequence like
(h, w), the output size will be matched to this. If size is an int,
the smaller edge of the image will be matched to this number maintaining
the aspect ratio. i.e, if height > width, then image will be rescaled to
:math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)`.
interpolation (InterpolationMode): Desired interpolation enum defined by
:class:`paddlevision.transforms.InterpolationMode`.
Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``,
``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
For backward compatibility integer values (e.g. ``PIL.Image.NEAREST``) are still acceptable.
max_size (int, optional): The maximum allowed for the longer edge of
the resized image: if the longer edge of the image is greater
than ``max_size`` after being resized according to ``size``, then
the image is resized again so that the longer edge is equal to
``max_size``. As a result, ``size`` might be overruled, i.e the
smaller edge may be shorter than ``size``.
antialias (bool, optional): antialias flag. If ``img`` is PIL Image, the flag is ignored and anti-alias
is always used. If ``img`` is Tensor, the flag is False by default and can be set to True for
``InterpolationMode.BILINEAR`` only mode. This can help making the output for PIL images and tensors
closer.
.. warning::
There is no autodiff support for ``antialias=True`` option with input ``img`` as Tensor.
Returns:
PIL Image or Tensor: Resized image.
"""
# Backward compatibility with integer value
if isinstance(interpolation, int):
warnings.warn(
"Argument interpolation should be of type InterpolationMode instead of int. "
"Please, use InterpolationMode enum.")
interpolation = _interpolation_modes_from_int(interpolation)
if not isinstance(interpolation, InterpolationMode):
raise TypeError("Argument interpolation should be a InterpolationMode")
if not isinstance(img, paddle.Tensor):
if antialias is not None and not antialias:
warnings.warn(
"Anti-alias option is always applied for PIL Image input. Argument antialias is ignored."
)
pil_interpolation = pil_modes_mapping[interpolation]
return F_pil.resize(
img, size=size, interpolation=pil_interpolation, max_size=max_size)
return F_t.resize(
img,
size=size,
interpolation=interpolation.value,
max_size=max_size,
antialias=antialias) | Resize the input image to the given size.
If the image is paddle Tensor, it is expected
to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
.. warning::
The output image might be different depending on its type: when downsampling, the interpolation of PIL images
and tensors is slightly different, because PIL applies antialiasing. This may lead to significant differences
in the performance of a network. Therefore, it is preferable to train and serve a model with the same input
types. See also below the ``antialias`` parameter, which can help making the output of PIL images and tensors
closer.
Args:
img (PIL Image or Tensor): Image to be resized.
size (sequence or int): Desired output size. If size is a sequence like
(h, w), the output size will be matched to this. If size is an int,
the smaller edge of the image will be matched to this number maintaining
the aspect ratio. i.e, if height > width, then image will be rescaled to
:math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)`.
interpolation (InterpolationMode): Desired interpolation enum defined by
:class:`paddlevision.transforms.InterpolationMode`.
Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``,
``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
For backward compatibility integer values (e.g. ``PIL.Image.NEAREST``) are still acceptable.
max_size (int, optional): The maximum allowed for the longer edge of
the resized image: if the longer edge of the image is greater
than ``max_size`` after being resized according to ``size``, then
the image is resized again so that the longer edge is equal to
``max_size``. As a result, ``size`` might be overruled, i.e the
smaller edge may be shorter than ``size``.
antialias (bool, optional): antialias flag. If ``img`` is PIL Image, the flag is ignored and anti-alias
is always used. If ``img`` is Tensor, the flag is False by default and can be set to True for
``InterpolationMode.BILINEAR`` only mode. This can help making the output for PIL images and tensors
closer.
.. warning::
There is no autodiff support for ``antialias=True`` option with input ``img`` as Tensor.
Returns:
PIL Image or Tensor: Resized image.
| resize | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py | Apache-2.0 |
def pad(img: Tensor,
padding: List[int],
fill: int=0,
padding_mode: str="constant") -> Tensor:
r"""Pad the given image on all sides with the given "pad" value.
If the image is paddle Tensor, it is expected
to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric,
at most 3 leading dimensions for mode edge,
and an arbitrary number of leading dimensions for mode constant
Args:
img (PIL Image or Tensor): Image to be padded.
padding (int or sequence): Padding on each border. If a single int is provided this
is used to pad all borders. If sequence of length 2 is provided this is the padding
on left/right and top/bottom respectively. If a sequence of length 4 is provided
this is the padding for the left, top, right and bottom borders respectively.
fill (number or str or tuple): Pixel fill value for constant fill. Default is 0.
If a tuple of length 3, it is used to fill R, G, B channels respectively.
This value is only used when the padding_mode is constant.
Only number is supported for paddle Tensor.
Only int or str or tuple value is supported for PIL Image.
padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric.
Default is constant.
- constant: pads with a constant value, this value is specified with fill
- edge: pads with the last value at the edge of the image.
If input a 5D paddle Tensor, the last 3 dimensions will be padded instead of the last 2
- reflect: pads with reflection of image without repeating the last value on the edge.
For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
will result in [3, 2, 1, 2, 3, 4, 3, 2]
- symmetric: pads with reflection of image repeating the last value on the edge.
For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
will result in [2, 1, 1, 2, 3, 4, 4, 3]
Returns:
PIL Image or Tensor: Padded image.
"""
if not isinstance(img, paddle.Tensor):
return F_pil.pad(img,
padding=padding,
fill=fill,
padding_mode=padding_mode)
return F_t.pad(img, padding=padding, fill=fill, padding_mode=padding_mode) | Pad the given image on all sides with the given "pad" value.
If the image is paddle Tensor, it is expected
to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric,
at most 3 leading dimensions for mode edge,
and an arbitrary number of leading dimensions for mode constant
Args:
img (PIL Image or Tensor): Image to be padded.
padding (int or sequence): Padding on each border. If a single int is provided this
is used to pad all borders. If sequence of length 2 is provided this is the padding
on left/right and top/bottom respectively. If a sequence of length 4 is provided
this is the padding for the left, top, right and bottom borders respectively.
fill (number or str or tuple): Pixel fill value for constant fill. Default is 0.
If a tuple of length 3, it is used to fill R, G, B channels respectively.
This value is only used when the padding_mode is constant.
Only number is supported for paddle Tensor.
Only int or str or tuple value is supported for PIL Image.
padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric.
Default is constant.
- constant: pads with a constant value, this value is specified with fill
- edge: pads with the last value at the edge of the image.
If input a 5D paddle Tensor, the last 3 dimensions will be padded instead of the last 2
- reflect: pads with reflection of image without repeating the last value on the edge.
For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
will result in [3, 2, 1, 2, 3, 4, 3, 2]
- symmetric: pads with reflection of image repeating the last value on the edge.
For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
will result in [2, 1, 1, 2, 3, 4, 4, 3]
Returns:
PIL Image or Tensor: Padded image.
| pad | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py | Apache-2.0 |
def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor:
"""Crop the given image at specified location and output size.
If the image is paddle Tensor, it is expected
to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
If image size is smaller than output size along any edge, image is padded with 0 and then cropped.
Args:
img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image.
top (int): Vertical component of the top left corner of the crop box.
left (int): Horizontal component of the top left corner of the crop box.
height (int): Height of the crop box.
width (int): Width of the crop box.
Returns:
PIL Image or Tensor: Cropped image.
"""
if not isinstance(img, paddle.Tensor):
return F_pil.crop(img, top, left, height, width)
return F_t.crop(img, top, left, height, width) | Crop the given image at specified location and output size.
If the image is paddle Tensor, it is expected
to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
If image size is smaller than output size along any edge, image is padded with 0 and then cropped.
Args:
img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image.
top (int): Vertical component of the top left corner of the crop box.
left (int): Horizontal component of the top left corner of the crop box.
height (int): Height of the crop box.
width (int): Width of the crop box.
Returns:
PIL Image or Tensor: Cropped image.
| crop | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py | Apache-2.0 |
def center_crop(img: Tensor, output_size: List[int]) -> Tensor:
"""Crops the given image at the center.
If the image is paddle Tensor, it is expected
to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
If image size is smaller than output size along any edge, image is padded with 0 and then center cropped.
Args:
img (PIL Image or Tensor): Image to be cropped.
output_size (sequence or int): (height, width) of the crop box. If int or sequence with single int,
it is used for both directions.
Returns:
PIL Image or Tensor: Cropped image.
"""
if isinstance(output_size, numbers.Number):
output_size = (int(output_size), int(output_size))
elif isinstance(output_size, (tuple, list)) and len(output_size) == 1:
output_size = (output_size[0], output_size[0])
image_width, image_height = _get_image_size(img)
crop_height, crop_width = output_size
if crop_width > image_width or crop_height > image_height:
padding_ltrb = [
(crop_width - image_width) // 2 if crop_width > image_width else 0,
(crop_height - image_height) // 2
if crop_height > image_height else 0,
(crop_width - image_width + 1) // 2
if crop_width > image_width else 0,
(crop_height - image_height + 1) // 2
if crop_height > image_height else 0,
]
img = pad(img, padding_ltrb, fill=0) # PIL uses fill value 0
image_width, image_height = _get_image_size(img)
if crop_width == image_width and crop_height == image_height:
return img
crop_top = int(round((image_height - crop_height) / 2.))
crop_left = int(round((image_width - crop_width) / 2.))
return crop(img, crop_top, crop_left, crop_height, crop_width) | Crops the given image at the center.
If the image is paddle Tensor, it is expected
to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
If image size is smaller than output size along any edge, image is padded with 0 and then center cropped.
Args:
img (PIL Image or Tensor): Image to be cropped.
output_size (sequence or int): (height, width) of the crop box. If int or sequence with single int,
it is used for both directions.
Returns:
PIL Image or Tensor: Cropped image.
| center_crop | python | PaddlePaddle/models | tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py | https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.