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 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/Step6/paddlevision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step6/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/Step6/paddlevision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step6/paddlevision/transforms/functional.py
Apache-2.0
def resized_crop( img: Tensor, top: int, left: int, height: int, width: int, size: List[int], interpolation: InterpolationMode=InterpolationMode.BILINEAR) -> Tensor: """Crop the given image and resize it to desired size. If the image is paddle Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions 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. size (sequence or int): Desired output size. Same semantics as ``resize``. 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. Returns: PIL Image or Tensor: Cropped image. """ img = crop(img, top, left, height, width) img = resize(img, size, interpolation) return img
Crop the given image and resize it to desired size. If the image is paddle Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions 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. size (sequence or int): Desired output size. Same semantics as ``resize``. 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. Returns: PIL Image or Tensor: Cropped image.
resized_crop
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step6/paddlevision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step6/paddlevision/transforms/functional.py
Apache-2.0
def hflip(img): """Horizontally flip the given image. Args: img (PIL Image or Tensor): Image to be flipped. If img is a Tensor, it is expected to be in [..., H, W] format, where ... means it can have an arbitrary number of leading dimensions. Returns: PIL Image or Tensor: Horizontally flipped image. """ if not isinstance(img, paddle.Tensor): return F_pil.hflip(img) return F_t.hflip(img)
Horizontally flip the given image. Args: img (PIL Image or Tensor): Image to be flipped. If img is a Tensor, it is expected to be in [..., H, W] format, where ... means it can have an arbitrary number of leading dimensions. Returns: PIL Image or Tensor: Horizontally flipped image.
hflip
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step6/paddlevision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step6/paddlevision/transforms/functional.py
Apache-2.0
def get_params(img: Tensor, scale: List[float], ratio: List[float]) -> Tuple[int, int, int, int]: """Get parameters for ``crop`` for a random sized crop. Args: img (PIL Image or Tensor): Input image. scale (list): range of scale of the origin size cropped ratio (list): range of aspect ratio of the origin aspect ratio cropped Returns: tuple: params (i, j, h, w) to be passed to ``crop`` for a random sized crop. """ width, height = F._get_image_size(img) area = height * width log_ratio = paddle.log(paddle.to_tensor(ratio)) for _ in range(10): target_area = area * paddle.uniform( shape=[1], min=scale[0], max=scale[1]).numpy().item() aspect_ratio = paddle.exp( paddle.uniform( shape=[1], min=log_ratio[0], max=log_ratio[1])).numpy( ).item() w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) if 0 < w <= width and 0 < h <= height: i = paddle.randint( 0, height - h + 1, shape=(1, )).numpy().item() j = paddle.randint( 0, width - w + 1, shape=(1, )).numpy().item() return i, j, h, w # Fallback to central crop in_ratio = float(width) / float(height) if in_ratio < min(ratio): w = width h = int(round(w / min(ratio))) elif in_ratio > max(ratio): h = height w = int(round(h * max(ratio))) else: # whole image w = width h = height i = (height - h) // 2 j = (width - w) // 2 return i, j, h, w
Get parameters for ``crop`` for a random sized crop. Args: img (PIL Image or Tensor): Input image. scale (list): range of scale of the origin size cropped ratio (list): range of aspect ratio of the origin aspect ratio cropped Returns: tuple: params (i, j, h, w) to be passed to ``crop`` for a random sized crop.
get_params
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step6/paddlevision/transforms/transforms.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step6/paddlevision/transforms/transforms.py
Apache-2.0
def forward(self, img): """ Args: img (PIL Image or Tensor): Image to be cropped and resized. Returns: PIL Image or Tensor: Randomly cropped and resized image. """ i, j, h, w = self.get_params(img, self.scale, self.ratio) return F.resized_crop(img, i, j, h, w, self.size, self.interpolation)
Args: img (PIL Image or Tensor): Image to be cropped and resized. Returns: PIL Image or Tensor: Randomly cropped and resized image.
forward
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step6/paddlevision/transforms/transforms.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step6/paddlevision/transforms/transforms.py
Apache-2.0
def forward(self, img): """ Args: img (PIL Image or Tensor): Image to be flipped. Returns: PIL Image or Tensor: Randomly flipped image. """ if random.random() < self.p: return F.hflip(img) return img
Args: img (PIL Image or Tensor): Image to be flipped. Returns: PIL Image or Tensor: Randomly flipped image.
forward
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step6/paddlevision/transforms/transforms.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step6/paddlevision/transforms/transforms.py
Apache-2.0
def __init__(self, config, model_info: dict={}, data_info: dict={}, perf_info: dict={}, resource_info: dict={}, **kwargs): """ Construct PaddleInferBenchmark Class to format logs. args: config(paddle.inference.Config): paddle inference config model_info(dict): basic model info {'model_name': 'resnet50' 'precision': 'fp32'} data_info(dict): input data info {'batch_size': 1 'shape': '3,224,224' 'data_num': 1000} perf_info(dict): performance result {'preprocess_time_s': 1.0 'inference_time_s': 2.0 'postprocess_time_s': 1.0 'total_time_s': 4.0} resource_info(dict): cpu and gpu resources {'cpu_rss': 100 'gpu_rss': 100 'gpu_util': 60} """ # PaddleInferBenchmark Log Version self.log_version = "1.0.3" # Paddle Version self.paddle_version = paddle.__version__ self.paddle_commit = paddle.__git_commit__ paddle_infer_info = paddle_infer.get_version() self.paddle_branch = paddle_infer_info.strip().split(': ')[-1] # model info self.model_info = model_info # data info self.data_info = data_info # perf info self.perf_info = perf_info try: # required value self.model_name = model_info['model_name'] self.precision = model_info['precision'] self.batch_size = data_info['batch_size'] self.shape = data_info['shape'] self.data_num = data_info['data_num'] self.inference_time_s = round(perf_info['inference_time_s'], 4) except: self.print_help() raise ValueError( "Set argument wrong, please check input argument and its type") self.preprocess_time_s = perf_info.get('preprocess_time_s', 0) self.postprocess_time_s = perf_info.get('postprocess_time_s', 0) self.total_time_s = perf_info.get('total_time_s', 0) self.inference_time_s_90 = perf_info.get("inference_time_s_90", "") self.inference_time_s_99 = perf_info.get("inference_time_s_99", "") self.succ_rate = perf_info.get("succ_rate", "") self.qps = perf_info.get("qps", "") # conf info self.config_status = self.parse_config(config) # mem info if isinstance(resource_info, dict): self.cpu_rss_mb = int(resource_info.get('cpu_rss_mb', 0)) self.cpu_vms_mb = int(resource_info.get('cpu_vms_mb', 0)) self.cpu_shared_mb = int(resource_info.get('cpu_shared_mb', 0)) self.cpu_dirty_mb = int(resource_info.get('cpu_dirty_mb', 0)) self.cpu_util = round(resource_info.get('cpu_util', 0), 2) self.gpu_rss_mb = int(resource_info.get('gpu_rss_mb', 0)) self.gpu_util = round(resource_info.get('gpu_util', 0), 2) self.gpu_mem_util = round(resource_info.get('gpu_mem_util', 0), 2) else: self.cpu_rss_mb = 0 self.cpu_vms_mb = 0 self.cpu_shared_mb = 0 self.cpu_dirty_mb = 0 self.cpu_util = 0 self.gpu_rss_mb = 0 self.gpu_util = 0 self.gpu_mem_util = 0 # init benchmark logger self.benchmark_logger()
Construct PaddleInferBenchmark Class to format logs. args: config(paddle.inference.Config): paddle inference config model_info(dict): basic model info {'model_name': 'resnet50' 'precision': 'fp32'} data_info(dict): input data info {'batch_size': 1 'shape': '3,224,224' 'data_num': 1000} perf_info(dict): performance result {'preprocess_time_s': 1.0 'inference_time_s': 2.0 'postprocess_time_s': 1.0 'total_time_s': 4.0} resource_info(dict): cpu and gpu resources {'cpu_rss': 100 'gpu_rss': 100 'gpu_util': 60}
__init__
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/deploy/benchmark_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/benchmark_utils.py
Apache-2.0
def parse_config(self, config) -> dict: """ parse paddle predictor config args: config(paddle.inference.Config): paddle inference config return: config_status(dict): dict style config info """ if isinstance(config, paddle_infer.Config): config_status = {} config_status['runtime_device'] = "gpu" if config.use_gpu( ) else "cpu" config_status['ir_optim'] = config.ir_optim() config_status['enable_tensorrt'] = config.tensorrt_engine_enabled() config_status['precision'] = self.precision config_status['enable_mkldnn'] = config.mkldnn_enabled() config_status[ 'cpu_math_library_num_threads'] = config.cpu_math_library_num_threads( ) elif isinstance(config, dict): config_status['runtime_device'] = config.get('runtime_device', "") config_status['ir_optim'] = config.get('ir_optim', "") config_status['enable_tensorrt'] = config.get('enable_tensorrt', "") config_status['precision'] = config.get('precision', "") config_status['enable_mkldnn'] = config.get('enable_mkldnn', "") config_status['cpu_math_library_num_threads'] = config.get( 'cpu_math_library_num_threads', "") else: self.print_help() raise ValueError( "Set argument config wrong, please check input argument and its type" ) return config_status
parse paddle predictor config args: config(paddle.inference.Config): paddle inference config return: config_status(dict): dict style config info
parse_config
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/deploy/benchmark_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/benchmark_utils.py
Apache-2.0
def report(self, identifier=None): """ print log report args: identifier(string): identify log """ if identifier: identifier = f"[{identifier}]" else: identifier = "" self.logger.info("\n") self.logger.info( "---------------------- Paddle info ----------------------") self.logger.info(f"{identifier} paddle_version: {self.paddle_version}") self.logger.info(f"{identifier} paddle_commit: {self.paddle_commit}") self.logger.info(f"{identifier} paddle_branch: {self.paddle_branch}") self.logger.info(f"{identifier} log_api_version: {self.log_version}") self.logger.info( "----------------------- Conf info -----------------------") self.logger.info( f"{identifier} runtime_device: {self.config_status['runtime_device']}" ) self.logger.info( f"{identifier} ir_optim: {self.config_status['ir_optim']}") self.logger.info(f"{identifier} enable_memory_optim: {True}") self.logger.info( f"{identifier} enable_tensorrt: {self.config_status['enable_tensorrt']}" ) self.logger.info( f"{identifier} enable_mkldnn: {self.config_status['enable_mkldnn']}" ) self.logger.info( f"{identifier} cpu_math_library_num_threads: {self.config_status['cpu_math_library_num_threads']}" ) self.logger.info( "----------------------- Model info ----------------------") self.logger.info(f"{identifier} model_name: {self.model_name}") self.logger.info(f"{identifier} precision: {self.precision}") self.logger.info( "----------------------- Data info -----------------------") self.logger.info(f"{identifier} batch_size: {self.batch_size}") self.logger.info(f"{identifier} input_shape: {self.shape}") self.logger.info(f"{identifier} data_num: {self.data_num}") self.logger.info( "----------------------- Perf info -----------------------") self.logger.info( f"{identifier} cpu_rss(MB): {self.cpu_rss_mb}, cpu_vms: {self.cpu_vms_mb}, cpu_shared_mb: {self.cpu_shared_mb}, cpu_dirty_mb: {self.cpu_dirty_mb}, cpu_util: {self.cpu_util}%" ) self.logger.info( f"{identifier} gpu_rss(MB): {self.gpu_rss_mb}, gpu_util: {self.gpu_util}%, gpu_mem_util: {self.gpu_mem_util}%" ) self.logger.info( f"{identifier} total time spent(s): {self.total_time_s}") self.logger.info( f"{identifier} preprocess_time(ms): {round(self.preprocess_time_s*1000, 1)}, inference_time(ms): {round(self.inference_time_s*1000, 1)}, postprocess_time(ms): {round(self.postprocess_time_s*1000, 1)}" ) if self.inference_time_s_90: self.looger.info( f"{identifier} 90%_cost: {self.inference_time_s_90}, 99%_cost: {self.inference_time_s_99}, succ_rate: {self.succ_rate}" ) if self.qps: self.logger.info(f"{identifier} QPS: {self.qps}")
print log report args: identifier(string): identify log
report
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/deploy/benchmark_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/benchmark_utils.py
Apache-2.0
def predict(self, image_list, threshold=0.5, repeats=1, add_timer=True): ''' Args: image_list (list): list of image threshold (float): threshold of predicted box' score repeats (int): repeat number for prediction add_timer (bool): whether add timer during prediction Returns: results (dict): include 'boxes': np.ndarray: shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] MaskRCNN's results include 'masks': np.ndarray: shape: [N, im_h, im_w] ''' # preprocess if add_timer: self.det_times.preprocess_time_s.start() inputs = self.preprocess(image_list) np_boxes = None input_names = self.predictor.get_input_names() for i in range(len(input_names)): input_tensor = self.predictor.get_input_handle(input_names[i]) input_tensor.copy_from_cpu(inputs[input_names[i]]) if add_timer: self.det_times.preprocess_time_s.end() self.det_times.inference_time_s.start() # model prediction for i in range(repeats): self.predictor.run() output_names = self.predictor.get_output_names() boxes_tensor = self.predictor.get_output_handle(output_names[0]) np_boxes = boxes_tensor.copy_to_cpu() if add_timer: self.det_times.inference_time_s.end(repeats=repeats) self.det_times.postprocess_time_s.start() # postprocess results = self.postprocess(np_boxes, inputs, threshold=threshold) if add_timer: self.det_times.postprocess_time_s.end() self.det_times.img_num += len(image_list) return results
Args: image_list (list): list of image threshold (float): threshold of predicted box' score repeats (int): repeat number for prediction add_timer (bool): whether add timer during prediction Returns: results (dict): include 'boxes': np.ndarray: shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] MaskRCNN's results include 'masks': np.ndarray: shape: [N, im_h, im_w]
predict
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/deploy/infer.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/infer.py
Apache-2.0
def create_inputs(imgs, im_info): """generate input for different model type Args: imgs (list(numpy)): list of images (np.ndarray) im_info (list(dict)): list of image info Returns: inputs (dict): input of model """ inputs = {} inputs['image'] = np.stack(imgs, axis=0) im_shape = [] for e in im_info: im_shape.append(np.array((e['im_shape'])).astype('float32')) inputs['im_shape'] = np.stack(im_shape, axis=0) return inputs
generate input for different model type Args: imgs (list(numpy)): list of images (np.ndarray) im_info (list(dict)): list of image info Returns: inputs (dict): input of model
create_inputs
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/deploy/infer.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/infer.py
Apache-2.0
def load_predictor(model_dir, run_mode='paddle', batch_size=1, device='CPU', min_subgraph_size=3, use_dynamic_shape=False, trt_min_shape=1, trt_max_shape=1280, trt_opt_shape=640, trt_calib_mode=False, cpu_threads=1, enable_mkldnn=False): """set AnalysisConfig, generate AnalysisPredictor Args: model_dir (str): root path of __model__ and __params__ device (str): Choose the device you want to run, it can be: CPU/GPU/XPU, default is CPU run_mode (str): mode of running(paddle/trt_fp32/trt_fp16/trt_int8) use_dynamic_shape (bool): use dynamic shape or not trt_min_shape (int): min shape for dynamic shape in trt trt_max_shape (int): max shape for dynamic shape in trt trt_opt_shape (int): opt shape for dynamic shape in trt trt_calib_mode (bool): If the model is produced by TRT offline quantitative calibration, trt_calib_mode need to set True Returns: predictor (PaddlePredictor): AnalysisPredictor Raises: ValueError: predict by TensorRT need device == 'GPU'. """ if device != 'GPU' and run_mode != 'paddle': raise ValueError( "Predict by TensorRT mode: {}, expect device=='GPU', but device == {}" .format(run_mode, device)) config = Config( os.path.join(model_dir, 'model.pdmodel'), os.path.join(model_dir, 'model.pdiparams')) if device == 'GPU': # initial GPU memory(M), device ID config.enable_use_gpu(200, 0) # optimize graph and fuse op config.switch_ir_optim(True) elif device == 'XPU': config.enable_lite_engine() config.enable_xpu(10 * 1024 * 1024) else: config.disable_gpu() config.set_cpu_math_library_num_threads(cpu_threads) if enable_mkldnn: try: # cache 10 different shapes for mkldnn to avoid memory leak config.set_mkldnn_cache_capacity(10) config.enable_mkldnn() except Exception as e: print( "The current environment does not support `mkldnn`, so disable mkldnn." ) pass precision_map = { 'trt_int8': Config.Precision.Int8, 'trt_fp32': Config.Precision.Float32, 'trt_fp16': Config.Precision.Half } if run_mode in precision_map.keys(): config.enable_tensorrt_engine( workspace_size=1 << 25, max_batch_size=batch_size, min_subgraph_size=min_subgraph_size, precision_mode=precision_map[run_mode], use_static=False, use_calib_mode=trt_calib_mode) if use_dynamic_shape: min_input_shape = { 'image': [batch_size, 3, trt_min_shape, trt_min_shape] } max_input_shape = { 'image': [batch_size, 3, trt_max_shape, trt_max_shape] } opt_input_shape = { 'image': [batch_size, 3, trt_opt_shape, trt_opt_shape] } config.set_trt_dynamic_shape_info(min_input_shape, max_input_shape, opt_input_shape) print('trt set dynamic shape done!') # disable print log when predict config.disable_glog_info() # enable shared memory config.enable_memory_optim() # disable feed, fetch OP, needed by zero_copy_run config.switch_use_feed_fetch_ops(False) predictor = create_predictor(config) return predictor, config
set AnalysisConfig, generate AnalysisPredictor Args: model_dir (str): root path of __model__ and __params__ device (str): Choose the device you want to run, it can be: CPU/GPU/XPU, default is CPU run_mode (str): mode of running(paddle/trt_fp32/trt_fp16/trt_int8) use_dynamic_shape (bool): use dynamic shape or not trt_min_shape (int): min shape for dynamic shape in trt trt_max_shape (int): max shape for dynamic shape in trt trt_opt_shape (int): opt shape for dynamic shape in trt trt_calib_mode (bool): If the model is produced by TRT offline quantitative calibration, trt_calib_mode need to set True Returns: predictor (PaddlePredictor): AnalysisPredictor Raises: ValueError: predict by TensorRT need device == 'GPU'.
load_predictor
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/deploy/infer.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/infer.py
Apache-2.0
def get_test_images(infer_dir, infer_img): """ Get image path list in TEST mode """ assert infer_img is not None or infer_dir is not None, \ "--infer_img or --infer_dir should be set" assert infer_img is None or os.path.isfile(infer_img), \ "{} is not a file".format(infer_img) assert infer_dir is None or os.path.isdir(infer_dir), \ "{} is not a directory".format(infer_dir) # infer_img has a higher priority if infer_img and os.path.isfile(infer_img): return [infer_img] images = set() infer_dir = os.path.abspath(infer_dir) assert os.path.isdir(infer_dir), \ "infer_dir {} is not a directory".format(infer_dir) exts = ['jpg', 'jpeg', 'png', 'bmp'] exts += [ext.upper() for ext in exts] for ext in exts: images.update(glob.glob('{}/*.{}'.format(infer_dir, ext))) images = list(images) assert len(images) > 0, "no image found in {}".format(infer_dir) print("Found {} inference images in total.".format(len(images))) return images
Get image path list in TEST mode
get_test_images
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/deploy/infer.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/infer.py
Apache-2.0
def setup_logger(name="ppdet", output=None): """ Initialize logger and set its verbosity level to INFO. Args: 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`. name (str): the root module name of this logger 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: 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`. name (str): the root module name of this logger Returns: logging.Logger: a logger
setup_logger
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/deploy/logger.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/logger.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
tutorials/pp-series/HRNet-Keypoint/deploy/postprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/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
tutorials/pp-series/HRNet-Keypoint/deploy/postprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/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
tutorials/pp-series/HRNet-Keypoint/deploy/postprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/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
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/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
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/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
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/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
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/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
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/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
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/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 """ img = cv2.cvtColor(im, cv2.COLOR_RGB2BGR) h, w = img.shape[:2] if self.keep_res: input_h = (h | self.pad) + 1 input_w = (w | self.pad) + 1 s = np.array([input_w, input_h], dtype=np.float32) c = np.array([w // 2, h // 2], dtype=np.float32) else: s = max(h, w) * 1.0 input_h, input_w = self.input_h, self.input_w c = np.array([w / 2., h / 2.], dtype=np.float32) trans_input = get_affine_transform(c, s, 0, [input_w, input_h]) img = cv2.resize(img, (w, h)) inp = cv2.warpAffine( img, trans_input, (input_w, input_h), flags=cv2.INTER_LINEAR) return inp, 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
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.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
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
Apache-2.0
def get_warp_matrix(theta, size_input, size_dst, size_target): """This code is based on https://github.com/open-mmlab/mmpose/blob/master/mmpose/core/post_processing/post_transforms.py Calculate the transformation matrix under the constraint of unbiased. Paper ref: Huang et al. The Devil is in the Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020). Args: theta (float): Rotation angle in degrees. size_input (np.ndarray): Size of input image [w, h]. size_dst (np.ndarray): Size of output image [w, h]. size_target (np.ndarray): Size of ROI in input plane [w, h]. Returns: matrix (np.ndarray): A matrix for transformation. """ theta = np.deg2rad(theta) matrix = np.zeros((2, 3), dtype=np.float32) scale_x = size_dst[0] / size_target[0] scale_y = size_dst[1] / size_target[1] matrix[0, 0] = np.cos(theta) * scale_x matrix[0, 1] = -np.sin(theta) * scale_x matrix[0, 2] = scale_x * ( -0.5 * size_input[0] * np.cos(theta) + 0.5 * size_input[1] * np.sin(theta) + 0.5 * size_target[0]) matrix[1, 0] = np.sin(theta) * scale_y matrix[1, 1] = np.cos(theta) * scale_y matrix[1, 2] = scale_y * ( -0.5 * size_input[0] * np.sin(theta) - 0.5 * size_input[1] * np.cos(theta) + 0.5 * size_target[1]) return matrix
This code is based on https://github.com/open-mmlab/mmpose/blob/master/mmpose/core/post_processing/post_transforms.py Calculate the transformation matrix under the constraint of unbiased. Paper ref: Huang et al. The Devil is in the Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020). Args: theta (float): Rotation angle in degrees. size_input (np.ndarray): Size of input image [w, h]. size_dst (np.ndarray): Size of output image [w, h]. size_target (np.ndarray): Size of ROI in input plane [w, h]. Returns: matrix (np.ndarray): A matrix for transformation.
get_warp_matrix
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/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
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/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
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.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
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
Apache-2.0
def get_warp_matrix(theta, size_input, size_dst, size_target): """This code is based on https://github.com/open-mmlab/mmpose/blob/master/mmpose/core/post_processing/post_transforms.py Calculate the transformation matrix under the constraint of unbiased. Paper ref: Huang et al. The Devil is in the Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020). Args: theta (float): Rotation angle in degrees. size_input (np.ndarray): Size of input image [w, h]. size_dst (np.ndarray): Size of output image [w, h]. size_target (np.ndarray): Size of ROI in input plane [w, h]. Returns: matrix (np.ndarray): A matrix for transformation. """ theta = np.deg2rad(theta) matrix = np.zeros((2, 3), dtype=np.float32) scale_x = size_dst[0] / size_target[0] scale_y = size_dst[1] / size_target[1] matrix[0, 0] = np.cos(theta) * scale_x matrix[0, 1] = -np.sin(theta) * scale_x matrix[0, 2] = scale_x * ( -0.5 * size_input[0] * np.cos(theta) + 0.5 * size_input[1] * np.sin(theta) + 0.5 * size_target[0]) matrix[1, 0] = np.sin(theta) * scale_y matrix[1, 1] = np.cos(theta) * scale_y matrix[1, 2] = scale_y * ( -0.5 * size_input[0] * np.sin(theta) - 0.5 * size_input[1] * np.cos(theta) + 0.5 * size_target[1]) return matrix
This code is based on https://github.com/open-mmlab/mmpose/blob/master/mmpose/core/post_processing/post_transforms.py Calculate the transformation matrix under the constraint of unbiased. Paper ref: Huang et al. The Devil is in the Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020). Args: theta (float): Rotation angle in degrees. size_input (np.ndarray): Size of input image [w, h]. size_dst (np.ndarray): Size of output image [w, h]. size_target (np.ndarray): Size of ROI in input plane [w, h]. Returns: matrix (np.ndarray): A matrix for transformation.
get_warp_matrix
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/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
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/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
tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/preprocess.py
Apache-2.0
def get_current_memory_mb(): """ It is used to Obtain the memory usage of the CPU and GPU during the running of the program. And this function Current program is time-consuming. """ import pynvml import psutil import GPUtil gpu_id = int(os.environ.get('CUDA_VISIBLE_DEVICES', 0)) pid = os.getpid() p = psutil.Process(pid) info = p.memory_full_info() cpu_mem = info.uss / 1024. / 1024. gpu_mem = 0 gpu_percent = 0 gpus = GPUtil.getGPUs() if gpu_id is not None and len(gpus) > 0: gpu_percent = gpus[gpu_id].load pynvml.nvmlInit() handle = pynvml.nvmlDeviceGetHandleByIndex(0) meminfo = pynvml.nvmlDeviceGetMemoryInfo(handle) gpu_mem = meminfo.used / 1024. / 1024. return round(cpu_mem, 4), round(gpu_mem, 4), round(gpu_percent, 4)
It is used to Obtain the memory usage of the CPU and GPU during the running of the program. And this function Current program is time-consuming.
get_current_memory_mb
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/deploy/utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/deploy/utils.py
Apache-2.0
def _get_save_image_name(self, output_dir, image_path): """ Get save image name from source image path. """ if not os.path.exists(output_dir): os.makedirs(output_dir) image_name = os.path.split(image_path)[-1] name, ext = os.path.splitext(image_name) return os.path.join(output_dir, "{}".format(name)) + ext
Get save image name from source image path.
_get_save_image_name
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/core/trainer.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/core/trainer.py
Apache-2.0
def get_categories(metric_type, anno_file=None, arch=None): """ Get class id to category id map and category id to category name map from annotation file. Args: metric_type (str): metric type, currently support 'coco'. anno_file (str): annotation file path """ if arch == 'keypoint_arch': return (None, {'id': 'keypoint'}) if metric_type.lower() == 'keypointtopdowncocoeval' or metric_type.lower( ) == 'keypointtopdownmpiieval': return (None, {'id': 'keypoint'}) else: raise ValueError("unknown metric type {}".format(metric_type))
Get class id to category id map and category id to category name map from annotation file. Args: metric_type (str): metric type, currently support 'coco'. anno_file (str): annotation file path
get_categories
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/category.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/category.py
Apache-2.0
def _mot_category(category='pedestrian'): """ Get class id to category id map and category id to category name map of mot dataset """ label_map = {category: 0} label_map = sorted(label_map.items(), key=lambda x: x[1]) cats = [l[0] for l in label_map] clsid2catid = {i: i for i in range(len(cats))} catid2name = {i: name for i, name in enumerate(cats)} return clsid2catid, catid2name
Get class id to category id map and category id to category name map of mot dataset
_mot_category
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/category.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/category.py
Apache-2.0
def _coco17_category(): """ Get class id to category id map and category id to category name map of COCO2017 dataset """ clsid2catid = { 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 13, 13: 14, 14: 15, 15: 16, 16: 17, 17: 18, 18: 19, 19: 20, 20: 21, 21: 22, 22: 23, 23: 24, 24: 25, 25: 27, 26: 28, 27: 31, 28: 32, 29: 33, 30: 34, 31: 35, 32: 36, 33: 37, 34: 38, 35: 39, 36: 40, 37: 41, 38: 42, 39: 43, 40: 44, 41: 46, 42: 47, 43: 48, 44: 49, 45: 50, 46: 51, 47: 52, 48: 53, 49: 54, 50: 55, 51: 56, 52: 57, 53: 58, 54: 59, 55: 60, 56: 61, 57: 62, 58: 63, 59: 64, 60: 65, 61: 67, 62: 70, 63: 72, 64: 73, 65: 74, 66: 75, 67: 76, 68: 77, 69: 78, 70: 79, 71: 80, 72: 81, 73: 82, 74: 84, 75: 85, 76: 86, 77: 87, 78: 88, 79: 89, 80: 90 } catid2name = { 0: 'background', 1: 'person', 2: 'bicycle', 3: 'car', 4: 'motorcycle', 5: 'airplane', 6: 'bus', 7: 'train', 8: 'truck', 9: 'boat', 10: 'traffic light', 11: 'fire hydrant', 13: 'stop sign', 14: 'parking meter', 15: 'bench', 16: 'bird', 17: 'cat', 18: 'dog', 19: 'horse', 20: 'sheep', 21: 'cow', 22: 'elephant', 23: 'bear', 24: 'zebra', 25: 'giraffe', 27: 'backpack', 28: 'umbrella', 31: 'handbag', 32: 'tie', 33: 'suitcase', 34: 'frisbee', 35: 'skis', 36: 'snowboard', 37: 'sports ball', 38: 'kite', 39: 'baseball bat', 40: 'baseball glove', 41: 'skateboard', 42: 'surfboard', 43: 'tennis racket', 44: 'bottle', 46: 'wine glass', 47: 'cup', 48: 'fork', 49: 'knife', 50: 'spoon', 51: 'bowl', 52: 'banana', 53: 'apple', 54: 'sandwich', 55: 'orange', 56: 'broccoli', 57: 'carrot', 58: 'hot dog', 59: 'pizza', 60: 'donut', 61: 'cake', 62: 'chair', 63: 'couch', 64: 'potted plant', 65: 'bed', 67: 'dining table', 70: 'toilet', 72: 'tv', 73: 'laptop', 74: 'mouse', 75: 'remote', 76: 'keyboard', 77: 'cell phone', 78: 'microwave', 79: 'oven', 80: 'toaster', 81: 'sink', 82: 'refrigerator', 84: 'book', 85: 'clock', 86: 'vase', 87: 'scissors', 88: 'teddy bear', 89: 'hair drier', 90: 'toothbrush' } clsid2catid = {k - 1: v for k, v in clsid2catid.items()} catid2name.pop(0) return clsid2catid, catid2name
Get class id to category id map and category id to category name map of COCO2017 dataset
_coco17_category
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/category.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/category.py
Apache-2.0
def _dota_category(): """ Get class id to category id map and category id to category name map of dota dataset """ catid2name = { 0: 'background', 1: 'plane', 2: 'baseball-diamond', 3: 'bridge', 4: 'ground-track-field', 5: 'small-vehicle', 6: 'large-vehicle', 7: 'ship', 8: 'tennis-court', 9: 'basketball-court', 10: 'storage-tank', 11: 'soccer-ball-field', 12: 'roundabout', 13: 'harbor', 14: 'swimming-pool', 15: 'helicopter' } catid2name.pop(0) clsid2catid = {i: i + 1 for i in range(len(catid2name))} return clsid2catid, catid2name
Get class id to category id map and category id to category name map of dota dataset
_dota_category
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/category.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/category.py
Apache-2.0
def __getitem__(self, idx): """Prepare sample for training given the index.""" records = copy.deepcopy(self.db[idx]) records['image'] = cv2.imread(records['image_file'], cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION) records['image'] = cv2.cvtColor(records['image'], cv2.COLOR_BGR2RGB) records['score'] = records['score'] if 'score' in records else 1 records = self.transform(records) # print('records', records) return records
Prepare sample for training given the index.
__getitem__
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/keypoint_coco.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/keypoint_coco.py
Apache-2.0
def policy_v0(): """Autoaugment policy that was used in AutoAugment Detection Paper.""" # Each tuple is an augmentation operation of the form # (operation, probability, magnitude). Each element in policy is a # sub-policy that will be applied sequentially on the image. policy = [ [('TranslateX_BBox', 0.6, 4), ('Equalize', 0.8, 10)], [('TranslateY_Only_BBoxes', 0.2, 2), ('Cutout', 0.8, 8)], [('Sharpness', 0.0, 8), ('ShearX_BBox', 0.4, 0)], [('ShearY_BBox', 1.0, 2), ('TranslateY_Only_BBoxes', 0.6, 6)], [('Rotate_BBox', 0.6, 10), ('Color', 1.0, 6)], ] return policy
Autoaugment policy that was used in AutoAugment Detection Paper.
policy_v0
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def policy_v1(): """Autoaugment policy that was used in AutoAugment Detection Paper.""" # Each tuple is an augmentation operation of the form # (operation, probability, magnitude). Each element in policy is a # sub-policy that will be applied sequentially on the image. policy = [ [('TranslateX_BBox', 0.6, 4), ('Equalize', 0.8, 10)], [('TranslateY_Only_BBoxes', 0.2, 2), ('Cutout', 0.8, 8)], [('Sharpness', 0.0, 8), ('ShearX_BBox', 0.4, 0)], [('ShearY_BBox', 1.0, 2), ('TranslateY_Only_BBoxes', 0.6, 6)], [('Rotate_BBox', 0.6, 10), ('Color', 1.0, 6)], [('Color', 0.0, 0), ('ShearX_Only_BBoxes', 0.8, 4)], [('ShearY_Only_BBoxes', 0.8, 2), ('Flip_Only_BBoxes', 0.0, 10)], [('Equalize', 0.6, 10), ('TranslateX_BBox', 0.2, 2)], [('Color', 1.0, 10), ('TranslateY_Only_BBoxes', 0.4, 6)], [('Rotate_BBox', 0.8, 10), ('Contrast', 0.0, 10)], # , [('Cutout', 0.2, 2), ('Brightness', 0.8, 10)], [('Color', 1.0, 6), ('Equalize', 1.0, 2)], [('Cutout_Only_BBoxes', 0.4, 6), ('TranslateY_Only_BBoxes', 0.8, 2)], [('Color', 0.2, 8), ('Rotate_BBox', 0.8, 10)], [('Sharpness', 0.4, 4), ('TranslateY_Only_BBoxes', 0.0, 4)], [('Sharpness', 1.0, 4), ('SolarizeAdd', 0.4, 4)], [('Rotate_BBox', 1.0, 8), ('Sharpness', 0.2, 8)], [('ShearY_BBox', 0.6, 10), ('Equalize_Only_BBoxes', 0.6, 8)], [('ShearX_BBox', 0.2, 6), ('TranslateY_Only_BBoxes', 0.2, 10)], [('SolarizeAdd', 0.6, 8), ('Brightness', 0.8, 10)], ] return policy
Autoaugment policy that was used in AutoAugment Detection Paper.
policy_v1
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def policy_v2(): """Additional policy that performs well on object detection.""" # Each tuple is an augmentation operation of the form # (operation, probability, magnitude). Each element in policy is a # sub-policy that will be applied sequentially on the image. policy = [ [('Color', 0.0, 6), ('Cutout', 0.6, 8), ('Sharpness', 0.4, 8)], [('Rotate_BBox', 0.4, 8), ('Sharpness', 0.4, 2), ('Rotate_BBox', 0.8, 10)], [('TranslateY_BBox', 1.0, 8), ('AutoContrast', 0.8, 2)], [('AutoContrast', 0.4, 6), ('ShearX_BBox', 0.8, 8), ('Brightness', 0.0, 10)], [('SolarizeAdd', 0.2, 6), ('Contrast', 0.0, 10), ('AutoContrast', 0.6, 0)], [('Cutout', 0.2, 0), ('Solarize', 0.8, 8), ('Color', 1.0, 4)], [('TranslateY_BBox', 0.0, 4), ('Equalize', 0.6, 8), ('Solarize', 0.0, 10)], [('TranslateY_BBox', 0.2, 2), ('ShearY_BBox', 0.8, 8), ('Rotate_BBox', 0.8, 8)], [('Cutout', 0.8, 8), ('Brightness', 0.8, 8), ('Cutout', 0.2, 2)], [('Color', 0.8, 4), ('TranslateY_BBox', 1.0, 6), ('Rotate_BBox', 0.6, 6)], [('Rotate_BBox', 0.6, 10), ('BBox_Cutout', 1.0, 4), ('Cutout', 0.2, 8)], [('Rotate_BBox', 0.0, 0), ('Equalize', 0.6, 6), ('ShearY_BBox', 0.6, 8)], [('Brightness', 0.8, 8), ('AutoContrast', 0.4, 2), ('Brightness', 0.2, 2)], [('TranslateY_BBox', 0.4, 8), ('Solarize', 0.4, 6), ('SolarizeAdd', 0.2, 10)], [('Contrast', 1.0, 10), ('SolarizeAdd', 0.2, 8), ('Equalize', 0.2, 4)], ] return policy
Additional policy that performs well on object detection.
policy_v2
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def policy_v3(): """"Additional policy that performs well on object detection.""" # Each tuple is an augmentation operation of the form # (operation, probability, magnitude). Each element in policy is a # sub-policy that will be applied sequentially on the image. policy = [ [('Posterize', 0.8, 2), ('TranslateX_BBox', 1.0, 8)], [('BBox_Cutout', 0.2, 10), ('Sharpness', 1.0, 8)], [('Rotate_BBox', 0.6, 8), ('Rotate_BBox', 0.8, 10)], [('Equalize', 0.8, 10), ('AutoContrast', 0.2, 10)], [('SolarizeAdd', 0.2, 2), ('TranslateY_BBox', 0.2, 8)], [('Sharpness', 0.0, 2), ('Color', 0.4, 8)], [('Equalize', 1.0, 8), ('TranslateY_BBox', 1.0, 8)], [('Posterize', 0.6, 2), ('Rotate_BBox', 0.0, 10)], [('AutoContrast', 0.6, 0), ('Rotate_BBox', 1.0, 6)], [('Equalize', 0.0, 4), ('Cutout', 0.8, 10)], [('Brightness', 1.0, 2), ('TranslateY_BBox', 1.0, 6)], [('Contrast', 0.0, 2), ('ShearY_BBox', 0.8, 0)], [('AutoContrast', 0.8, 10), ('Contrast', 0.2, 10)], [('Rotate_BBox', 1.0, 10), ('Cutout', 1.0, 10)], [('SolarizeAdd', 0.8, 6), ('Equalize', 0.8, 8)], ] return policy
"Additional policy that performs well on object detection.
policy_v3
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def blend(image1, image2, factor): """Blend image1 and image2 using 'factor'. Factor can be above 0.0. A value of 0.0 means only image1 is used. A value of 1.0 means only image2 is used. A value between 0.0 and 1.0 means we linearly interpolate the pixel values between the two images. A value greater than 1.0 "extrapolates" the difference between the two pixel values, and we clip the results to values between 0 and 255. Args: image1: An image Tensor of type uint8. image2: An image Tensor of type uint8. factor: A floating point value above 0.0. Returns: A blended image Tensor of type uint8. """ if factor == 0.0: return image1 if factor == 1.0: return image2 image1 = image1.astype(np.float32) image2 = image2.astype(np.float32) difference = image2 - image1 scaled = factor * difference # Do addition in float. temp = image1 + scaled # Interpolate if factor > 0.0 and factor < 1.0: # Interpolation means we always stay within 0 and 255. return temp.astype(np.uint8) # Extrapolate: # # We need to clip and then cast. return np.clip(temp, a_min=0, a_max=255).astype(np.uint8)
Blend image1 and image2 using 'factor'. Factor can be above 0.0. A value of 0.0 means only image1 is used. A value of 1.0 means only image2 is used. A value between 0.0 and 1.0 means we linearly interpolate the pixel values between the two images. A value greater than 1.0 "extrapolates" the difference between the two pixel values, and we clip the results to values between 0 and 255. Args: image1: An image Tensor of type uint8. image2: An image Tensor of type uint8. factor: A floating point value above 0.0. Returns: A blended image Tensor of type uint8.
blend
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def cutout(image, pad_size, replace=0): """Apply cutout (https://arxiv.org/abs/1708.04552) to image. This operation applies a (2*pad_size x 2*pad_size) mask of zeros to a random location within `img`. The pixel values filled in will be of the value `replace`. The located where the mask will be applied is randomly chosen uniformly over the whole image. Args: image: An image Tensor of type uint8. pad_size: Specifies how big the zero mask that will be generated is that is applied to the image. The mask will be of size (2*pad_size x 2*pad_size). replace: What pixel value to fill in the image in the area that has the cutout mask applied to it. Returns: An image Tensor that is of type uint8. Example: img = cv2.imread( "/home/vis/gry/train/img_data/test.jpg", cv2.COLOR_BGR2RGB ) new_img = cutout(img, pad_size=50, replace=0) """ image_height, image_width = image.shape[0], image.shape[1] cutout_center_height = np.random.randint(low=0, high=image_height) cutout_center_width = np.random.randint(low=0, high=image_width) lower_pad = np.maximum(0, cutout_center_height - pad_size) upper_pad = np.maximum(0, image_height - cutout_center_height - pad_size) left_pad = np.maximum(0, cutout_center_width - pad_size) right_pad = np.maximum(0, image_width - cutout_center_width - pad_size) cutout_shape = [ image_height - (lower_pad + upper_pad), image_width - (left_pad + right_pad) ] padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]] mask = np.pad(np.zeros( cutout_shape, dtype=image.dtype), padding_dims, 'constant', constant_values=1) mask = np.expand_dims(mask, -1) mask = np.tile(mask, [1, 1, 3]) image = np.where( np.equal(mask, 0), np.ones_like( image, dtype=image.dtype) * replace, image) return image.astype(np.uint8)
Apply cutout (https://arxiv.org/abs/1708.04552) to image. This operation applies a (2*pad_size x 2*pad_size) mask of zeros to a random location within `img`. The pixel values filled in will be of the value `replace`. The located where the mask will be applied is randomly chosen uniformly over the whole image. Args: image: An image Tensor of type uint8. pad_size: Specifies how big the zero mask that will be generated is that is applied to the image. The mask will be of size (2*pad_size x 2*pad_size). replace: What pixel value to fill in the image in the area that has the cutout mask applied to it. Returns: An image Tensor that is of type uint8. Example: img = cv2.imread( "/home/vis/gry/train/img_data/test.jpg", cv2.COLOR_BGR2RGB ) new_img = cutout(img, pad_size=50, replace=0)
cutout
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def rotate(image, degrees, replace): """Rotates the image by degrees either clockwise or counterclockwise. Args: image: An image Tensor of type uint8. degrees: Float, a scalar angle in degrees to rotate all images by. If degrees is positive the image will be rotated clockwise otherwise it will be rotated counterclockwise. replace: A one or three value 1D tensor to fill empty pixels caused by the rotate operation. Returns: The rotated version of image. """ image = wrap(image) image = Image.fromarray(image) image = image.rotate(degrees) image = np.array(image, dtype=np.uint8) return unwrap(image, replace)
Rotates the image by degrees either clockwise or counterclockwise. Args: image: An image Tensor of type uint8. degrees: Float, a scalar angle in degrees to rotate all images by. If degrees is positive the image will be rotated clockwise otherwise it will be rotated counterclockwise. replace: A one or three value 1D tensor to fill empty pixels caused by the rotate operation. Returns: The rotated version of image.
rotate
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def random_shift_bbox(image, bbox, pixel_scaling, replace, new_min_bbox_coords=None): """Move the bbox and the image content to a slightly new random location. Args: image: 3D uint8 Tensor. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. The potential values for the new min corner of the bbox will be between [old_min - pixel_scaling * bbox_height/2, old_min - pixel_scaling * bbox_height/2]. pixel_scaling: A float between 0 and 1 that specifies the pixel range that the new bbox location will be sampled from. replace: A one or three value 1D tensor to fill empty pixels. new_min_bbox_coords: If not None, then this is a tuple that specifies the (min_y, min_x) coordinates of the new bbox. Normally this is randomly specified, but this allows it to be manually set. The coordinates are the absolute coordinates between 0 and image height/width and are int32. Returns: The new image that will have the shifted bbox location in it along with the new bbox that contains the new coordinates. """ # Obtains image height and width and create helper clip functions. image_height, image_width = image.shape[0], image.shape[1] image_height = float(image_height) image_width = float(image_width) def clip_y(val): return np.clip(val, a_min=0, a_max=image_height - 1).astype(np.int32) def clip_x(val): return np.clip(val, a_min=0, a_max=image_width - 1).astype(np.int32) # Convert bbox to pixel coordinates. min_y = int(image_height * bbox[0]) min_x = int(image_width * bbox[1]) max_y = clip_y(image_height * bbox[2]) max_x = clip_x(image_width * bbox[3]) bbox_height, bbox_width = (max_y - min_y + 1, max_x - min_x + 1) image_height = int(image_height) image_width = int(image_width) # Select the new min/max bbox ranges that are used for sampling the # new min x/y coordinates of the shifted bbox. minval_y = clip_y(min_y - np.int32(pixel_scaling * float(bbox_height) / 2.0)) maxval_y = clip_y(min_y + np.int32(pixel_scaling * float(bbox_height) / 2.0)) minval_x = clip_x(min_x - np.int32(pixel_scaling * float(bbox_width) / 2.0)) maxval_x = clip_x(min_x + np.int32(pixel_scaling * float(bbox_width) / 2.0)) # Sample and calculate the new unclipped min/max coordinates of the new bbox. if new_min_bbox_coords is None: unclipped_new_min_y = np.random.randint( low=minval_y, high=maxval_y, dtype=np.int32) unclipped_new_min_x = np.random.randint( low=minval_x, high=maxval_x, dtype=np.int32) else: unclipped_new_min_y, unclipped_new_min_x = ( clip_y(new_min_bbox_coords[0]), clip_x(new_min_bbox_coords[1])) unclipped_new_max_y = unclipped_new_min_y + bbox_height - 1 unclipped_new_max_x = unclipped_new_min_x + bbox_width - 1 # Determine if any of the new bbox was shifted outside the current image. # This is used for determining if any of the original bbox content should be # discarded. new_min_y, new_min_x, new_max_y, new_max_x = ( clip_y(unclipped_new_min_y), clip_x(unclipped_new_min_x), clip_y(unclipped_new_max_y), clip_x(unclipped_new_max_x)) shifted_min_y = (new_min_y - unclipped_new_min_y) + min_y shifted_max_y = max_y - (unclipped_new_max_y - new_max_y) shifted_min_x = (new_min_x - unclipped_new_min_x) + min_x shifted_max_x = max_x - (unclipped_new_max_x - new_max_x) # Create the new bbox tensor by converting pixel integer values to floats. new_bbox = np.stack([ float(new_min_y) / float(image_height), float(new_min_x) / float(image_width), float(new_max_y) / float(image_height), float(new_max_x) / float(image_width) ]) # Copy the contents in the bbox and fill the old bbox location # with gray (128). bbox_content = image[shifted_min_y:shifted_max_y + 1, shifted_min_x: shifted_max_x + 1, :] def mask_and_add_image(min_y_, min_x_, max_y_, max_x_, mask, content_tensor, image_): """Applies mask to bbox region in image then adds content_tensor to it.""" mask = np.pad(mask, [[min_y_, (image_height - 1) - max_y_], [min_x_, (image_width - 1) - max_x_], [0, 0]], 'constant', constant_values=1) content_tensor = np.pad(content_tensor, [[min_y_, (image_height - 1) - max_y_], [min_x_, (image_width - 1) - max_x_], [0, 0]], 'constant', constant_values=0) return image_ * mask + content_tensor # Zero out original bbox location. mask = np.zeros_like(image)[min_y:max_y + 1, min_x:max_x + 1, :] grey_tensor = np.zeros_like(mask) + replace[0] image = mask_and_add_image(min_y, min_x, max_y, max_x, mask, grey_tensor, image) # Fill in bbox content to new bbox location. mask = np.zeros_like(bbox_content) image = mask_and_add_image(new_min_y, new_min_x, new_max_y, new_max_x, mask, bbox_content, image) return image.astype(np.uint8), new_bbox
Move the bbox and the image content to a slightly new random location. Args: image: 3D uint8 Tensor. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. The potential values for the new min corner of the bbox will be between [old_min - pixel_scaling * bbox_height/2, old_min - pixel_scaling * bbox_height/2]. pixel_scaling: A float between 0 and 1 that specifies the pixel range that the new bbox location will be sampled from. replace: A one or three value 1D tensor to fill empty pixels. new_min_bbox_coords: If not None, then this is a tuple that specifies the (min_y, min_x) coordinates of the new bbox. Normally this is randomly specified, but this allows it to be manually set. The coordinates are the absolute coordinates between 0 and image height/width and are int32. Returns: The new image that will have the shifted bbox location in it along with the new bbox that contains the new coordinates.
random_shift_bbox
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def mask_and_add_image(min_y_, min_x_, max_y_, max_x_, mask, content_tensor, image_): """Applies mask to bbox region in image then adds content_tensor to it.""" mask = np.pad(mask, [[min_y_, (image_height - 1) - max_y_], [min_x_, (image_width - 1) - max_x_], [0, 0]], 'constant', constant_values=1) content_tensor = np.pad(content_tensor, [[min_y_, (image_height - 1) - max_y_], [min_x_, (image_width - 1) - max_x_], [0, 0]], 'constant', constant_values=0) return image_ * mask + content_tensor
Applies mask to bbox region in image then adds content_tensor to it.
mask_and_add_image
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _clip_bbox(min_y, min_x, max_y, max_x): """Clip bounding box coordinates between 0 and 1. Args: min_y: Normalized bbox coordinate of type float between 0 and 1. min_x: Normalized bbox coordinate of type float between 0 and 1. max_y: Normalized bbox coordinate of type float between 0 and 1. max_x: Normalized bbox coordinate of type float between 0 and 1. Returns: Clipped coordinate values between 0 and 1. """ min_y = np.clip(min_y, a_min=0, a_max=1.0) min_x = np.clip(min_x, a_min=0, a_max=1.0) max_y = np.clip(max_y, a_min=0, a_max=1.0) max_x = np.clip(max_x, a_min=0, a_max=1.0) return min_y, min_x, max_y, max_x
Clip bounding box coordinates between 0 and 1. Args: min_y: Normalized bbox coordinate of type float between 0 and 1. min_x: Normalized bbox coordinate of type float between 0 and 1. max_y: Normalized bbox coordinate of type float between 0 and 1. max_x: Normalized bbox coordinate of type float between 0 and 1. Returns: Clipped coordinate values between 0 and 1.
_clip_bbox
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _check_bbox_area(min_y, min_x, max_y, max_x, delta=0.05): """Adjusts bbox coordinates to make sure the area is > 0. Args: min_y: Normalized bbox coordinate of type float between 0 and 1. min_x: Normalized bbox coordinate of type float between 0 and 1. max_y: Normalized bbox coordinate of type float between 0 and 1. max_x: Normalized bbox coordinate of type float between 0 and 1. delta: Float, this is used to create a gap of size 2 * delta between bbox min/max coordinates that are the same on the boundary. This prevents the bbox from having an area of zero. Returns: Tuple of new bbox coordinates between 0 and 1 that will now have a guaranteed area > 0. """ height = max_y - min_y width = max_x - min_x def _adjust_bbox_boundaries(min_coord, max_coord): # Make sure max is never 0 and min is never 1. max_coord = np.maximum(max_coord, 0.0 + delta) min_coord = np.minimum(min_coord, 1.0 - delta) return min_coord, max_coord if _equal(height, 0): min_y, max_y = _adjust_bbox_boundaries(min_y, max_y) if _equal(width, 0): min_x, max_x = _adjust_bbox_boundaries(min_x, max_x) return min_y, min_x, max_y, max_x
Adjusts bbox coordinates to make sure the area is > 0. Args: min_y: Normalized bbox coordinate of type float between 0 and 1. min_x: Normalized bbox coordinate of type float between 0 and 1. max_y: Normalized bbox coordinate of type float between 0 and 1. max_x: Normalized bbox coordinate of type float between 0 and 1. delta: Float, this is used to create a gap of size 2 * delta between bbox min/max coordinates that are the same on the boundary. This prevents the bbox from having an area of zero. Returns: Tuple of new bbox coordinates between 0 and 1 that will now have a guaranteed area > 0.
_check_bbox_area
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _apply_bbox_augmentation(image, bbox, augmentation_func, *args): """Applies augmentation_func to the subsection of image indicated by bbox. Args: image: 3D uint8 Tensor. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. augmentation_func: Augmentation function that will be applied to the subsection of image. *args: Additional parameters that will be passed into augmentation_func when it is called. Returns: A modified version of image, where the bbox location in the image will have `ugmentation_func applied to it. """ image_height = image.shape[0] image_width = image.shape[1] min_y = int(image_height * bbox[0]) min_x = int(image_width * bbox[1]) max_y = int(image_height * bbox[2]) max_x = int(image_width * bbox[3]) # Clip to be sure the max values do not fall out of range. max_y = np.minimum(max_y, image_height - 1) max_x = np.minimum(max_x, image_width - 1) # Get the sub-tensor that is the image within the bounding box region. bbox_content = image[min_y:max_y + 1, min_x:max_x + 1, :] # Apply the augmentation function to the bbox portion of the image. augmented_bbox_content = augmentation_func(bbox_content, *args) # Pad the augmented_bbox_content and the mask to match the shape of original # image. augmented_bbox_content = np.pad( augmented_bbox_content, [[min_y, (image_height - 1) - max_y], [min_x, (image_width - 1) - max_x], [0, 0]], 'constant', constant_values=1) # Create a mask that will be used to zero out a part of the original image. mask_tensor = np.zeros_like(bbox_content) mask_tensor = np.pad(mask_tensor, [[min_y, (image_height - 1) - max_y], [min_x, (image_width - 1) - max_x], [0, 0]], 'constant', constant_values=1) # Replace the old bbox content with the new augmented content. image = image * mask_tensor + augmented_bbox_content return image.astype(np.uint8)
Applies augmentation_func to the subsection of image indicated by bbox. Args: image: 3D uint8 Tensor. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. augmentation_func: Augmentation function that will be applied to the subsection of image. *args: Additional parameters that will be passed into augmentation_func when it is called. Returns: A modified version of image, where the bbox location in the image will have `ugmentation_func applied to it.
_apply_bbox_augmentation
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _concat_bbox(bbox, bboxes): """Helper function that concates bbox to bboxes along the first dimension.""" # Note if all elements in bboxes are -1 (_INVALID_BOX), then this means # we discard bboxes and start the bboxes Tensor with the current bbox. bboxes_sum_check = np.sum(bboxes) bbox = np.expand_dims(bbox, 0) # This check will be true when it is an _INVALID_BOX if _equal(bboxes_sum_check, -4): bboxes = bbox else: bboxes = np.concatenate([bboxes, bbox], 0) return bboxes
Helper function that concates bbox to bboxes along the first dimension.
_concat_bbox
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _apply_bbox_augmentation_wrapper(image, bbox, new_bboxes, prob, augmentation_func, func_changes_bbox, *args): """Applies _apply_bbox_augmentation with probability prob. Args: image: 3D uint8 Tensor. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. new_bboxes: 2D Tensor that is a list of the bboxes in the image after they have been altered by aug_func. These will only be changed when func_changes_bbox is set to true. Each bbox has 4 elements (min_y, min_x, max_y, max_x) of type float that are the normalized bbox coordinates between 0 and 1. prob: Float that is the probability of applying _apply_bbox_augmentation. augmentation_func: Augmentation function that will be applied to the subsection of image. func_changes_bbox: Boolean. Does augmentation_func return bbox in addition to image. *args: Additional parameters that will be passed into augmentation_func when it is called. Returns: A tuple. Fist element is a modified version of image, where the bbox location in the image will have augmentation_func applied to it if it is chosen to be called with probability `prob`. The second element is a Tensor of Tensors of length 4 that will contain the altered bbox after applying augmentation_func. """ should_apply_op = (np.random.rand() + prob >= 1) if func_changes_bbox: if should_apply_op: augmented_image, bbox = augmentation_func(image, bbox, *args) else: augmented_image, bbox = (image, bbox) else: if should_apply_op: augmented_image = _apply_bbox_augmentation( image, bbox, augmentation_func, *args) else: augmented_image = image new_bboxes = _concat_bbox(bbox, new_bboxes) return augmented_image.astype(np.uint8), new_bboxes
Applies _apply_bbox_augmentation with probability prob. Args: image: 3D uint8 Tensor. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. new_bboxes: 2D Tensor that is a list of the bboxes in the image after they have been altered by aug_func. These will only be changed when func_changes_bbox is set to true. Each bbox has 4 elements (min_y, min_x, max_y, max_x) of type float that are the normalized bbox coordinates between 0 and 1. prob: Float that is the probability of applying _apply_bbox_augmentation. augmentation_func: Augmentation function that will be applied to the subsection of image. func_changes_bbox: Boolean. Does augmentation_func return bbox in addition to image. *args: Additional parameters that will be passed into augmentation_func when it is called. Returns: A tuple. Fist element is a modified version of image, where the bbox location in the image will have augmentation_func applied to it if it is chosen to be called with probability `prob`. The second element is a Tensor of Tensors of length 4 that will contain the altered bbox after applying augmentation_func.
_apply_bbox_augmentation_wrapper
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _apply_multi_bbox_augmentation(image, bboxes, prob, aug_func, func_changes_bbox, *args): """Applies aug_func to the image for each bbox in bboxes. Args: image: 3D uint8 Tensor. bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox has 4 elements (min_y, min_x, max_y, max_x) of type float. prob: Float that is the probability of applying aug_func to a specific bounding box within the image. aug_func: Augmentation function that will be applied to the subsections of image indicated by the bbox values in bboxes. func_changes_bbox: Boolean. Does augmentation_func return bbox in addition to image. *args: Additional parameters that will be passed into augmentation_func when it is called. Returns: A modified version of image, where each bbox location in the image will have augmentation_func applied to it if it is chosen to be called with probability prob independently across all bboxes. Also the final bboxes are returned that will be unchanged if func_changes_bbox is set to false and if true, the new altered ones will be returned. """ # Will keep track of the new altered bboxes after aug_func is repeatedly # applied. The -1 values are a dummy value and this first Tensor will be # removed upon appending the first real bbox. new_bboxes = np.array(_INVALID_BOX) # If the bboxes are empty, then just give it _INVALID_BOX. The result # will be thrown away. bboxes = np.array((_INVALID_BOX)) if bboxes.size == 0 else bboxes assert bboxes.shape[1] == 4, "bboxes.shape[1] must be 4!!!!" # pylint:disable=g-long-lambda # pylint:disable=line-too-long wrapped_aug_func = lambda _image, bbox, _new_bboxes: _apply_bbox_augmentation_wrapper(_image, bbox, _new_bboxes, prob, aug_func, func_changes_bbox, *args) # pylint:enable=g-long-lambda # pylint:enable=line-too-long # Setup the while_loop. num_bboxes = bboxes.shape[0] # We loop until we go over all bboxes. idx = 0 # Counter for the while loop. # Conditional function when to end the loop once we go over all bboxes # images_and_bboxes contain (_image, _new_bboxes) def cond(_idx, _images_and_bboxes): return _idx < num_bboxes # Shuffle the bboxes so that the augmentation order is not deterministic if # we are not changing the bboxes with aug_func. # if not func_changes_bbox: # print(bboxes) # loop_bboxes = np.take(bboxes,np.random.permutation(bboxes.shape[0]),axis=0) # print(loop_bboxes) # else: # loop_bboxes = bboxes # we can not shuffle the bbox because it does not contain class information here loop_bboxes = deepcopy(bboxes) # Main function of while_loop where we repeatedly apply augmentation on the # bboxes in the image. # pylint:disable=g-long-lambda body = lambda _idx, _images_and_bboxes: [ _idx + 1, wrapped_aug_func(_images_and_bboxes[0], loop_bboxes[_idx], _images_and_bboxes[1])] while (cond(idx, (image, new_bboxes))): idx, (image, new_bboxes) = body(idx, (image, new_bboxes)) # Either return the altered bboxes or the original ones depending on if # we altered them in anyway. if func_changes_bbox: final_bboxes = new_bboxes else: final_bboxes = bboxes return image, final_bboxes
Applies aug_func to the image for each bbox in bboxes. Args: image: 3D uint8 Tensor. bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox has 4 elements (min_y, min_x, max_y, max_x) of type float. prob: Float that is the probability of applying aug_func to a specific bounding box within the image. aug_func: Augmentation function that will be applied to the subsections of image indicated by the bbox values in bboxes. func_changes_bbox: Boolean. Does augmentation_func return bbox in addition to image. *args: Additional parameters that will be passed into augmentation_func when it is called. Returns: A modified version of image, where each bbox location in the image will have augmentation_func applied to it if it is chosen to be called with probability prob independently across all bboxes. Also the final bboxes are returned that will be unchanged if func_changes_bbox is set to false and if true, the new altered ones will be returned.
_apply_multi_bbox_augmentation
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, aug_func, func_changes_bbox, *args): """Checks to be sure num bboxes > 0 before calling inner function.""" num_bboxes = len(bboxes) new_image = deepcopy(image) new_bboxes = deepcopy(bboxes) if num_bboxes != 0: new_image, new_bboxes = _apply_multi_bbox_augmentation( new_image, new_bboxes, prob, aug_func, func_changes_bbox, *args) return new_image, new_bboxes
Checks to be sure num bboxes > 0 before calling inner function.
_apply_multi_bbox_augmentation_wrapper
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def rotate_only_bboxes(image, bboxes, prob, degrees, replace): """Apply rotate to each bbox in the image with probability prob.""" func_changes_bbox = False prob = _scale_bbox_only_op_probability(prob) return _apply_multi_bbox_augmentation_wrapper( image, bboxes, prob, rotate, func_changes_bbox, degrees, replace)
Apply rotate to each bbox in the image with probability prob.
rotate_only_bboxes
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def shear_x_only_bboxes(image, bboxes, prob, level, replace): """Apply shear_x to each bbox in the image with probability prob.""" func_changes_bbox = False prob = _scale_bbox_only_op_probability(prob) return _apply_multi_bbox_augmentation_wrapper( image, bboxes, prob, shear_x, func_changes_bbox, level, replace)
Apply shear_x to each bbox in the image with probability prob.
shear_x_only_bboxes
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def shear_y_only_bboxes(image, bboxes, prob, level, replace): """Apply shear_y to each bbox in the image with probability prob.""" func_changes_bbox = False prob = _scale_bbox_only_op_probability(prob) return _apply_multi_bbox_augmentation_wrapper( image, bboxes, prob, shear_y, func_changes_bbox, level, replace)
Apply shear_y to each bbox in the image with probability prob.
shear_y_only_bboxes
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def translate_x_only_bboxes(image, bboxes, prob, pixels, replace): """Apply translate_x to each bbox in the image with probability prob.""" func_changes_bbox = False prob = _scale_bbox_only_op_probability(prob) return _apply_multi_bbox_augmentation_wrapper( image, bboxes, prob, translate_x, func_changes_bbox, pixels, replace)
Apply translate_x to each bbox in the image with probability prob.
translate_x_only_bboxes
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def translate_y_only_bboxes(image, bboxes, prob, pixels, replace): """Apply translate_y to each bbox in the image with probability prob.""" func_changes_bbox = False prob = _scale_bbox_only_op_probability(prob) return _apply_multi_bbox_augmentation_wrapper( image, bboxes, prob, translate_y, func_changes_bbox, pixels, replace)
Apply translate_y to each bbox in the image with probability prob.
translate_y_only_bboxes
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def flip_only_bboxes(image, bboxes, prob): """Apply flip_lr to each bbox in the image with probability prob.""" func_changes_bbox = False prob = _scale_bbox_only_op_probability(prob) return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, np.fliplr, func_changes_bbox)
Apply flip_lr to each bbox in the image with probability prob.
flip_only_bboxes
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def solarize_only_bboxes(image, bboxes, prob, threshold): """Apply solarize to each bbox in the image with probability prob.""" func_changes_bbox = False prob = _scale_bbox_only_op_probability(prob) return _apply_multi_bbox_augmentation_wrapper( image, bboxes, prob, solarize, func_changes_bbox, threshold)
Apply solarize to each bbox in the image with probability prob.
solarize_only_bboxes
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def equalize_only_bboxes(image, bboxes, prob): """Apply equalize to each bbox in the image with probability prob.""" func_changes_bbox = False prob = _scale_bbox_only_op_probability(prob) return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, equalize, func_changes_bbox)
Apply equalize to each bbox in the image with probability prob.
equalize_only_bboxes
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def cutout_only_bboxes(image, bboxes, prob, pad_size, replace): """Apply cutout to each bbox in the image with probability prob.""" func_changes_bbox = False prob = _scale_bbox_only_op_probability(prob) return _apply_multi_bbox_augmentation_wrapper( image, bboxes, prob, cutout, func_changes_bbox, pad_size, replace)
Apply cutout to each bbox in the image with probability prob.
cutout_only_bboxes
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _rotate_bbox(bbox, image_height, image_width, degrees): """Rotates the bbox coordinated by degrees. Args: bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. image_height: Int, height of the image. image_width: Int, height of the image. degrees: Float, a scalar angle in degrees to rotate all images by. If degrees is positive the image will be rotated clockwise otherwise it will be rotated counterclockwise. Returns: A tensor of the same shape as bbox, but now with the rotated coordinates. """ image_height, image_width = (float(image_height), float(image_width)) # Convert from degrees to radians. degrees_to_radians = math.pi / 180.0 radians = degrees * degrees_to_radians # Translate the bbox to the center of the image and turn the normalized 0-1 # coordinates to absolute pixel locations. # Y coordinates are made negative as the y axis of images goes down with # increasing pixel values, so we negate to make sure x axis and y axis points # are in the traditionally positive direction. min_y = -int(image_height * (bbox[0] - 0.5)) min_x = int(image_width * (bbox[1] - 0.5)) max_y = -int(image_height * (bbox[2] - 0.5)) max_x = int(image_width * (bbox[3] - 0.5)) coordinates = np.stack([[min_y, min_x], [min_y, max_x], [max_y, min_x], [max_y, max_x]]).astype(np.float32) # Rotate the coordinates according to the rotation matrix clockwise if # radians is positive, else negative rotation_matrix = np.stack([[math.cos(radians), math.sin(radians)], [-math.sin(radians), math.cos(radians)]]) new_coords = np.matmul(rotation_matrix, np.transpose(coordinates)).astype(np.int32) # Find min/max values and convert them back to normalized 0-1 floats. min_y = -(float(np.max(new_coords[0, :])) / image_height - 0.5) min_x = float(np.min(new_coords[1, :])) / image_width + 0.5 max_y = -(float(np.min(new_coords[0, :])) / image_height - 0.5) max_x = float(np.max(new_coords[1, :])) / image_width + 0.5 # Clip the bboxes to be sure the fall between [0, 1]. min_y, min_x, max_y, max_x = _clip_bbox(min_y, min_x, max_y, max_x) min_y, min_x, max_y, max_x = _check_bbox_area(min_y, min_x, max_y, max_x) return np.stack([min_y, min_x, max_y, max_x])
Rotates the bbox coordinated by degrees. Args: bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. image_height: Int, height of the image. image_width: Int, height of the image. degrees: Float, a scalar angle in degrees to rotate all images by. If degrees is positive the image will be rotated clockwise otherwise it will be rotated counterclockwise. Returns: A tensor of the same shape as bbox, but now with the rotated coordinates.
_rotate_bbox
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def translate_x(image, pixels, replace): """Equivalent of PIL Translate in X dimension.""" image = Image.fromarray(wrap(image)) image = image.transform(image.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0)) return unwrap(np.array(image), replace)
Equivalent of PIL Translate in X dimension.
translate_x
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def translate_y(image, pixels, replace): """Equivalent of PIL Translate in Y dimension.""" image = Image.fromarray(wrap(image)) image = image.transform(image.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels)) return unwrap(np.array(image), replace)
Equivalent of PIL Translate in Y dimension.
translate_y
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _shift_bbox(bbox, image_height, image_width, pixels, shift_horizontal): """Shifts the bbox coordinates by pixels. Args: bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. image_height: Int, height of the image. image_width: Int, width of the image. pixels: An int. How many pixels to shift the bbox. shift_horizontal: Boolean. If true then shift in X dimension else shift in Y dimension. Returns: A tensor of the same shape as bbox, but now with the shifted coordinates. """ pixels = int(pixels) # Convert bbox to integer pixel locations. min_y = int(float(image_height) * bbox[0]) min_x = int(float(image_width) * bbox[1]) max_y = int(float(image_height) * bbox[2]) max_x = int(float(image_width) * bbox[3]) if shift_horizontal: min_x = np.maximum(0, min_x - pixels) max_x = np.minimum(image_width, max_x - pixels) else: min_y = np.maximum(0, min_y - pixels) max_y = np.minimum(image_height, max_y - pixels) # Convert bbox back to floats. min_y = float(min_y) / float(image_height) min_x = float(min_x) / float(image_width) max_y = float(max_y) / float(image_height) max_x = float(max_x) / float(image_width) # Clip the bboxes to be sure the fall between [0, 1]. min_y, min_x, max_y, max_x = _clip_bbox(min_y, min_x, max_y, max_x) min_y, min_x, max_y, max_x = _check_bbox_area(min_y, min_x, max_y, max_x) return np.stack([min_y, min_x, max_y, max_x])
Shifts the bbox coordinates by pixels. Args: bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. image_height: Int, height of the image. image_width: Int, width of the image. pixels: An int. How many pixels to shift the bbox. shift_horizontal: Boolean. If true then shift in X dimension else shift in Y dimension. Returns: A tensor of the same shape as bbox, but now with the shifted coordinates.
_shift_bbox
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def translate_bbox(image, bboxes, pixels, replace, shift_horizontal): """Equivalent of PIL Translate in X/Y dimension that shifts image and bbox. Args: image: 3D uint8 Tensor. bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox has 4 elements (min_y, min_x, max_y, max_x) of type float with values between [0, 1]. pixels: An int. How many pixels to shift the image and bboxes replace: A one or three value 1D tensor to fill empty pixels. shift_horizontal: Boolean. If true then shift in X dimension else shift in Y dimension. Returns: A tuple containing a 3D uint8 Tensor that will be the result of translating image by pixels. The second element of the tuple is bboxes, where now the coordinates will be shifted to reflect the shifted image. """ if shift_horizontal: image = translate_x(image, pixels, replace) else: image = translate_y(image, pixels, replace) # Convert bbox coordinates to pixel values. image_height, image_width = image.shape[0], image.shape[1] # pylint:disable=g-long-lambda wrapped_shift_bbox = lambda bbox: _shift_bbox(bbox, image_height, image_width, pixels, shift_horizontal) # pylint:enable=g-long-lambda new_bboxes = deepcopy(bboxes) num_bboxes = len(bboxes) for idx in range(num_bboxes): new_bboxes[idx] = wrapped_shift_bbox(bboxes[idx]) return image.astype(np.uint8), new_bboxes
Equivalent of PIL Translate in X/Y dimension that shifts image and bbox. Args: image: 3D uint8 Tensor. bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox has 4 elements (min_y, min_x, max_y, max_x) of type float with values between [0, 1]. pixels: An int. How many pixels to shift the image and bboxes replace: A one or three value 1D tensor to fill empty pixels. shift_horizontal: Boolean. If true then shift in X dimension else shift in Y dimension. Returns: A tuple containing a 3D uint8 Tensor that will be the result of translating image by pixels. The second element of the tuple is bboxes, where now the coordinates will be shifted to reflect the shifted image.
translate_bbox
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def shear_x(image, level, replace): """Equivalent of PIL Shearing in X dimension.""" # Shear parallel to x axis is a projective transform # with a matrix form of: # [1 level # 0 1]. image = Image.fromarray(wrap(image)) image = image.transform(image.size, Image.AFFINE, (1, level, 0, 0, 1, 0)) return unwrap(np.array(image), replace)
Equivalent of PIL Shearing in X dimension.
shear_x
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def shear_y(image, level, replace): """Equivalent of PIL Shearing in Y dimension.""" # Shear parallel to y axis is a projective transform # with a matrix form of: # [1 0 # level 1]. image = Image.fromarray(wrap(image)) image = image.transform(image.size, Image.AFFINE, (1, 0, 0, level, 1, 0)) return unwrap(np.array(image), replace)
Equivalent of PIL Shearing in Y dimension.
shear_y
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _shear_bbox(bbox, image_height, image_width, level, shear_horizontal): """Shifts the bbox according to how the image was sheared. Args: bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. image_height: Int, height of the image. image_width: Int, height of the image. level: Float. How much to shear the image. shear_horizontal: If true then shear in X dimension else shear in the Y dimension. Returns: A tensor of the same shape as bbox, but now with the shifted coordinates. """ image_height, image_width = (float(image_height), float(image_width)) # Change bbox coordinates to be pixels. min_y = int(image_height * bbox[0]) min_x = int(image_width * bbox[1]) max_y = int(image_height * bbox[2]) max_x = int(image_width * bbox[3]) coordinates = np.stack( [[min_y, min_x], [min_y, max_x], [max_y, min_x], [max_y, max_x]]) coordinates = coordinates.astype(np.float32) # Shear the coordinates according to the translation matrix. if shear_horizontal: translation_matrix = np.stack([[1, 0], [-level, 1]]) else: translation_matrix = np.stack([[1, -level], [0, 1]]) translation_matrix = translation_matrix.astype(np.float32) new_coords = np.matmul(translation_matrix, np.transpose(coordinates)).astype(np.int32) # Find min/max values and convert them back to floats. min_y = float(np.min(new_coords[0, :])) / image_height min_x = float(np.min(new_coords[1, :])) / image_width max_y = float(np.max(new_coords[0, :])) / image_height max_x = float(np.max(new_coords[1, :])) / image_width # Clip the bboxes to be sure the fall between [0, 1]. min_y, min_x, max_y, max_x = _clip_bbox(min_y, min_x, max_y, max_x) min_y, min_x, max_y, max_x = _check_bbox_area(min_y, min_x, max_y, max_x) return np.stack([min_y, min_x, max_y, max_x])
Shifts the bbox according to how the image was sheared. Args: bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. image_height: Int, height of the image. image_width: Int, height of the image. level: Float. How much to shear the image. shear_horizontal: If true then shear in X dimension else shear in the Y dimension. Returns: A tensor of the same shape as bbox, but now with the shifted coordinates.
_shear_bbox
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def shear_with_bboxes(image, bboxes, level, replace, shear_horizontal): """Applies Shear Transformation to the image and shifts the bboxes. Args: image: 3D uint8 Tensor. bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox has 4 elements (min_y, min_x, max_y, max_x) of type float with values between [0, 1]. level: Float. How much to shear the image. This value will be between -0.3 to 0.3. replace: A one or three value 1D tensor to fill empty pixels. shear_horizontal: Boolean. If true then shear in X dimension else shear in the Y dimension. Returns: A tuple containing a 3D uint8 Tensor that will be the result of shearing image by level. The second element of the tuple is bboxes, where now the coordinates will be shifted to reflect the sheared image. """ if shear_horizontal: image = shear_x(image, level, replace) else: image = shear_y(image, level, replace) # Convert bbox coordinates to pixel values. image_height, image_width = image.shape[:2] # pylint:disable=g-long-lambda wrapped_shear_bbox = lambda bbox: _shear_bbox(bbox, image_height, image_width, level, shear_horizontal) # pylint:enable=g-long-lambda new_bboxes = deepcopy(bboxes) num_bboxes = len(bboxes) for idx in range(num_bboxes): new_bboxes[idx] = wrapped_shear_bbox(bboxes[idx]) return image.astype(np.uint8), new_bboxes
Applies Shear Transformation to the image and shifts the bboxes. Args: image: 3D uint8 Tensor. bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox has 4 elements (min_y, min_x, max_y, max_x) of type float with values between [0, 1]. level: Float. How much to shear the image. This value will be between -0.3 to 0.3. replace: A one or three value 1D tensor to fill empty pixels. shear_horizontal: Boolean. If true then shear in X dimension else shear in the Y dimension. Returns: A tuple containing a 3D uint8 Tensor that will be the result of shearing image by level. The second element of the tuple is bboxes, where now the coordinates will be shifted to reflect the sheared image.
shear_with_bboxes
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def autocontrast(image): """Implements Autocontrast function from PIL. Args: image: A 3D uint8 tensor. Returns: The image after it has had autocontrast applied to it and will be of type uint8. """ def scale_channel(image): """Scale the 2D image using the autocontrast rule.""" # A possibly cheaper version can be done using cumsum/unique_with_counts # over the histogram values, rather than iterating over the entire image. # to compute mins and maxes. lo = float(np.min(image)) hi = float(np.max(image)) # Scale the image, making the lowest value 0 and the highest value 255. def scale_values(im): scale = 255.0 / (hi - lo) offset = -lo * scale im = im.astype(np.float32) * scale + offset img = np.clip(im, a_min=0, a_max=255.0) return im.astype(np.uint8) result = scale_values(image) if hi > lo else image return result # Assumes RGB for now. Scales each channel independently # and then stacks the result. s1 = scale_channel(image[:, :, 0]) s2 = scale_channel(image[:, :, 1]) s3 = scale_channel(image[:, :, 2]) image = np.stack([s1, s2, s3], 2) return image
Implements Autocontrast function from PIL. Args: image: A 3D uint8 tensor. Returns: The image after it has had autocontrast applied to it and will be of type uint8.
autocontrast
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def scale_channel(image): """Scale the 2D image using the autocontrast rule.""" # A possibly cheaper version can be done using cumsum/unique_with_counts # over the histogram values, rather than iterating over the entire image. # to compute mins and maxes. lo = float(np.min(image)) hi = float(np.max(image)) # Scale the image, making the lowest value 0 and the highest value 255. def scale_values(im): scale = 255.0 / (hi - lo) offset = -lo * scale im = im.astype(np.float32) * scale + offset img = np.clip(im, a_min=0, a_max=255.0) return im.astype(np.uint8) result = scale_values(image) if hi > lo else image return result
Scale the 2D image using the autocontrast rule.
scale_channel
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def equalize(image): """Implements Equalize function from PIL using.""" def scale_channel(im, c): """Scale the data in the channel to implement equalize.""" im = im[:, :, c].astype(np.int32) # Compute the histogram of the image channel. histo, _ = np.histogram(im, range=[0, 255], bins=256) # For the purposes of computing the step, filter out the nonzeros. nonzero = np.where(np.not_equal(histo, 0)) nonzero_histo = np.reshape(np.take(histo, nonzero), [-1]) step = (np.sum(nonzero_histo) - nonzero_histo[-1]) // 255 def build_lut(histo, step): # Compute the cumulative sum, shifting by step // 2 # and then normalization by step. lut = (np.cumsum(histo) + (step // 2)) // step # Shift lut, prepending with 0. lut = np.concatenate([[0], lut[:-1]], 0) # Clip the counts to be in range. This is done # in the C code for image.point. return np.clip(lut, a_min=0, a_max=255).astype(np.uint8) # If step is zero, return the original image. Otherwise, build # lut from the full histogram and step and then index from it. if step == 0: result = im else: result = np.take(build_lut(histo, step), im) return result.astype(np.uint8) # Assumes RGB for now. Scales each channel independently # and then stacks the result. s1 = scale_channel(image, 0) s2 = scale_channel(image, 1) s3 = scale_channel(image, 2) image = np.stack([s1, s2, s3], 2) return image
Implements Equalize function from PIL using.
equalize
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def scale_channel(im, c): """Scale the data in the channel to implement equalize.""" im = im[:, :, c].astype(np.int32) # Compute the histogram of the image channel. histo, _ = np.histogram(im, range=[0, 255], bins=256) # For the purposes of computing the step, filter out the nonzeros. nonzero = np.where(np.not_equal(histo, 0)) nonzero_histo = np.reshape(np.take(histo, nonzero), [-1]) step = (np.sum(nonzero_histo) - nonzero_histo[-1]) // 255 def build_lut(histo, step): # Compute the cumulative sum, shifting by step // 2 # and then normalization by step. lut = (np.cumsum(histo) + (step // 2)) // step # Shift lut, prepending with 0. lut = np.concatenate([[0], lut[:-1]], 0) # Clip the counts to be in range. This is done # in the C code for image.point. return np.clip(lut, a_min=0, a_max=255).astype(np.uint8) # If step is zero, return the original image. Otherwise, build # lut from the full histogram and step and then index from it. if step == 0: result = im else: result = np.take(build_lut(histo, step), im) return result.astype(np.uint8)
Scale the data in the channel to implement equalize.
scale_channel
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def wrap(image): """Returns 'image' with an extra channel set to all 1s.""" shape = image.shape extended_channel = 255 * np.ones([shape[0], shape[1], 1], image.dtype) extended = np.concatenate([image, extended_channel], 2).astype(image.dtype) return extended
Returns 'image' with an extra channel set to all 1s.
wrap
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def unwrap(image, replace): """Unwraps an image produced by wrap. Where there is a 0 in the last channel for every spatial position, the rest of the three channels in that spatial dimension are grayed (set to 128). Operations like translate and shear on a wrapped Tensor will leave 0s in empty locations. Some transformations look at the intensity of values to do preprocessing, and we want these empty pixels to assume the 'average' value, rather than pure black. Args: image: A 3D Image Tensor with 4 channels. replace: A one or three value 1D tensor to fill empty pixels. Returns: image: A 3D image Tensor with 3 channels. """ image_shape = image.shape # Flatten the spatial dimensions. flattened_image = np.reshape(image, [-1, image_shape[2]]) # Find all pixels where the last channel is zero. alpha_channel = flattened_image[:, 3] replace = np.concatenate([replace, np.ones([1], image.dtype)], 0) # Where they are zero, fill them in with 'replace'. alpha_channel = np.reshape(alpha_channel, (-1, 1)) alpha_channel = np.tile(alpha_channel, reps=(1, flattened_image.shape[1])) flattened_image = np.where( np.equal(alpha_channel, 0), np.ones_like( flattened_image, dtype=image.dtype) * replace, flattened_image) image = np.reshape(flattened_image, image_shape) image = image[:, :, :3] return image.astype(np.uint8)
Unwraps an image produced by wrap. Where there is a 0 in the last channel for every spatial position, the rest of the three channels in that spatial dimension are grayed (set to 128). Operations like translate and shear on a wrapped Tensor will leave 0s in empty locations. Some transformations look at the intensity of values to do preprocessing, and we want these empty pixels to assume the 'average' value, rather than pure black. Args: image: A 3D Image Tensor with 4 channels. replace: A one or three value 1D tensor to fill empty pixels. Returns: image: A 3D image Tensor with 3 channels.
unwrap
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _cutout_inside_bbox(image, bbox, pad_fraction): """Generates cutout mask and the mean pixel value of the bbox. First a location is randomly chosen within the image as the center where the cutout mask will be applied. Note this can be towards the boundaries of the image, so the full cutout mask may not be applied. Args: image: 3D uint8 Tensor. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. pad_fraction: Float that specifies how large the cutout mask should be in in reference to the size of the original bbox. If pad_fraction is 0.25, then the cutout mask will be of shape (0.25 * bbox height, 0.25 * bbox width). Returns: A tuple. Fist element is a tensor of the same shape as image where each element is either a 1 or 0 that is used to determine where the image will have cutout applied. The second element is the mean of the pixels in the image where the bbox is located. mask value: [0,1] """ image_height, image_width = image.shape[0], image.shape[1] # Transform from shape [1, 4] to [4]. bbox = np.squeeze(bbox) min_y = int(float(image_height) * bbox[0]) min_x = int(float(image_width) * bbox[1]) max_y = int(float(image_height) * bbox[2]) max_x = int(float(image_width) * bbox[3]) # Calculate the mean pixel values in the bounding box, which will be used # to fill the cutout region. mean = np.mean(image[min_y:max_y + 1, min_x:max_x + 1], axis=(0, 1)) # Cutout mask will be size pad_size_heigh * 2 by pad_size_width * 2 if the # region lies entirely within the bbox. box_height = max_y - min_y + 1 box_width = max_x - min_x + 1 pad_size_height = int(pad_fraction * (box_height / 2)) pad_size_width = int(pad_fraction * (box_width / 2)) # Sample the center location in the image where the zero mask will be applied. cutout_center_height = np.random.randint(min_y, max_y + 1, dtype=np.int32) cutout_center_width = np.random.randint(min_x, max_x + 1, dtype=np.int32) lower_pad = np.maximum(0, cutout_center_height - pad_size_height) upper_pad = np.maximum( 0, image_height - cutout_center_height - pad_size_height) left_pad = np.maximum(0, cutout_center_width - pad_size_width) right_pad = np.maximum(0, image_width - cutout_center_width - pad_size_width) cutout_shape = [ image_height - (lower_pad + upper_pad), image_width - (left_pad + right_pad) ] padding_dims = [[lower_pad, upper_pad], [left_pad, right_pad]] mask = np.pad(np.zeros( cutout_shape, dtype=image.dtype), padding_dims, 'constant', constant_values=1) mask = np.expand_dims(mask, 2) mask = np.tile(mask, [1, 1, 3]) return mask, mean
Generates cutout mask and the mean pixel value of the bbox. First a location is randomly chosen within the image as the center where the cutout mask will be applied. Note this can be towards the boundaries of the image, so the full cutout mask may not be applied. Args: image: 3D uint8 Tensor. bbox: 1D Tensor that has 4 elements (min_y, min_x, max_y, max_x) of type float that represents the normalized coordinates between 0 and 1. pad_fraction: Float that specifies how large the cutout mask should be in in reference to the size of the original bbox. If pad_fraction is 0.25, then the cutout mask will be of shape (0.25 * bbox height, 0.25 * bbox width). Returns: A tuple. Fist element is a tensor of the same shape as image where each element is either a 1 or 0 that is used to determine where the image will have cutout applied. The second element is the mean of the pixels in the image where the bbox is located. mask value: [0,1]
_cutout_inside_bbox
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def bbox_cutout(image, bboxes, pad_fraction, replace_with_mean): """Applies cutout to the image according to bbox information. This is a cutout variant that using bbox information to make more informed decisions on where to place the cutout mask. Args: image: 3D uint8 Tensor. bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox has 4 elements (min_y, min_x, max_y, max_x) of type float with values between [0, 1]. pad_fraction: Float that specifies how large the cutout mask should be in in reference to the size of the original bbox. If pad_fraction is 0.25, then the cutout mask will be of shape (0.25 * bbox height, 0.25 * bbox width). replace_with_mean: Boolean that specified what value should be filled in where the cutout mask is applied. Since the incoming image will be of uint8 and will not have had any mean normalization applied, by default we set the value to be 128. If replace_with_mean is True then we find the mean pixel values across the channel dimension and use those to fill in where the cutout mask is applied. Returns: A tuple. First element is a tensor of the same shape as image that has cutout applied to it. Second element is the bboxes that were passed in that will be unchanged. """ def apply_bbox_cutout(image, bboxes, pad_fraction): """Applies cutout to a single bounding box within image.""" # Choose a single bounding box to apply cutout to. random_index = np.random.randint(0, bboxes.shape[0], dtype=np.int32) # Select the corresponding bbox and apply cutout. chosen_bbox = np.take(bboxes, random_index, axis=0) mask, mean = _cutout_inside_bbox(image, chosen_bbox, pad_fraction) # When applying cutout we either set the pixel value to 128 or to the mean # value inside the bbox. replace = mean if replace_with_mean else [128] * 3 # Apply the cutout mask to the image. Where the mask is 0 we fill it with # `replace`. image = np.where( np.equal(mask, 0), np.ones_like( image, dtype=image.dtype) * replace, image).astype(image.dtype) return image # Check to see if there are boxes, if so then apply boxcutout. if len(bboxes) != 0: image = apply_bbox_cutout(image, bboxes, pad_fraction) return image, bboxes
Applies cutout to the image according to bbox information. This is a cutout variant that using bbox information to make more informed decisions on where to place the cutout mask. Args: image: 3D uint8 Tensor. bboxes: 2D Tensor that is a list of the bboxes in the image. Each bbox has 4 elements (min_y, min_x, max_y, max_x) of type float with values between [0, 1]. pad_fraction: Float that specifies how large the cutout mask should be in in reference to the size of the original bbox. If pad_fraction is 0.25, then the cutout mask will be of shape (0.25 * bbox height, 0.25 * bbox width). replace_with_mean: Boolean that specified what value should be filled in where the cutout mask is applied. Since the incoming image will be of uint8 and will not have had any mean normalization applied, by default we set the value to be 128. If replace_with_mean is True then we find the mean pixel values across the channel dimension and use those to fill in where the cutout mask is applied. Returns: A tuple. First element is a tensor of the same shape as image that has cutout applied to it. Second element is the bboxes that were passed in that will be unchanged.
bbox_cutout
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def apply_bbox_cutout(image, bboxes, pad_fraction): """Applies cutout to a single bounding box within image.""" # Choose a single bounding box to apply cutout to. random_index = np.random.randint(0, bboxes.shape[0], dtype=np.int32) # Select the corresponding bbox and apply cutout. chosen_bbox = np.take(bboxes, random_index, axis=0) mask, mean = _cutout_inside_bbox(image, chosen_bbox, pad_fraction) # When applying cutout we either set the pixel value to 128 or to the mean # value inside the bbox. replace = mean if replace_with_mean else [128] * 3 # Apply the cutout mask to the image. Where the mask is 0 we fill it with # `replace`. image = np.where( np.equal(mask, 0), np.ones_like( image, dtype=image.dtype) * replace, image).astype(image.dtype) return image
Applies cutout to a single bounding box within image.
apply_bbox_cutout
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _randomly_negate_tensor(tensor): """With 50% prob turn the tensor negative.""" should_flip = np.floor(np.random.rand() + 0.5) >= 1 final_tensor = tensor if should_flip else -tensor return final_tensor
With 50% prob turn the tensor negative.
_randomly_negate_tensor
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _shrink_level_to_arg(level): """Converts level to ratio by which we shrink the image content.""" if level == 0: return (1.0, ) # if level is zero, do not shrink the image # Maximum shrinking ratio is 2.9. level = 2. / (_MAX_LEVEL / level) + 0.9 return (level, )
Converts level to ratio by which we shrink the image content.
_shrink_level_to_arg
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def bbox_wrapper(func): """Adds a bboxes function argument to func and returns unchanged bboxes.""" def wrapper(images, bboxes, *args, **kwargs): return (func(images, *args, **kwargs), bboxes) return wrapper
Adds a bboxes function argument to func and returns unchanged bboxes.
bbox_wrapper
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _parse_policy_info(name, prob, level, replace_value, augmentation_hparams): """Return the function that corresponds to `name` and update `level` param.""" func = NAME_TO_FUNC[name] args = level_to_arg(augmentation_hparams)[name](level) # Check to see if prob is passed into function. This is used for operations # where we alter bboxes independently. # pytype:disable=wrong-arg-types if 'prob' in inspect.getfullargspec(func)[0]: args = tuple([prob] + list(args)) # pytype:enable=wrong-arg-types # Add in replace arg if it is required for the function that is being called. if 'replace' in inspect.getfullargspec(func)[0]: # Make sure replace is the final argument assert 'replace' == inspect.getfullargspec(func)[0][-1] args = tuple(list(args) + [replace_value]) # Add bboxes as the second positional argument for the function if it does # not already exist. if 'bboxes' not in inspect.getfullargspec(func)[0]: func = bbox_wrapper(func) return (func, prob, args)
Return the function that corresponds to `name` and update `level` param.
_parse_policy_info
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def _apply_func_with_prob(func, image, args, prob, bboxes): """Apply `func` to image w/ `args` as input with probability `prob`.""" assert isinstance(args, tuple) assert 'bboxes' == inspect.getfullargspec(func)[0][1] # If prob is a function argument, then this randomness is being handled # inside the function, so make sure it is always called. if 'prob' in inspect.getfullargspec(func)[0]: prob = 1.0 # Apply the function with probability `prob`. should_apply_op = np.floor(np.random.rand() + 0.5) >= 1 if should_apply_op: augmented_image, augmented_bboxes = func(image, bboxes, *args) else: augmented_image, augmented_bboxes = (image, bboxes) return augmented_image, augmented_bboxes
Apply `func` to image w/ `args` as input with probability `prob`.
_apply_func_with_prob
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def select_and_apply_random_policy(policies, image, bboxes): """Select a random policy from `policies` and apply it to `image`.""" policy_to_select = np.random.randint(0, len(policies), dtype=np.int32) # policy_to_select = 6 # for test for (i, policy) in enumerate(policies): if i == policy_to_select: image, bboxes = policy(image, bboxes) return (image, bboxes)
Select a random policy from `policies` and apply it to `image`.
select_and_apply_random_policy
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def build_and_apply_nas_policy(policies, image, bboxes, augmentation_hparams): """Build a policy from the given policies passed in and apply to image. Args: policies: list of lists of tuples in the form `(func, prob, level)`, `func` is a string name of the augmentation function, `prob` is the probability of applying the `func` operation, `level` is the input argument for `func`. image: numpy array that the resulting policy will be applied to. bboxes: augmentation_hparams: Hparams associated with the NAS learned policy. Returns: A version of image that now has data augmentation applied to it based on the `policies` pass into the function. Additionally, returns bboxes if a value for them is passed in that is not None """ replace_value = [128, 128, 128] # func is the string name of the augmentation function, prob is the # probability of applying the operation and level is the parameter associated # tf_policies are functions that take in an image and return an augmented # image. tf_policies = [] for policy in policies: tf_policy = [] # Link string name to the correct python function and make sure the correct # argument is passed into that function. for policy_info in policy: policy_info = list( policy_info) + [replace_value, augmentation_hparams] tf_policy.append(_parse_policy_info(*policy_info)) # Now build the tf policy that will apply the augmentation procedue # on image. def make_final_policy(tf_policy_): def final_policy(image_, bboxes_): for func, prob, args in tf_policy_: image_, bboxes_ = _apply_func_with_prob(func, image_, args, prob, bboxes_) return image_, bboxes_ return final_policy tf_policies.append(make_final_policy(tf_policy)) augmented_images, augmented_bboxes = select_and_apply_random_policy( tf_policies, image, bboxes) # If no bounding boxes were specified, then just return the images. return (augmented_images, augmented_bboxes)
Build a policy from the given policies passed in and apply to image. Args: policies: list of lists of tuples in the form `(func, prob, level)`, `func` is a string name of the augmentation function, `prob` is the probability of applying the `func` operation, `level` is the input argument for `func`. image: numpy array that the resulting policy will be applied to. bboxes: augmentation_hparams: Hparams associated with the NAS learned policy. Returns: A version of image that now has data augmentation applied to it based on the `policies` pass into the function. Additionally, returns bboxes if a value for them is passed in that is not None
build_and_apply_nas_policy
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def distort_image_with_autoaugment(image, bboxes, augmentation_name): """Applies the AutoAugment policy to `image` and `bboxes`. Args: image: `Tensor` of shape [height, width, 3] representing an image. bboxes: `Tensor` of shape [N, 4] representing ground truth boxes that are normalized between [0, 1]. augmentation_name: The name of the AutoAugment policy to use. The available options are `v0`, `v1`, `v2`, `v3` and `test`. `v0` is the policy used for all of the results in the paper and was found to achieve the best results on the COCO dataset. `v1`, `v2` and `v3` are additional good policies found on the COCO dataset that have slight variation in what operations were used during the search procedure along with how many operations are applied in parallel to a single image (2 vs 3). Returns: A tuple containing the augmented versions of `image` and `bboxes`. """ available_policies = { 'v0': policy_v0, 'v1': policy_v1, 'v2': policy_v2, 'v3': policy_v3, 'test': policy_vtest } if augmentation_name not in available_policies: raise ValueError('Invalid augmentation_name: {}'.format( augmentation_name)) policy = available_policies[augmentation_name]() augmentation_hparams = {} return build_and_apply_nas_policy(policy, image, bboxes, augmentation_hparams)
Applies the AutoAugment policy to `image` and `bboxes`. Args: image: `Tensor` of shape [height, width, 3] representing an image. bboxes: `Tensor` of shape [N, 4] representing ground truth boxes that are normalized between [0, 1]. augmentation_name: The name of the AutoAugment policy to use. The available options are `v0`, `v1`, `v2`, `v3` and `test`. `v0` is the policy used for all of the results in the paper and was found to achieve the best results on the COCO dataset. `v1`, `v2` and `v3` are additional good policies found on the COCO dataset that have slight variation in what operations were used during the search procedure along with how many operations are applied in parallel to a single image (2 vs 3). Returns: A tuple containing the augmented versions of `image` and `bboxes`.
distort_image_with_autoaugment
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/autoaugment_utils.py
Apache-2.0
def __call__(self, sample, context=None): """ Process a sample. Args: sample (dict): a dict of sample, eg: {'image':xx, 'label': xxx} context (dict): info about this sample processing Returns: result (dict): a processed sample """ if isinstance(sample, Sequence): for i in range(len(sample)): sample[i] = self.apply(sample[i], context) else: sample = self.apply(sample, context) return sample
Process a sample. Args: sample (dict): a dict of sample, eg: {'image':xx, 'label': xxx} context (dict): info about this sample processing Returns: result (dict): a processed sample
__call__
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/operators.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/operators.py
Apache-2.0
def apply(self, sample, context=None): """ load image if 'im_file' field is not empty but 'image' is""" if 'image' not in sample: with open(sample['im_file'], 'rb') as f: sample['image'] = f.read() sample.pop('im_file') im = sample['image'] data = np.frombuffer(im, dtype='uint8') im = cv2.imdecode(data, 1) # BGR mode, but need RGB mode if 'keep_ori_im' in sample and sample['keep_ori_im']: sample['ori_image'] = im im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) sample['image'] = im if 'h' not in sample: sample['h'] = im.shape[0] elif sample['h'] != im.shape[0]: logger.warning( "The actual image height: {} is not equal to the " "height: {} in annotation, and update sample['h'] by actual " "image height.".format(im.shape[0], sample['h'])) sample['h'] = im.shape[0] if 'w' not in sample: sample['w'] = im.shape[1] elif sample['w'] != im.shape[1]: logger.warning( "The actual image width: {} is not equal to the " "width: {} in annotation, and update sample['w'] by actual " "image width.".format(im.shape[1], sample['w'])) sample['w'] = im.shape[1] sample['im_shape'] = np.array(im.shape[:2], dtype=np.float32) sample['scale_factor'] = np.array([1., 1.], dtype=np.float32) return sample
load image if 'im_file' field is not empty but 'image' is
apply
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/operators.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/operators.py
Apache-2.0
def __init__(self, mean=[0.485, 0.456, 0.406], std=[1, 1, 1], is_scale=True): """ Args: mean (list): the pixel mean std (list): the pixel variance """ super(NormalizeImage, self).__init__() self.mean = mean self.std = std self.is_scale = is_scale if not (isinstance(self.mean, list) and isinstance(self.std, list) and isinstance(self.is_scale, bool)): raise TypeError("{}: input type is invalid.".format(self)) from functools import reduce if reduce(lambda x, y: x * y, self.std) == 0: raise ValueError('{}: std is invalid!'.format(self))
Args: mean (list): the pixel mean std (list): the pixel variance
__init__
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/operators.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/operators.py
Apache-2.0
def apply(self, sample, context=None): """Normalize the image. Operators: 1.(optional) Scale the image to [0,1] 2. Each pixel minus mean and is divided by std """ im = sample['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 sample['image'] = im return sample
Normalize the image. Operators: 1.(optional) Scale the image to [0,1] 2. Each pixel minus mean and is divided by std
apply
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/operators.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/dataset/transform/operators.py
Apache-2.0
def get_infer_results(outs, catid, bias=0): """ Get result at the stage of inference. The output format is dictionary containing bbox or mask result. For example, bbox result is a list and each element contains image_id, category_id, bbox and score. """ if outs is None or len(outs) == 0: raise ValueError( 'The number of valid detection result if zero. Please use reasonable model and check input data.' ) im_id = outs['im_id'] infer_res = {} if 'bbox' in outs: if len(outs['bbox']) > 0 and len(outs['bbox'][0]) > 6: infer_res['bbox'] = get_det_poly_res( outs['bbox'], outs['bbox_num'], im_id, catid, bias=bias) else: infer_res['bbox'] = get_det_res( outs['bbox'], outs['bbox_num'], im_id, catid, bias=bias) if 'mask' in outs: # mask post process infer_res['mask'] = get_seg_res(outs['mask'], outs['bbox'], outs['bbox_num'], im_id, catid) if 'segm' in outs: infer_res['segm'] = get_solov2_segm_res(outs, im_id, catid) if 'keypoint' in outs: infer_res['keypoint'] = get_keypoint_res(outs, im_id) outs['bbox_num'] = [len(infer_res['keypoint'])] return infer_res
Get result at the stage of inference. The output format is dictionary containing bbox or mask result. For example, bbox result is a list and each element contains image_id, category_id, bbox and score.
get_infer_results
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/metrics/coco_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/metrics/coco_utils.py
Apache-2.0
def cocoapi_eval(jsonfile, style, coco_gt=None, anno_file=None, max_dets=(100, 300, 1000), classwise=False, sigmas=None, use_area=True): """ Args: jsonfile (str): Evaluation json file, eg: bbox.json, mask.json. style (str): COCOeval style, can be `bbox` , `segm` , `proposal`, `keypoints` and `keypoints_crowd`. coco_gt (str): Whether to load COCOAPI through anno_file, eg: coco_gt = COCO(anno_file) anno_file (str): COCO annotations file. max_dets (tuple): COCO evaluation maxDets. classwise (bool): Whether per-category AP and draw P-R Curve or not. sigmas (nparray): keypoint labelling sigmas. use_area (bool): If gt annotations (eg. CrowdPose, AIC) do not have 'area', please set use_area=False. """ assert coco_gt != None or anno_file != None if style == 'keypoints_crowd': #please install xtcocotools==1.6 from xtcocotools.coco import COCO from xtcocotools.cocoeval import COCOeval else: from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval if coco_gt == None: coco_gt = COCO(anno_file) logger.info("Start evaluate...") coco_dt = coco_gt.loadRes(jsonfile) if style == 'proposal': coco_eval = COCOeval(coco_gt, coco_dt, 'bbox') coco_eval.params.useCats = 0 coco_eval.params.maxDets = list(max_dets) elif style == 'keypoints_crowd': coco_eval = COCOeval(coco_gt, coco_dt, style, sigmas, use_area) else: coco_eval = COCOeval(coco_gt, coco_dt, style) coco_eval.evaluate() coco_eval.accumulate() coco_eval.summarize() if classwise: # Compute per-category AP and PR curve try: from terminaltables import AsciiTable except Exception as e: logger.error( 'terminaltables not found, plaese install terminaltables. ' 'for example: `pip install terminaltables`.') raise e precisions = coco_eval.eval['precision'] cat_ids = coco_gt.getCatIds() # precision: (iou, recall, cls, area range, max dets) assert len(cat_ids) == precisions.shape[2] results_per_category = [] for idx, catId in enumerate(cat_ids): # area range index 0: all area ranges # max dets index -1: typically 100 per image nm = coco_gt.loadCats(catId)[0] precision = precisions[:, :, idx, 0, -1] precision = precision[precision > -1] if precision.size: ap = np.mean(precision) else: ap = float('nan') results_per_category.append( (str(nm["name"]), '{:0.3f}'.format(float(ap)))) pr_array = precisions[0, :, idx, 0, 2] recall_array = np.arange(0.0, 1.01, 0.01) draw_pr_curve( pr_array, recall_array, out_dir=style + '_pr_curve', file_name='{}_precision_recall_curve.jpg'.format(nm["name"])) num_columns = min(6, len(results_per_category) * 2) results_flatten = list(itertools.chain(*results_per_category)) headers = ['category', 'AP'] * (num_columns // 2) results_2d = itertools.zip_longest( * [results_flatten[i::num_columns] for i in range(num_columns)]) table_data = [headers] table_data += [result for result in results_2d] table = AsciiTable(table_data) logger.info('Per-category of {} AP: \n{}'.format(style, table.table)) logger.info("per-category PR curve has output to {} folder.".format( style + '_pr_curve')) # flush coco evaluation result sys.stdout.flush() return coco_eval.stats
Args: jsonfile (str): Evaluation json file, eg: bbox.json, mask.json. style (str): COCOeval style, can be `bbox` , `segm` , `proposal`, `keypoints` and `keypoints_crowd`. coco_gt (str): Whether to load COCOAPI through anno_file, eg: coco_gt = COCO(anno_file) anno_file (str): COCO annotations file. max_dets (tuple): COCO evaluation maxDets. classwise (bool): Whether per-category AP and draw P-R Curve or not. sigmas (nparray): keypoint labelling sigmas. use_area (bool): If gt annotations (eg. CrowdPose, AIC) do not have 'area', please set use_area=False.
cocoapi_eval
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/metrics/coco_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/metrics/coco_utils.py
Apache-2.0
def json_eval_results(metric, json_directory, dataset): """ cocoapi eval with already exists proposal.json, bbox.json or mask.json """ assert metric == 'COCO' anno_file = dataset.get_anno() json_file_list = ['proposal.json', 'bbox.json', 'mask.json'] if json_directory: assert os.path.exists( json_directory), "The json directory:{} does not exist".format( json_directory) for k, v in enumerate(json_file_list): json_file_list[k] = os.path.join(str(json_directory), v) coco_eval_style = ['proposal', 'bbox', 'segm'] for i, v_json in enumerate(json_file_list): if os.path.exists(v_json): cocoapi_eval(v_json, coco_eval_style[i], anno_file=anno_file) else: logger.info("{} not exists!".format(v_json))
cocoapi eval with already exists proposal.json, bbox.json or mask.json
json_eval_results
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/metrics/coco_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/metrics/coco_utils.py
Apache-2.0
def jaccard_overlap(pred, gt, is_bbox_normalized=False): """ Calculate jaccard overlap ratio between two bounding box """ if pred[0] >= gt[2] or pred[2] <= gt[0] or \ pred[1] >= gt[3] or pred[3] <= gt[1]: return 0. inter_xmin = max(pred[0], gt[0]) inter_ymin = max(pred[1], gt[1]) inter_xmax = min(pred[2], gt[2]) inter_ymax = min(pred[3], gt[3]) inter_size = bbox_area([inter_xmin, inter_ymin, inter_xmax, inter_ymax], is_bbox_normalized) pred_size = bbox_area(pred, is_bbox_normalized) gt_size = bbox_area(gt, is_bbox_normalized) overlap = float(inter_size) / (pred_size + gt_size - inter_size) return overlap
Calculate jaccard overlap ratio between two bounding box
jaccard_overlap
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/metrics/map_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/metrics/map_utils.py
Apache-2.0
def update(self, bbox, score, label, gt_box, gt_label, difficult=None): """ Update metric statics from given prediction and ground truth infomations. """ if difficult is None: difficult = np.zeros_like(gt_label) # record class gt count for gtl, diff in zip(gt_label, difficult): if self.evaluate_difficult or int(diff) == 0: self.class_gt_counts[int(np.array(gtl))] += 1 # record class score positive visited = [False] * len(gt_label) for b, s, l in zip(bbox, score, label): pred = b.tolist() if isinstance(b, np.ndarray) else b max_idx = -1 max_overlap = -1.0 for i, gl in enumerate(gt_label): if int(gl) == int(l): if len(gt_box[i]) == 5: overlap = calc_rbox_iou(pred, gt_box[i]) else: overlap = jaccard_overlap(pred, gt_box[i], self.is_bbox_normalized) if overlap > max_overlap: max_overlap = overlap max_idx = i if max_overlap > self.overlap_thresh: if self.evaluate_difficult or \ int(np.array(difficult[max_idx])) == 0: if not visited[max_idx]: self.class_score_poss[int(l)].append([s, 1.0]) visited[max_idx] = True else: self.class_score_poss[int(l)].append([s, 0.0]) else: self.class_score_poss[int(l)].append([s, 0.0])
Update metric statics from given prediction and ground truth infomations.
update
python
PaddlePaddle/models
tutorials/pp-series/HRNet-Keypoint/lib/metrics/map_utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/pp-series/HRNet-Keypoint/lib/metrics/map_utils.py
Apache-2.0