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 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, enable_mkldnn_bfloat16=False, delete_shuffle_pass=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 delete_shuffle_pass (bool): whether to remove shuffle_channel_detect_pass in TensorRT. Used by action model. 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)) infer_model = os.path.join(model_dir, 'model.pdmodel') infer_params = os.path.join(model_dir, 'model.pdiparams') if not os.path.exists(infer_model): infer_model = os.path.join(model_dir, 'inference.pdmodel') infer_params = os.path.join(model_dir, 'inference.pdiparams') if not os.path.exists(infer_model): raise ValueError("Cannot find any inference model in dir: {},". format(model_dir)) config = Config(infer_model, infer_params) 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() if enable_mkldnn_bfloat16: config.enable_mkldnn_bfloat16() 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) * batch_size, 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) if delete_shuffle_pass: config.delete_pass("shuffle_channel_detect_pass") 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 delete_shuffle_pass (bool): whether to remove shuffle_channel_detect_pass in TensorRT. Used by action model. Returns: predictor (PaddlePredictor): AnalysisPredictor Raises: ValueError: predict by TensorRT need device == 'GPU'.
load_predictor
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/infer.py
Apache-2.0
def predict(self, repeats=1): ''' Args: repeats (int): repeat number for 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] ''' # model prediction np_heatmap, np_masks = None, None for i in range(repeats): self.predictor.run() output_names = self.predictor.get_output_names() heatmap_tensor = self.predictor.get_output_handle(output_names[0]) np_heatmap = heatmap_tensor.copy_to_cpu() if self.pred_config.tagmap: masks_tensor = self.predictor.get_output_handle(output_names[ 1]) heat_k = self.predictor.get_output_handle(output_names[2]) inds_k = self.predictor.get_output_handle(output_names[3]) np_masks = [ masks_tensor.copy_to_cpu(), heat_k.copy_to_cpu(), inds_k.copy_to_cpu() ] result = dict(heatmap=np_heatmap, masks=np_masks) return result
Args: repeats (int): repeat number for 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
modelcenter/PP-HumanV2/APP/python/keypoint_infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/keypoint_infer.py
Apache-2.0
def create_inputs(imgs, im_info): """generate input for different model type Args: imgs (list(numpy)): list of image (np.ndarray) im_info (list(dict)): list of image info Returns: inputs (dict): input of model """ inputs = {} inputs['image'] = np.stack(imgs, axis=0).astype('float32') 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 image (np.ndarray) im_info (list(dict)): list of image info Returns: inputs (dict): input of model
create_inputs
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/keypoint_infer.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/keypoint_infer.py
Apache-2.0
def warp_affine_joints(joints, mat): """Apply affine transformation defined by the transform matrix on the joints. Args: joints (np.ndarray[..., 2]): Origin coordinate of joints. mat (np.ndarray[3, 2]): The affine matrix. Returns: matrix (np.ndarray[..., 2]): Result coordinate of joints. """ joints = np.array(joints) shape = joints.shape joints = joints.reshape(-1, 2) return np.dot(np.concatenate( (joints, joints[:, 0:1] * 0 + 1), axis=1), mat.T).reshape(shape)
Apply affine transformation defined by the transform matrix on the joints. Args: joints (np.ndarray[..., 2]): Origin coordinate of joints. mat (np.ndarray[3, 2]): The affine matrix. Returns: matrix (np.ndarray[..., 2]): Result coordinate of joints.
warp_affine_joints
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/keypoint_postprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/keypoint_postprocess.py
Apache-2.0
def get_max_preds(self, heatmaps): """get predictions from score maps Args: heatmaps: numpy.ndarray([batch_size, num_joints, height, width]) Returns: preds: numpy.ndarray([batch_size, num_joints, 2]), keypoints coords maxvals: numpy.ndarray([batch_size, num_joints, 2]), the maximum confidence of the keypoints """ assert isinstance(heatmaps, np.ndarray), 'heatmaps should be numpy.ndarray' assert heatmaps.ndim == 4, 'batch_images should be 4-ndim' batch_size = heatmaps.shape[0] num_joints = heatmaps.shape[1] width = heatmaps.shape[3] heatmaps_reshaped = heatmaps.reshape((batch_size, num_joints, -1)) idx = np.argmax(heatmaps_reshaped, 2) maxvals = np.amax(heatmaps_reshaped, 2) maxvals = maxvals.reshape((batch_size, num_joints, 1)) idx = idx.reshape((batch_size, num_joints, 1)) preds = np.tile(idx, (1, 1, 2)).astype(np.float32) preds[:, :, 0] = (preds[:, :, 0]) % width preds[:, :, 1] = np.floor((preds[:, :, 1]) / width) pred_mask = np.tile(np.greater(maxvals, 0.0), (1, 1, 2)) pred_mask = pred_mask.astype(np.float32) preds *= pred_mask return preds, maxvals
get predictions from score maps Args: heatmaps: numpy.ndarray([batch_size, num_joints, height, width]) Returns: preds: numpy.ndarray([batch_size, num_joints, 2]), keypoints coords maxvals: numpy.ndarray([batch_size, num_joints, 2]), the maximum confidence of the keypoints
get_max_preds
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/keypoint_postprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/keypoint_postprocess.py
Apache-2.0
def dark_postprocess(self, hm, coords, kernelsize): """ refer to https://github.com/ilovepose/DarkPose/lib/core/inference.py """ hm = self.gaussian_blur(hm, kernelsize) hm = np.maximum(hm, 1e-10) hm = np.log(hm) for n in range(coords.shape[0]): for p in range(coords.shape[1]): coords[n, p] = self.dark_parse(hm[n][p], coords[n][p]) return coords
refer to https://github.com/ilovepose/DarkPose/lib/core/inference.py
dark_postprocess
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/keypoint_postprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/keypoint_postprocess.py
Apache-2.0
def get_final_preds(self, heatmaps, center, scale, kernelsize=3): """the highest heatvalue location with a quarter offset in the direction from the highest response to the second highest response. Args: heatmaps (numpy.ndarray): The predicted heatmaps center (numpy.ndarray): The boxes center scale (numpy.ndarray): The scale factor Returns: preds: numpy.ndarray([batch_size, num_joints, 2]), keypoints coords maxvals: numpy.ndarray([batch_size, num_joints, 1]), the maximum confidence of the keypoints """ coords, maxvals = self.get_max_preds(heatmaps) heatmap_height = heatmaps.shape[2] heatmap_width = heatmaps.shape[3] if self.use_dark: coords = self.dark_postprocess(heatmaps, coords, kernelsize) else: for n in range(coords.shape[0]): for p in range(coords.shape[1]): hm = heatmaps[n][p] px = int(math.floor(coords[n][p][0] + 0.5)) py = int(math.floor(coords[n][p][1] + 0.5)) if 1 < px < heatmap_width - 1 and 1 < py < heatmap_height - 1: diff = np.array([ hm[py][px + 1] - hm[py][px - 1], hm[py + 1][px] - hm[py - 1][px] ]) coords[n][p] += np.sign(diff) * .25 preds = coords.copy() # Transform back for i in range(coords.shape[0]): preds[i] = transform_preds(coords[i], center[i], scale[i], [heatmap_width, heatmap_height]) return preds, maxvals
the highest heatvalue location with a quarter offset in the direction from the highest response to the second highest response. Args: heatmaps (numpy.ndarray): The predicted heatmaps center (numpy.ndarray): The boxes center scale (numpy.ndarray): The scale factor Returns: preds: numpy.ndarray([batch_size, num_joints, 2]), keypoints coords maxvals: numpy.ndarray([batch_size, num_joints, 1]), the maximum confidence of the keypoints
get_final_preds
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/keypoint_postprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/keypoint_postprocess.py
Apache-2.0
def get_affine_transform(center, input_size, rot, output_size, shift=(0., 0.), inv=False): """Get the affine transform matrix, given the center/scale/rot/output_size. Args: center (np.ndarray[2, ]): Center of the bounding box (x, y). scale (np.ndarray[2, ]): Scale of the bounding box wrt [width, height]. rot (float): Rotation angle (degree). output_size (np.ndarray[2, ]): Size of the destination heatmaps. shift (0-100%): Shift translation ratio wrt the width/height. Default (0., 0.). inv (bool): Option to inverse the affine transform direction. (inv=False: src->dst or inv=True: dst->src) Returns: np.ndarray: The transform matrix. """ assert len(center) == 2 assert len(output_size) == 2 assert len(shift) == 2 if not isinstance(input_size, (np.ndarray, list)): input_size = np.array([input_size, input_size], dtype=np.float32) scale_tmp = input_size shift = np.array(shift) src_w = scale_tmp[0] dst_w = output_size[0] dst_h = output_size[1] rot_rad = np.pi * rot / 180 src_dir = rotate_point([0., src_w * -0.5], rot_rad) dst_dir = np.array([0., dst_w * -0.5]) src = np.zeros((3, 2), dtype=np.float32) src[0, :] = center + scale_tmp * shift src[1, :] = center + src_dir + scale_tmp * shift src[2, :] = _get_3rd_point(src[0, :], src[1, :]) dst = np.zeros((3, 2), dtype=np.float32) dst[0, :] = [dst_w * 0.5, dst_h * 0.5] dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5]) + dst_dir dst[2, :] = _get_3rd_point(dst[0, :], dst[1, :]) if inv: trans = cv2.getAffineTransform(np.float32(dst), np.float32(src)) else: trans = cv2.getAffineTransform(np.float32(src), np.float32(dst)) return trans
Get the affine transform matrix, given the center/scale/rot/output_size. Args: center (np.ndarray[2, ]): Center of the bounding box (x, y). scale (np.ndarray[2, ]): Scale of the bounding box wrt [width, height]. rot (float): Rotation angle (degree). output_size (np.ndarray[2, ]): Size of the destination heatmaps. shift (0-100%): Shift translation ratio wrt the width/height. Default (0., 0.). inv (bool): Option to inverse the affine transform direction. (inv=False: src->dst or inv=True: dst->src) Returns: np.ndarray: The transform matrix.
get_affine_transform
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/keypoint_preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/keypoint_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
modelcenter/PP-HumanV2/APP/python/keypoint_preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/keypoint_preprocess.py
Apache-2.0
def rotate_point(pt, angle_rad): """Rotate a point by an angle. Args: pt (list[float]): 2 dimensional point to be rotated angle_rad (float): rotation angle by radian Returns: list[float]: Rotated point. """ assert len(pt) == 2 sn, cs = np.sin(angle_rad), np.cos(angle_rad) new_x = pt[0] * cs - pt[1] * sn new_y = pt[0] * sn + pt[1] * cs rotated_pt = [new_x, new_y] return rotated_pt
Rotate a point by an angle. Args: pt (list[float]): 2 dimensional point to be rotated angle_rad (float): rotation angle by radian Returns: list[float]: Rotated point.
rotate_point
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/keypoint_preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/keypoint_preprocess.py
Apache-2.0
def _get_3rd_point(a, b): """To calculate the affine matrix, three pairs of points are required. This function is used to get the 3rd point, given 2D points a & b. The 3rd point is defined by rotating vector `a - b` by 90 degrees anticlockwise, using b as the rotation center. Args: a (np.ndarray): point(x,y) b (np.ndarray): point(x,y) Returns: np.ndarray: The 3rd point. """ assert len(a) == 2 assert len(b) == 2 direction = a - b third_pt = b + np.array([-direction[1], direction[0]], dtype=np.float32) return third_pt
To calculate the affine matrix, three pairs of points are required. This function is used to get the 3rd point, given 2D points a & b. The 3rd point is defined by rotating vector `a - b` by 90 degrees anticlockwise, using b as the rotation center. Args: a (np.ndarray): point(x,y) b (np.ndarray): point(x,y) Returns: np.ndarray: The 3rd point.
_get_3rd_point
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/keypoint_preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/keypoint_preprocess.py
Apache-2.0
def generate_scale(self, img): """ Args: img (np.ndarray): image (np.ndarray) Returns: im_scale_x: the resize ratio of X im_scale_y: the resize ratio of Y """ limit_side_len = self.limit_side_len h, w, c = img.shape # limit the max side if self.limit_type == 'max': if h > w: ratio = float(limit_side_len) / h else: ratio = float(limit_side_len) / w elif self.limit_type == 'min': if h < w: ratio = float(limit_side_len) / h else: ratio = float(limit_side_len) / w elif self.limit_type == 'resize_long': ratio = float(limit_side_len) / max(h, w) else: raise Exception('not support limit type, image ') resize_h = int(h * ratio) resize_w = int(w * ratio) resize_h = max(int(round(resize_h / 32) * 32), 32) resize_w = max(int(round(resize_w / 32) * 32), 32) im_scale_y = resize_h / float(h) im_scale_x = resize_w / float(w) return im_scale_y, im_scale_x
Args: img (np.ndarray): image (np.ndarray) Returns: im_scale_x: the resize ratio of X im_scale_y: the resize ratio of Y
generate_scale
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/preprocess.py
Apache-2.0
def __call__(self, img): """ Performs resize operations. Args: img (PIL.Image): a PIL.Image. return: resized_img: a PIL.Image after scaling. """ result_img = None if isinstance(img, np.ndarray): h, w, _ = img.shape elif isinstance(img, Image.Image): w, h = img.size else: raise NotImplementedError if w <= h: ow = self.short_size if self.fixed_ratio: # default is True oh = int(self.short_size * 4.0 / 3.0) elif not self.keep_ratio: # no oh = self.short_size else: scale_factor = self.short_size / w oh = int(h * float(scale_factor) + 0.5) if self.do_round else int(h * self.short_size / w) ow = int(w * float(scale_factor) + 0.5) if self.do_round else int(w * self.short_size / h) else: oh = self.short_size if self.fixed_ratio: ow = int(self.short_size * 4.0 / 3.0) elif not self.keep_ratio: # no ow = self.short_size else: scale_factor = self.short_size / h oh = int(h * float(scale_factor) + 0.5) if self.do_round else int(h * self.short_size / w) ow = int(w * float(scale_factor) + 0.5) if self.do_round else int(w * self.short_size / h) if type(img) == np.ndarray: img = Image.fromarray(img, mode='RGB') if self.backend == 'pillow': result_img = img.resize((ow, oh), Image.BILINEAR) elif self.backend == 'cv2' and (self.keep_ratio is not None): result_img = cv2.resize( img, (ow, oh), interpolation=cv2.INTER_LINEAR) else: result_img = Image.fromarray( cv2.resize( np.asarray(img), (ow, oh), interpolation=cv2.INTER_LINEAR)) return result_img
Performs resize operations. Args: img (PIL.Image): a PIL.Image. return: resized_img: a PIL.Image after scaling.
__call__
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/preprocess.py
Apache-2.0
def nms(dets, match_threshold=0.6, match_metric='iou'): """ Apply NMS to avoid detecting too many overlapping bounding boxes. Args: dets: shape [N, 5], [score, x1, y1, x2, y2] match_metric: 'iou' or 'ios' match_threshold: overlap thresh for match metric. """ if dets.shape[0] == 0: return dets[[], :] scores = dets[:, 0] x1 = dets[:, 1] y1 = dets[:, 2] x2 = dets[:, 3] y2 = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] ndets = dets.shape[0] suppressed = np.zeros((ndets), dtype=np.int) for _i in range(ndets): i = order[_i] if suppressed[i] == 1: continue ix1 = x1[i] iy1 = y1[i] ix2 = x2[i] iy2 = y2[i] iarea = areas[i] for _j in range(_i + 1, ndets): j = order[_j] if suppressed[j] == 1: continue xx1 = max(ix1, x1[j]) yy1 = max(iy1, y1[j]) xx2 = min(ix2, x2[j]) yy2 = min(iy2, y2[j]) w = max(0.0, xx2 - xx1 + 1) h = max(0.0, yy2 - yy1 + 1) inter = w * h if match_metric == 'iou': union = iarea + areas[j] - inter match_value = inter / union elif match_metric == 'ios': smaller = min(iarea, areas[j]) match_value = inter / smaller else: raise ValueError() if match_value >= match_threshold: suppressed[j] = 1 keep = np.where(suppressed == 0)[0] dets = dets[keep, :] return dets
Apply NMS to avoid detecting too many overlapping bounding boxes. Args: dets: shape [N, 5], [score, x1, y1, x2, y2] match_metric: 'iou' or 'ios' match_threshold: overlap thresh for match metric.
nms
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/utils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/utils.py
Apache-2.0
def visualize_box_mask(im, results, labels, threshold=0.5): """ Args: im (str/np.ndarray): path of image/np.ndarray read by cv2 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] labels (list): labels:['class1', ..., 'classn'] threshold (float): Threshold of score. Returns: im (PIL.Image.Image): visualized image """ if isinstance(im, str): im = Image.open(im).convert('RGB') elif isinstance(im, np.ndarray): im = Image.fromarray(im) if 'masks' in results and 'boxes' in results and len(results['boxes']) > 0: im = draw_mask( im, results['boxes'], results['masks'], labels, threshold=threshold) if 'boxes' in results and len(results['boxes']) > 0: im = draw_box(im, results['boxes'], labels, threshold=threshold) if 'segm' in results: im = draw_segm( im, results['segm'], results['label'], results['score'], labels, threshold=threshold) return im
Args: im (str/np.ndarray): path of image/np.ndarray read by cv2 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] labels (list): labels:['class1', ..., 'classn'] threshold (float): Threshold of score. Returns: im (PIL.Image.Image): visualized image
visualize_box_mask
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/visualize.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/visualize.py
Apache-2.0
def draw_mask(im, np_boxes, np_masks, labels, threshold=0.5): """ Args: im (PIL.Image.Image): PIL image np_boxes (np.ndarray): shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] np_masks (np.ndarray): shape:[N, im_h, im_w] labels (list): labels:['class1', ..., 'classn'] threshold (float): threshold of mask Returns: im (PIL.Image.Image): visualized image """ color_list = get_color_map_list(len(labels)) w_ratio = 0.4 alpha = 0.7 im = np.array(im).astype('float32') clsid2color = {} expect_boxes = (np_boxes[:, 1] > threshold) & (np_boxes[:, 0] > -1) np_boxes = np_boxes[expect_boxes, :] np_masks = np_masks[expect_boxes, :, :] im_h, im_w = im.shape[:2] np_masks = np_masks[:, :im_h, :im_w] for i in range(len(np_masks)): clsid, score = int(np_boxes[i][0]), np_boxes[i][1] mask = np_masks[i] if clsid not in clsid2color: clsid2color[clsid] = color_list[clsid] color_mask = clsid2color[clsid] for c in range(3): color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio * 255 idx = np.nonzero(mask) color_mask = np.array(color_mask) im[idx[0], idx[1], :] *= 1.0 - alpha im[idx[0], idx[1], :] += alpha * color_mask return Image.fromarray(im.astype('uint8'))
Args: im (PIL.Image.Image): PIL image np_boxes (np.ndarray): shape:[N,6], N: number of box, matix element:[class, score, x_min, y_min, x_max, y_max] np_masks (np.ndarray): shape:[N, im_h, im_w] labels (list): labels:['class1', ..., 'classn'] threshold (float): threshold of mask Returns: im (PIL.Image.Image): visualized image
draw_mask
python
PaddlePaddle/models
modelcenter/PP-HumanV2/APP/python/visualize.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-HumanV2/APP/python/visualize.py
Apache-2.0
def get_pseudo_color_map(self, pred, color_map=None): """ Get the pseudo color image. Args: pred (numpy.ndarray): the origin predicted image. color_map (list, optional): the palette color map. Default: None, use paddleseg's default color map. Returns: (numpy.ndarray): the pseduo image. """ pred_mask = PILImage.fromarray(pred.astype(np.uint8), mode='P') if color_map is None: color_map = self.get_color_map_list(256) pred_mask.putpalette(color_map) return pred_mask
Get the pseudo color image. Args: pred (numpy.ndarray): the origin predicted image. color_map (list, optional): the palette color map. Default: None, use paddleseg's default color map. Returns: (numpy.ndarray): the pseduo image.
get_pseudo_color_map
python
PaddlePaddle/models
modelcenter/PP-LiteSeg/APP/app.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-LiteSeg/APP/app.py
Apache-2.0
def get_color_map_list(self, num_classes, custom_color=None): """ Returns the color map for visualizing the segmentation mask, which can support arbitrary number of classes. Args: num_classes (int): Number of classes. custom_color (list, optional): Save images with a custom color map. Default: None, use paddleseg's default color map. Returns: (list). The color map. """ num_classes += 1 color_map = num_classes * [0, 0, 0] for i in range(0, num_classes): j = 0 lab = i while lab: color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j)) color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j)) color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j)) j += 1 lab >>= 3 color_map = color_map[3:] if custom_color: color_map[:len(custom_color)] = custom_color return color_map
Returns the color map for visualizing the segmentation mask, which can support arbitrary number of classes. Args: num_classes (int): Number of classes. custom_color (list, optional): Save images with a custom color map. Default: None, use paddleseg's default color map. Returns: (list). The color map.
get_color_map_list
python
PaddlePaddle/models
modelcenter/PP-LiteSeg/APP/app.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-LiteSeg/APP/app.py
Apache-2.0
def get_output(img, size, bg, download_size): """ Get the special size and background photo. Args: img(numpy:ndarray): The image array. size(str): The size user specified. bg(str): The background color user specified. download_size(str): The size for image saving. """ alpha = predictor.run(img) res = utils.bg_replace(img, alpha, bg_name=bg) size_index = sizes_play.index(size) res = utils.adjust_size(res, size_index) res_download = utils.download(res, download_size) return res, res_download
Get the special size and background photo. Args: img(numpy:ndarray): The image array. size(str): The size user specified. bg(str): The background color user specified. download_size(str): The size for image saving.
get_output
python
PaddlePaddle/models
modelcenter/PP-Matting/APP1/app.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-Matting/APP1/app.py
Apache-2.0
def download_with_progressbar(url: str, save_path: str): """Download file from given url and decompress it Args: url (str): url save_path (str): path for saving downloaded file Raises: Exception: exception """ print(f"Auto downloading {url} to {save_path}") if os.path.exists(save_path): print("File already exist, skip...") else: response = requests.get(url, stream=True) total_size_in_bytes = int(response.headers.get("content-length", 0)) block_size = 1024 # 1 Kibibyte progress_bar = tqdm( total=total_size_in_bytes, unit="iB", unit_scale=True) with open(save_path, "wb") as file: for data in response.iter_content(block_size): progress_bar.update(len(data)) file.write(data) progress_bar.close() if total_size_in_bytes == 0 or progress_bar.n != total_size_in_bytes or not os.path.isfile( save_path): raise Exception( f"Something went wrong while downloading file from {url}") print("Finished downloading") print(f"Try decompression at {save_path}") os.system(f"tar -xf {save_path}") print(f"Finished decompression at {save_path}")
Download file from given url and decompress it Args: url (str): url save_path (str): path for saving downloaded file Raises: Exception: exception
download_with_progressbar
python
PaddlePaddle/models
modelcenter/PP-ShiTuV2/APP/app.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-ShiTuV2/APP/app.py
Apache-2.0
def model_inference(image) -> tuple: """send given image to inference model and get result from output Args: image (gr.Image): input image Returns: tuple: (drawn image to display, result in json format) """ results = clas_engine.predict(image, print_pred=True, predict_type="shitu") # bs = 1, fetch the first result results = list(results)[0] image_draw_box = draw_bbox_results(image, results) im_show = Image.fromarray(image_draw_box) json_out = {"base64": image_to_base64(im_show), "result": str(results)} return im_show, json_out
send given image to inference model and get result from output Args: image (gr.Image): input image Returns: tuple: (drawn image to display, result in json format)
model_inference
python
PaddlePaddle/models
modelcenter/PP-ShiTuV2/APP/app.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-ShiTuV2/APP/app.py
Apache-2.0
def draw_bbox_results(image: Union[np.ndarray, Image.Image], results: List[Dict[str, Any]]) -> np.ndarray: """draw bounding box(es) Args: image (Union[np.ndarray, Image.Image]): image to be drawn results (List[Dict[str, Any]]): information for drawing bounding box Returns: np.ndarray: drawn image """ if isinstance(image, np.ndarray): image = Image.fromarray(image) draw = ImageDraw.Draw(image) font_size = 18 font = ImageFont.truetype("./simfang.ttf", font_size, encoding="utf-8") color = (0, 102, 255) for result in results: # empty results if result["rec_docs"] is None: continue xmin, ymin, xmax, ymax = result["bbox"] text = "{}, {:.2f}".format(result["rec_docs"], result["rec_scores"]) th = font_size tw = font.getsize(text)[0] start_y = max(0, ymin - th) draw.rectangle( [(xmin + 1, start_y), (xmin + tw + 1, start_y + th)], fill=color) draw.text((xmin + 1, start_y), text, fill=(255, 255, 255), font=font) draw.rectangle( [(xmin, ymin), (xmax, ymax)], outline=(255, 0, 0), width=2) return np.array(image)
draw bounding box(es) Args: image (Union[np.ndarray, Image.Image]): image to be drawn results (List[Dict[str, Any]]): information for drawing bounding box Returns: np.ndarray: drawn image
draw_bbox_results
python
PaddlePaddle/models
modelcenter/PP-ShiTuV2/APP/app.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-ShiTuV2/APP/app.py
Apache-2.0
def boxes_from_bitmap(self, pred, _bitmap, dest_width, dest_height): ''' _bitmap: single map with shape (1, H, W), whose values are binarized as {0, 1} ''' bitmap = _bitmap height, width = bitmap.shape outs = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) if len(outs) == 3: img, contours, _ = outs[0], outs[1], outs[2] elif len(outs) == 2: contours, _ = outs[0], outs[1] num_contours = min(len(contours), self.max_candidates) boxes = [] scores = [] for index in range(num_contours): contour = contours[index] points, sside = self.get_mini_boxes(contour) if sside < self.min_size: continue points = np.array(points) if self.score_mode == "fast": score = self.box_score_fast(pred, points.reshape(-1, 2)) else: score = self.box_score_slow(pred, contour) if self.box_thresh > score: continue box = self.unclip(points).reshape(-1, 1, 2) box, sside = self.get_mini_boxes(box) if sside < self.min_size + 2: continue box = np.array(box) box[:, 0] = np.clip( np.round(box[:, 0] / width * dest_width), 0, dest_width) box[:, 1] = np.clip( np.round(box[:, 1] / height * dest_height), 0, dest_height) boxes.append(box.astype(np.int16)) scores.append(score) return np.array(boxes, dtype=np.int16), scores
_bitmap: single map with shape (1, H, W), whose values are binarized as {0, 1}
boxes_from_bitmap
python
PaddlePaddle/models
modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicleplate_postprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicleplate_postprocess.py
Apache-2.0
def box_score_fast(self, bitmap, _box): ''' box_score_fast: use bbox mean score as the mean score ''' h, w = bitmap.shape[:2] box = _box.copy() xmin = np.clip(np.floor(box[:, 0].min()).astype(np.int), 0, w - 1) xmax = np.clip(np.ceil(box[:, 0].max()).astype(np.int), 0, w - 1) ymin = np.clip(np.floor(box[:, 1].min()).astype(np.int), 0, h - 1) ymax = np.clip(np.ceil(box[:, 1].max()).astype(np.int), 0, h - 1) mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8) box[:, 0] = box[:, 0] - xmin box[:, 1] = box[:, 1] - ymin cv2.fillPoly(mask, box.reshape(1, -1, 2).astype(np.int32), 1) return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0]
box_score_fast: use bbox mean score as the mean score
box_score_fast
python
PaddlePaddle/models
modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicleplate_postprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicleplate_postprocess.py
Apache-2.0
def box_score_slow(self, bitmap, contour): ''' box_score_slow: use polyon mean score as the mean score ''' h, w = bitmap.shape[:2] contour = contour.copy() contour = np.reshape(contour, (-1, 2)) xmin = np.clip(np.min(contour[:, 0]), 0, w - 1) xmax = np.clip(np.max(contour[:, 0]), 0, w - 1) ymin = np.clip(np.min(contour[:, 1]), 0, h - 1) ymax = np.clip(np.max(contour[:, 1]), 0, h - 1) mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8) contour[:, 0] = contour[:, 0] - xmin contour[:, 1] = contour[:, 1] - ymin cv2.fillPoly(mask, contour.reshape(1, -1, 2).astype(np.int32), 1) return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0]
box_score_slow: use polyon mean score as the mean score
box_score_slow
python
PaddlePaddle/models
modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicleplate_postprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicleplate_postprocess.py
Apache-2.0
def decode(self, text_index, text_prob=None, is_remove_duplicate=False): """ convert text-index into text-label. """ result_list = [] ignored_tokens = self.get_ignored_tokens() batch_size = len(text_index) for batch_idx in range(batch_size): selection = np.ones(len(text_index[batch_idx]), dtype=bool) if is_remove_duplicate: selection[1:] = text_index[batch_idx][1:] != text_index[ batch_idx][:-1] for ignored_token in ignored_tokens: selection &= text_index[batch_idx] != ignored_token char_list = [ self.character[text_id] for text_id in text_index[batch_idx][selection] ] if text_prob is not None: conf_list = text_prob[batch_idx][selection] else: conf_list = [1] * len(selection) if len(conf_list) == 0: conf_list = [0] text = ''.join(char_list) result_list.append((text, np.mean(conf_list).tolist())) return result_list
convert text-index into text-label.
decode
python
PaddlePaddle/models
modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicleplate_postprocess.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicleplate_postprocess.py
Apache-2.0
def draw_ocr(image, boxes, txts=None, scores=None, drop_score=0.5, font_path="./doc/fonts/simfang.ttf"): """ Visualize the results of OCR detection and recognition args: image(Image|array): RGB image boxes(list): boxes with shape(N, 4, 2) txts(list): the texts scores(list): txxs corresponding scores drop_score(float): only scores greater than drop_threshold will be visualized font_path: the path of font which is used to draw text return(array): the visualized img """ if scores is None: scores = [1] * len(boxes) box_num = len(boxes) for i in range(box_num): if scores is not None and (scores[i] < drop_score or math.isnan(scores[i])): continue box = np.reshape(np.array(boxes[i]), [-1, 1, 2]).astype(np.int64) image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2) if txts is not None: img = np.array(resize_img(image, input_size=600)) txt_img = text_visual( txts, scores, img_h=img.shape[0], img_w=600, threshold=drop_score, font_path=font_path) img = np.concatenate([np.array(img), np.array(txt_img)], axis=1) return img return image
Visualize the results of OCR detection and recognition args: image(Image|array): RGB image boxes(list): boxes with shape(N, 4, 2) txts(list): the texts scores(list): txxs corresponding scores drop_score(float): only scores greater than drop_threshold will be visualized font_path: the path of font which is used to draw text return(array): the visualized img
draw_ocr
python
PaddlePaddle/models
modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicle_plateutils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicle_plateutils.py
Apache-2.0
def str_count(s): """ Count the number of Chinese characters, a single English character and a single number equal to half the length of Chinese characters. args: s(string): the input of string return(int): the number of Chinese characters """ import string count_zh = count_pu = 0 s_len = len(s) en_dg_count = 0 for c in s: if c in string.ascii_letters or c.isdigit() or c.isspace(): en_dg_count += 1 elif c.isalpha(): count_zh += 1 else: count_pu += 1 return s_len - math.ceil(en_dg_count / 2)
Count the number of Chinese characters, a single English character and a single number equal to half the length of Chinese characters. args: s(string): the input of string return(int): the number of Chinese characters
str_count
python
PaddlePaddle/models
modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicle_plateutils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicle_plateutils.py
Apache-2.0
def text_visual(texts, scores, img_h=400, img_w=600, threshold=0., font_path="./doc/simfang.ttf"): """ create new blank img and draw txt on it args: texts(list): the text will be draw scores(list|None): corresponding score of each txt img_h(int): the height of blank img img_w(int): the width of blank img font_path: the path of font which is used to draw text return(array): """ if scores is not None: assert len(texts) == len( scores), "The number of txts and corresponding scores must match" def create_blank_img(): blank_img = np.ones(shape=[img_h, img_w], dtype=np.int8) * 255 blank_img[:, img_w - 1:] = 0 blank_img = Image.fromarray(blank_img).convert("RGB") draw_txt = ImageDraw.Draw(blank_img) return blank_img, draw_txt blank_img, draw_txt = create_blank_img() font_size = 20 txt_color = (0, 0, 0) font = ImageFont.truetype(font_path, font_size, encoding="utf-8") gap = font_size + 5 txt_img_list = [] count, index = 1, 0 for idx, txt in enumerate(texts): index += 1 if scores[idx] < threshold or math.isnan(scores[idx]): index -= 1 continue first_line = True while str_count(txt) >= img_w // font_size - 4: tmp = txt txt = tmp[:img_w // font_size - 4] if first_line: new_txt = str(index) + ': ' + txt first_line = False else: new_txt = ' ' + txt draw_txt.text((0, gap * count), new_txt, txt_color, font=font) txt = tmp[img_w // font_size - 4:] if count >= img_h // gap - 1: txt_img_list.append(np.array(blank_img)) blank_img, draw_txt = create_blank_img() count = 0 count += 1 if first_line: new_txt = str(index) + ': ' + txt + ' ' + '%.3f' % (scores[idx]) else: new_txt = " " + txt + " " + '%.3f' % (scores[idx]) draw_txt.text((0, gap * count), new_txt, txt_color, font=font) # whether add new blank img or not if count >= img_h // gap - 1 and idx + 1 < len(texts): txt_img_list.append(np.array(blank_img)) blank_img, draw_txt = create_blank_img() count = 0 count += 1 txt_img_list.append(np.array(blank_img)) if len(txt_img_list) == 1: blank_img = np.array(txt_img_list[0]) else: blank_img = np.concatenate(txt_img_list, axis=1) return np.array(blank_img)
create new blank img and draw txt on it args: texts(list): the text will be draw scores(list|None): corresponding score of each txt img_h(int): the height of blank img img_w(int): the width of blank img font_path: the path of font which is used to draw text return(array):
text_visual
python
PaddlePaddle/models
modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicle_plateutils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicle_plateutils.py
Apache-2.0
def get_rotate_crop_image(img, points): ''' img_height, img_width = img.shape[0:2] left = int(np.min(points[:, 0])) right = int(np.max(points[:, 0])) top = int(np.min(points[:, 1])) bottom = int(np.max(points[:, 1])) img_crop = img[top:bottom, left:right, :].copy() points[:, 0] = points[:, 0] - left points[:, 1] = points[:, 1] - top ''' assert len(points) == 4, "shape of points must be 4*2" img_crop_width = int( max( np.linalg.norm(points[0] - points[1]), np.linalg.norm(points[2] - points[3]))) img_crop_height = int( max( np.linalg.norm(points[0] - points[3]), np.linalg.norm(points[1] - points[2]))) pts_std = np.float32([[0, 0], [img_crop_width, 0], [img_crop_width, img_crop_height], [0, img_crop_height]]) M = cv2.getPerspectiveTransform(points, pts_std) dst_img = cv2.warpPerspective( img, M, (img_crop_width, img_crop_height), borderMode=cv2.BORDER_REPLICATE, flags=cv2.INTER_CUBIC) dst_img_height, dst_img_width = dst_img.shape[0:2] if dst_img_height * 1.0 / dst_img_width >= 1.5: dst_img = np.rot90(dst_img) return dst_img
img_height, img_width = img.shape[0:2] left = int(np.min(points[:, 0])) right = int(np.max(points[:, 0])) top = int(np.min(points[:, 1])) bottom = int(np.max(points[:, 1])) img_crop = img[top:bottom, left:right, :].copy() points[:, 0] = points[:, 0] - left points[:, 1] = points[:, 1] - top
get_rotate_crop_image
python
PaddlePaddle/models
modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicle_plateutils.py
https://github.com/PaddlePaddle/models/blob/master/modelcenter/PP-Vehicle/APP/pipeline/ppvehicle/vehicle_plateutils.py
Apache-2.0
def get_package_data_files(package, data, package_dir=None): """ Helps to list all specified files in package including files in directories since `package_data` ignores directories. """ if package_dir is None: package_dir = os.path.join(*package.split('.')) all_files = [] for f in data: path = os.path.join(package_dir, f) if os.path.isfile(path): all_files.append(f) continue for root, _dirs, files in os.walk(path, followlinks=True): root = os.path.relpath(root, package_dir) for file in files: file = os.path.join(root, file) if file not in all_files: all_files.append(file) return all_files
Helps to list all specified files in package including files in directories since `package_data` ignores directories.
get_package_data_files
python
PaddlePaddle/models
paddlecv/setup.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/setup.py
Apache-2.0
def __call__(self, inputs): """ step1: parser inputs step2: run step3: merge results input: a list of dict """ # for the input_keys as list # inputs = [pipe_input[key] for pipe_input in pipe_inputs for key in self.input_keys] key = self.input_keys[0] if isinstance(inputs[0][key], (list, tuple)): inputs = [input[key] for input in inputs] else: inputs = [[input[key]] for input in inputs] sub_index_list = [len(input) for input in inputs] inputs = reduce(lambda x, y: x.extend(y) or x, inputs) # step2: run outputs, bbox_nums = self.infer(inputs) # step3: merge curr_offsef_id = 0 pipe_outputs = [] for i, bbox_num in enumerate(bbox_nums): output = outputs[i] start_id = 0 for num in bbox_num: end_id = start_id + num out = {k: v[start_id:end_id] for k, v in output.items()} pipe_outputs.append(out) start_id = end_id return pipe_outputs
step1: parser inputs step2: run step3: merge results input: a list of dict
__call__
python
PaddlePaddle/models
paddlecv/custom_op/inference.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/custom_op/inference.py
Apache-2.0
def topo_sort(self): """ Topological sort of DAG, creates inverted multi-layers views. Args: graph (dict): the DAG stucture in_degrees (dict): Next op list for each op Returns: sort_result: the hierarchical topology list. examples: DAG :[A -> B -> C -> E] \-> D / sort_result: [A, B, C, D, E] """ # Select vertices with in_degree = 0 Q = [u for u in self.in_degrees if self.in_degrees[u] == 0] sort_result = [] while Q: u = Q.pop() sort_result.append(u) for v in self.graph[u]: # remove output degrees self.in_degrees[v] -= 1 # re-select vertices with in_degree = 0 if self.in_degrees[v] == 0: Q.append(v) if len(sort_result) == self.num: return sort_result else: return None
Topological sort of DAG, creates inverted multi-layers views. Args: graph (dict): the DAG stucture in_degrees (dict): Next op list for each op Returns: sort_result: the hierarchical topology list. examples: DAG :[A -> B -> C -> E] \-> D / sort_result: [A, B, C, D, E]
topo_sort
python
PaddlePaddle/models
paddlecv/ppcv/core/framework.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/core/framework.py
Apache-2.0
def register(cls): """ Register a given module class. Args: cls (type): Module class to be registered. Returns: cls """ if cls.__name__ in global_config: raise ValueError("Module class already registered: {}".format( cls.__name__)) global_config[cls.__name__] = cls return cls
Register a given module class. Args: cls (type): Module class to be registered. Returns: cls
register
python
PaddlePaddle/models
paddlecv/ppcv/core/workspace.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/core/workspace.py
Apache-2.0
def create(cls_name, op_cfg, env_cfg): """ Create an instance of given module class. Args: cls_name(str): Class of which to create instnce. Return: instance of type `cls_or_name` """ assert type(cls_name) == str, "should be a name of class" if cls_name not in global_config: raise ValueError("The module {} is not registered".format(cls_name)) cls = global_config[cls_name] return cls(op_cfg, env_cfg)
Create an instance of given module class. Args: cls_name(str): Class of which to create instnce. Return: instance of type `cls_or_name`
create
python
PaddlePaddle/models
paddlecv/ppcv/core/workspace.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/core/workspace.py
Apache-2.0
def create_operators(params, mod): """ create operators based on the config Args: params(list): a dict list, used to create some operators mod(module) : a module that can import single ops """ assert isinstance(params, list), ('operator config should be a list') if mod is None: mod = importlib.import_module(__name__) ops = [] for operator in params: if isinstance(operator, str): op_name = operator param = {} else: assert isinstance(operator, dict) and len(operator) == 1, "yaml format error" op_name = list(operator)[0] param = {} if operator[op_name] is None else operator[op_name] op = getattr(mod, op_name)(**param) ops.append(op) return ops
create operators based on the config Args: params(list): a dict list, used to create some operators mod(module) : a module that can import single ops
create_operators
python
PaddlePaddle/models
paddlecv/ppcv/ops/base.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/base.py
Apache-2.0
def get(self, key): """ key can be one of [list, tuple, str] """ if isinstance(key, (list, tuple)): return [self.data_dict[k] for k in key] elif isinstance(key, (str)): return self.data_dict[key] else: assert False, f"key({key}) type must be in on of [list, tuple, str] but got {type(key)}"
key can be one of [list, tuple, str]
get
python
PaddlePaddle/models
paddlecv/ppcv/ops/general_data_obj.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/general_data_obj.py
Apache-2.0
def get_rotate_crop_image(self, img, points): ''' img_height, img_width = img.shape[0:2] left = int(np.min(points[:, 0])) right = int(np.max(points[:, 0])) top = int(np.min(points[:, 1])) bottom = int(np.max(points[:, 1])) img_crop = img[top:bottom, left:right, :].copy() points[:, 0] = points[:, 0] - left points[:, 1] = points[:, 1] - top ''' assert len(points) == 4, "shape of points must be 4*2" img_crop_width = int( max( np.linalg.norm(points[0] - points[1]), np.linalg.norm(points[2] - points[3]))) img_crop_height = int( max( np.linalg.norm(points[0] - points[3]), np.linalg.norm(points[1] - points[2]))) pts_std = np.float32([[0, 0], [img_crop_width, 0], [img_crop_width, img_crop_height], [0, img_crop_height]]) M = cv2.getPerspectiveTransform(points.astype(np.float32), pts_std) dst_img = cv2.warpPerspective( img, M, (img_crop_width, img_crop_height), borderMode=cv2.BORDER_REPLICATE, flags=cv2.INTER_CUBIC) dst_img_height, dst_img_width = dst_img.shape[0:2] if dst_img_height * 1.0 / dst_img_width >= 1.5: dst_img = np.rot90(dst_img) return dst_img
img_height, img_width = img.shape[0:2] left = int(np.min(points[:, 0])) right = int(np.max(points[:, 0])) top = int(np.min(points[:, 1])) bottom = int(np.max(points[:, 1])) img_crop = img[top:bottom, left:right, :].copy() points[:, 0] = points[:, 0] - left points[:, 1] = points[:, 1] - top
get_rotate_crop_image
python
PaddlePaddle/models
paddlecv/ppcv/ops/connector/op_connector.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/connector/op_connector.py
Apache-2.0
def sorted_boxes(self, dt_boxes): """ Sort text boxes in order from top to bottom, left to right args: dt_boxes(array):detected text boxes with shape [4, 2] return: sorted boxes(array) with shape [4, 2] """ num_boxes = dt_boxes.shape[0] sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0])) _boxes = list(sorted_boxes) for i in range(num_boxes - 1): for j in range(i, 0, -1): if abs(_boxes[j + 1][0][1] - _boxes[j][0][1]) < 10 and \ (_boxes[j + 1][0][0] < _boxes[j][0][0]): tmp = _boxes[j] _boxes[j] = _boxes[j + 1] _boxes[j + 1] = tmp else: break return _boxes
Sort text boxes in order from top to bottom, left to right args: dt_boxes(array):detected text boxes with shape [4, 2] return: sorted boxes(array) with shape [4, 2]
sorted_boxes
python
PaddlePaddle/models
paddlecv/ppcv/ops/connector/op_connector.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/connector/op_connector.py
Apache-2.0
def compute_iou(rec1, rec2): """ computing IoU :param rec1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU """ # computing area of each rectangles S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1]) S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1]) # computing the sum_area sum_area = S_rec1 + S_rec2 # find the each edge of intersect rectangle left_line = max(rec1[1], rec2[1]) right_line = min(rec1[3], rec2[3]) top_line = max(rec1[0], rec2[0]) bottom_line = min(rec1[2], rec2[2]) # judge if there is an intersect if left_line >= right_line or top_line >= bottom_line: return 0.0 else: intersect = (right_line - left_line) * (bottom_line - top_line) return (intersect / (sum_area - intersect)) * 1.0
computing IoU :param rec1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU
compute_iou
python
PaddlePaddle/models
paddlecv/ppcv/ops/connector/table_matcher.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/connector/table_matcher.py
Apache-2.0
def polygons_from_bitmap(self, pred, _bitmap, dest_width, dest_height): ''' _bitmap: single map with shape (1, H, W), whose values are binarized as {0, 1} ''' bitmap = _bitmap height, width = bitmap.shape boxes = [] scores = [] contours, _ = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) for contour in contours[:self.max_candidates]: epsilon = 0.002 * cv2.arcLength(contour, True) approx = cv2.approxPolyDP(contour, epsilon, True) points = approx.reshape((-1, 2)) if points.shape[0] < 4: continue score = self.box_score_fast(pred, points.reshape(-1, 2)) if self.box_thresh > score: continue if points.shape[0] > 2: box = self.unclip(points, self.unclip_ratio) if len(box) > 1: continue else: continue box = box.reshape(-1, 2) _, sside = self.get_mini_boxes(box.reshape((-1, 1, 2))) if sside < self.min_size + 2: continue box = np.array(box) box[:, 0] = np.clip( np.round(box[:, 0] / width * dest_width), 0, dest_width) box[:, 1] = np.clip( np.round(box[:, 1] / height * dest_height), 0, dest_height) boxes.append(box.tolist()) scores.append(score) return boxes, scores
_bitmap: single map with shape (1, H, W), whose values are binarized as {0, 1}
polygons_from_bitmap
python
PaddlePaddle/models
paddlecv/ppcv/ops/models/ocr/ocr_db_detection/postprocess.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_db_detection/postprocess.py
Apache-2.0
def sorted_boxes(dt_boxes): """ Sort text boxes in order from top to bottom, left to right args: dt_boxes(array):detected text boxes with shape [4, 2] return: sorted boxes(array) with shape [4, 2] """ num_boxes = dt_boxes.shape[0] sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0])) _boxes = list(sorted_boxes) for i in range(num_boxes - 1): for j in range(i, 0, -1): if abs(_boxes[j + 1][0][1] - _boxes[j][0][1]) < 10 and \ (_boxes[j + 1][0][0] < _boxes[j][0][0]): tmp = _boxes[j] _boxes[j] = _boxes[j + 1] _boxes[j + 1] = tmp else: break return np.array(_boxes)
Sort text boxes in order from top to bottom, left to right args: dt_boxes(array):detected text boxes with shape [4, 2] return: sorted boxes(array) with shape [4, 2]
sorted_boxes
python
PaddlePaddle/models
paddlecv/ppcv/ops/models/ocr/ocr_db_detection/postprocess.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_db_detection/postprocess.py
Apache-2.0
def resize_image_type0(self, img): """ resize image to a size multiple of 32 which is required by the network args: img(array): array with shape [h, w, c] return(tuple): img, (ratio_h, ratio_w) """ limit_side_len = self.limit_side_len h, w, c = img.shape # limit the max side if self.limit_type == 'max': if max(h, w) > limit_side_len: if h > w: ratio = float(limit_side_len) / h else: ratio = float(limit_side_len) / w else: ratio = 1. elif self.limit_type == 'min': if min(h, w) < limit_side_len: if h < w: ratio = float(limit_side_len) / h else: ratio = float(limit_side_len) / w else: ratio = 1. elif self.limit_type == 'resize_long': ratio = float(limit_side_len) / max(h, w) else: raise Exception('not support limit type, image ') resize_h = int(h * ratio) resize_w = int(w * ratio) resize_h = max(int(round(resize_h / 32) * 32), 32) resize_w = max(int(round(resize_w / 32) * 32), 32) try: if int(resize_w) <= 0 or int(resize_h) <= 0: return None, (None, None) img = cv2.resize(img, (int(resize_w), int(resize_h))) except: print(img.shape, resize_w, resize_h) sys.exit(0) ratio_h = resize_h / float(h) ratio_w = resize_w / float(w) return img, [ratio_h, ratio_w]
resize image to a size multiple of 32 which is required by the network args: img(array): array with shape [h, w, c] return(tuple): img, (ratio_h, ratio_w)
resize_image_type0
python
PaddlePaddle/models
paddlecv/ppcv/ops/models/ocr/ocr_db_detection/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_db_detection/preprocess.py
Apache-2.0
def filter_empty_contents(self, ocr_info): """ find out the empty texts and remove the links """ new_ocr_info = [] empty_index = [] for idx, info in enumerate(ocr_info): if len(info["transcription"]) > 0: new_ocr_info.append(copy.deepcopy(info)) else: empty_index.append(info["id"]) for idx, info in enumerate(new_ocr_info): new_link = [] for link in info["linking"]: if link[0] in empty_index or link[1] in empty_index: continue new_link.append(link) new_ocr_info[idx]["linking"] = new_link return new_ocr_info
find out the empty texts and remove the links
filter_empty_contents
python
PaddlePaddle/models
paddlecv/ppcv/ops/models/ocr/ocr_kie/preprocess.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_kie/preprocess.py
Apache-2.0
def decode(self, structure_probs, bbox_preds, shape_list): """convert text-label into text-index. """ ignored_tokens = self.get_ignored_tokens() end_idx = self.dict[self.end_str] structure_idx = structure_probs.argmax(axis=2) structure_probs = structure_probs.max(axis=2) structure_batch_list = [] bbox_batch_list = [] batch_size = len(structure_idx) for batch_idx in range(batch_size): structure_list = [] bbox_list = [] score_list = [] for idx in range(len(structure_idx[batch_idx])): char_idx = int(structure_idx[batch_idx][idx]) if idx > 0 and char_idx == end_idx: break if char_idx in ignored_tokens: continue text = self.character[char_idx] if text in self.td_token: bbox = bbox_preds[batch_idx, idx] bbox = self._bbox_decode(bbox, shape_list[batch_idx]) bbox_list.append(bbox) structure_list.append(text) score_list.append(structure_probs[batch_idx, idx]) structure_batch_list.append( [structure_list, np.mean(score_list).tolist()]) bbox_batch_list.append(np.array(bbox_list).tolist()) result = { 'bbox_batch_list': bbox_batch_list, 'structure_batch_list': structure_batch_list, } return result
convert text-label into text-index.
decode
python
PaddlePaddle/models
paddlecv/ppcv/ops/models/ocr/ocr_table_recognition/postprocess.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/models/ocr/ocr_table_recognition/postprocess.py
Apache-2.0
def get_pseudo_color_map(pred, color_map=None): """ Get the pseudo color image. Args: pred (numpy.ndarray): the origin predicted image. color_map (list, optional): the palette color map. Default: None, use paddleseg's default color map. Returns: (numpy.ndarray): the pseduo image. """ pred_mask = Image.fromarray(pred.astype(np.uint8), mode='P') if color_map is None: color_map = get_color_map_list(256) pred_mask.putpalette(color_map) return pred_mask
Get the pseudo color image. Args: pred (numpy.ndarray): the origin predicted image. color_map (list, optional): the palette color map. Default: None, use paddleseg's default color map. Returns: (numpy.ndarray): the pseduo image.
get_pseudo_color_map
python
PaddlePaddle/models
paddlecv/ppcv/ops/output/segmentation.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/output/segmentation.py
Apache-2.0
def get_color_map_list(num_classes, custom_color=None): """ Returns the color map for visualizing the segmentation mask, which can support arbitrary number of classes. Args: num_classes (int): Number of classes. custom_color (list, optional): Save images with a custom color map. Default: None, use paddleseg's default color map. Returns: (list). The color map. """ num_classes += 1 color_map = num_classes * [0, 0, 0] for i in range(0, num_classes): j = 0 lab = i while lab: color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j)) color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j)) color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j)) j += 1 lab >>= 3 color_map = color_map[3:] if custom_color: color_map[:len(custom_color)] = custom_color return color_map
Returns the color map for visualizing the segmentation mask, which can support arbitrary number of classes. Args: num_classes (int): Number of classes. custom_color (list, optional): Save images with a custom color map. Default: None, use paddleseg's default color map. Returns: (list). The color map.
get_color_map_list
python
PaddlePaddle/models
paddlecv/ppcv/ops/output/segmentation.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/ops/output/segmentation.py
Apache-2.0
def get_dict_path(path): """Get dict path from DICTS_HOME, if not exists, download it from url. """ if not is_url(path): return path url = parse_url(path) path, _ = get_path(url, DICTS_HOME) logger.info("The dict path is {}".format(path)) return path
Get dict path from DICTS_HOME, if not exists, download it from url.
get_dict_path
python
PaddlePaddle/models
paddlecv/ppcv/utils/download.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/utils/download.py
Apache-2.0
def setup_logger(name="ppcv", output=None): """ Initialize logger and set its verbosity level to INFO. Args: name (str): the root module name of this logger output (str): a file name or a directory to save log. If None, will not save log file. If ends with ".txt" or ".log", assumed to be a file name. Otherwise, logs will be saved to `output/log.txt`. Returns: logging.Logger: a logger """ logger = logging.getLogger(name) if name in logger_initialized: return logger logger.setLevel(logging.INFO) logger.propagate = False formatter = logging.Formatter( "[%(asctime)s] %(name)s %(levelname)s: %(message)s", datefmt="%m/%d %H:%M:%S") # stdout logging: master only local_rank = dist.get_rank() if local_rank == 0: ch = logging.StreamHandler(stream=sys.stdout) ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) logger.addHandler(ch) # file logging: all workers if output is not None: if output.endswith(".txt") or output.endswith(".log"): filename = output else: filename = os.path.join(output, "log.txt") if local_rank > 0: filename = filename + ".rank{}".format(local_rank) os.makedirs(os.path.dirname(filename)) fh = logging.FileHandler(filename, mode='a') fh.setLevel(logging.DEBUG) fh.setFormatter(logging.Formatter()) logger.addHandler(fh) logger_initialized.append(name) return logger
Initialize logger and set its verbosity level to INFO. Args: name (str): the root module name of this logger output (str): a file name or a directory to save log. If None, will not save log file. If ends with ".txt" or ".log", assumed to be a file name. Otherwise, logs will be saved to `output/log.txt`. Returns: logging.Logger: a logger
setup_logger
python
PaddlePaddle/models
paddlecv/ppcv/utils/logger.py
https://github.com/PaddlePaddle/models/blob/master/paddlecv/ppcv/utils/logger.py
Apache-2.0
def accuracy_paddle(output, target, topk=(1, )): """Computes the accuracy over the k top predictions for the specified values of k""" with paddle.no_grad(): maxk = max(topk) batch_size = target.shape[0] _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.equal(target) res = [] for k in topk: correct_k = correct.astype(paddle.int32)[:k].flatten().sum( dtype='float32') res.append(correct_k * (100.0 / batch_size)) return res
Computes the accuracy over the k top predictions for the specified values of k
accuracy_paddle
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/metric.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/metric.py
Apache-2.0
def synchronize_between_processes(self): """ Warning: does not synchronize the deque! """ t = paddle.to_tensor([self.count, self.total], dtype='float64') t = t.numpy().tolist() self.count = int(t[0]) self.total = t[1]
Warning: does not synchronize the deque!
synchronize_between_processes
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/utils.py
Apache-2.0
def has_file_allowed_extension(filename: str, extensions: Tuple[str, ...]) -> bool: """Checks if a file is an allowed extension. Args: filename (string): path to a file extensions (tuple of strings): extensions to consider (lowercase) Returns: bool: True if the filename ends with one of given extensions """ return filename.lower().endswith(extensions)
Checks if a file is an allowed extension. Args: filename (string): path to a file extensions (tuple of strings): extensions to consider (lowercase) Returns: bool: True if the filename ends with one of given extensions
has_file_allowed_extension
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py
Apache-2.0
def find_classes(directory: str) -> Tuple[List[str], Dict[str, int]]: """Finds the class folders in a dataset. See :class:`DatasetFolder` for details. """ classes = sorted( entry.name for entry in os.scandir(directory) if entry.is_dir()) if not classes: raise FileNotFoundError( f"Couldn't find any class folder in {directory}.") class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)} return classes, class_to_idx
Finds the class folders in a dataset. See :class:`DatasetFolder` for details.
find_classes
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py
Apache-2.0
def make_dataset( directory: str, class_to_idx: Optional[Dict[str, int]]=None, extensions: Optional[Tuple[str, ...]]=None, is_valid_file: Optional[Callable[[str], bool]]=None, ) -> List[Tuple[ str, int]]: """Generates a list of samples of a form (path_to_sample, class). See :class:`DatasetFolder` for details. Note: The class_to_idx parameter is here optional and will use the logic of the ``find_classes`` function by default. """ directory = os.path.expanduser(directory) if class_to_idx is None: _, class_to_idx = find_classes(directory) elif not class_to_idx: raise ValueError( "'class_to_index' must have at least one entry to collect any samples." ) both_none = extensions is None and is_valid_file is None both_something = extensions is not None and is_valid_file is not None if both_none or both_something: raise ValueError( "Both extensions and is_valid_file cannot be None or not None at the same time" ) if extensions is not None: def is_valid_file(x: str) -> bool: return has_file_allowed_extension( x, cast(Tuple[str, ...], extensions)) is_valid_file = cast(Callable[[str], bool], is_valid_file) instances = [] available_classes = set() for target_class in sorted(class_to_idx.keys()): class_index = class_to_idx[target_class] target_dir = os.path.join(directory, target_class) if not os.path.isdir(target_dir): continue for root, _, fnames in sorted(os.walk(target_dir, followlinks=True)): for fname in sorted(fnames): if is_valid_file(fname): path = os.path.join(root, fname) item = path, class_index instances.append(item) if target_class not in available_classes: available_classes.add(target_class) # print(fname) # exit() # empty_classes = set(class_to_idx.keys()) - available_classes # if empty_classes: # msg = f"Found no valid file for the classes {', '.join(sorted(empty_classes))}. " # if extensions is not None: # msg += f"Supported extensions are: {', '.join(extensions)}" # raise FileNotFoundError(msg) return instances
Generates a list of samples of a form (path_to_sample, class). See :class:`DatasetFolder` for details. Note: The class_to_idx parameter is here optional and will use the logic of the ``find_classes`` function by default.
make_dataset
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py
Apache-2.0
def make_dataset( directory: str, class_to_idx: Dict[str, int], extensions: Optional[Tuple[str, ...]]=None, is_valid_file: Optional[Callable[[str], bool]]=None, ) -> List[ Tuple[str, int]]: """Generates a list of samples of a form (path_to_sample, class). This can be overridden to e.g. read files from a compressed zip file instead of from the disk. Args: directory (str): root dataset directory, corresponding to ``self.root``. class_to_idx (Dict[str, int]): Dictionary mapping class name to class index. extensions (optional): A list of allowed extensions. Either extensions or is_valid_file should be passed. Defaults to None. is_valid_file (optional): A function that takes path of a file and checks if the file is a valid file (used to check of corrupt files) both extensions and is_valid_file should not be passed. Defaults to None. Raises: ValueError: In case ``class_to_idx`` is empty. ValueError: In case ``extensions`` and ``is_valid_file`` are None or both are not None. FileNotFoundError: In case no valid file was found for any class. Returns: List[Tuple[str, int]]: samples of a form (path_to_sample, class) """ if class_to_idx is None: # prevent potential bug since make_dataset() would use the class_to_idx logic of the # find_classes() function, instead of using that of the find_classes() method, which # is potentially overridden and thus could have a different logic. raise ValueError("The class_to_idx parameter cannot be None.") return make_dataset( directory, class_to_idx, extensions=extensions, is_valid_file=is_valid_file)
Generates a list of samples of a form (path_to_sample, class). This can be overridden to e.g. read files from a compressed zip file instead of from the disk. Args: directory (str): root dataset directory, corresponding to ``self.root``. class_to_idx (Dict[str, int]): Dictionary mapping class name to class index. extensions (optional): A list of allowed extensions. Either extensions or is_valid_file should be passed. Defaults to None. is_valid_file (optional): A function that takes path of a file and checks if the file is a valid file (used to check of corrupt files) both extensions and is_valid_file should not be passed. Defaults to None. Raises: ValueError: In case ``class_to_idx`` is empty. ValueError: In case ``extensions`` and ``is_valid_file`` are None or both are not None. FileNotFoundError: In case no valid file was found for any class. Returns: List[Tuple[str, int]]: samples of a form (path_to_sample, class)
make_dataset
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py
Apache-2.0
def __getitem__(self, index: int) -> Tuple[Any, Any]: """ Args: index (int): Index Returns: tuple: (sample, target) where target is class_index of the target class. """ path, target = self.samples[index] sample = self.loader(path) if self.transform is not None: sample = self.transform(sample) if self.target_transform is not None: target = self.target_transform(target) return sample, target
Args: index (int): Index Returns: tuple: (sample, target) where target is class_index of the target class.
__getitem__
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/datasets/folder.py
Apache-2.0
def _make_divisible(v: float, divisor: int, min_value: Optional[int]=None) -> int: """ This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py """ if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v
This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
_make_divisible
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py
Apache-2.0
def __init__( self, inverted_residual_setting: List[InvertedResidualConfig], last_channel: int, num_classes: int=1000, block: Optional[Callable[..., nn.Layer]]=None, norm_layer: Optional[Callable[..., nn.Layer]]=None, dropout: float=0.2, **kwargs: Any, ) -> None: """ MobileNet V3 main class Args: inverted_residual_setting (List[InvertedResidualConfig]): Network structure last_channel (int): The number of channels on the penultimate layer num_classes (int): Number of classes block (Optional[Callable[..., nn.Layer]]): Module specifying inverted residual building block for mobilenet norm_layer (Optional[Callable[..., nn.Layer]]): Module specifying the normalization layer to use dropout (float): The droupout probability """ super().__init__() if not inverted_residual_setting: raise ValueError( "The inverted_residual_setting should not be empty") elif not (isinstance(inverted_residual_setting, Sequence) and all([ isinstance(s, InvertedResidualConfig) for s in inverted_residual_setting ])): raise TypeError( "The inverted_residual_setting should be List[InvertedResidualConfig]" ) if block is None: block = InvertedResidual if norm_layer is None: norm_layer = partial(nn.BatchNorm2D, epsilon=0.001, momentum=0.01) layers: List[nn.Layer] = [] # building first layer firstconv_output_channels = inverted_residual_setting[0].input_channels layers.append( ConvNormActivation( 3, firstconv_output_channels, kernel_size=3, stride=2, norm_layer=norm_layer, activation_layer=nn.Hardswish, )) # building inverted residual blocks for cnf in inverted_residual_setting: layers.append(block(cnf, norm_layer)) # building last several layers lastconv_input_channels = inverted_residual_setting[-1].out_channels lastconv_output_channels = 6 * lastconv_input_channels layers.append( ConvNormActivation( lastconv_input_channels, lastconv_output_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=nn.Hardswish, )) self.features = nn.Sequential(*layers) self.avgpool = nn.AdaptiveAvgPool2D(1) self.classifier = nn.Sequential( nn.Linear(lastconv_output_channels, last_channel), nn.Hardswish(), nn.Dropout(p=dropout), nn.Linear(last_channel, num_classes), )
MobileNet V3 main class Args: inverted_residual_setting (List[InvertedResidualConfig]): Network structure last_channel (int): The number of channels on the penultimate layer num_classes (int): Number of classes block (Optional[Callable[..., nn.Layer]]): Module specifying inverted residual building block for mobilenet norm_layer (Optional[Callable[..., nn.Layer]]): Module specifying the normalization layer to use dropout (float): The droupout probability
__init__
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py
Apache-2.0
def mobilenet_v3_large(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> MobileNetV3: """ Constructs a large MobileNetV3 architecture from `"Searching for MobileNetV3" <https://arxiv.org/abs/1905.02244>`_. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ arch = "mobilenet_v3_large" inverted_residual_setting, last_channel = _mobilenet_v3_conf(arch, **kwargs) return _mobilenet_v3(arch, inverted_residual_setting, last_channel, pretrained, progress, **kwargs)
Constructs a large MobileNetV3 architecture from `"Searching for MobileNetV3" <https://arxiv.org/abs/1905.02244>`_. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr
mobilenet_v3_large
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py
Apache-2.0
def mobilenet_v3_small(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> MobileNetV3: """ Constructs a small MobileNetV3 architecture from `"Searching for MobileNetV3" <https://arxiv.org/abs/1905.02244>`_. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ arch = "mobilenet_v3_small" inverted_residual_setting, last_channel = _mobilenet_v3_conf(arch, **kwargs) return _mobilenet_v3(arch, inverted_residual_setting, last_channel, pretrained, progress, **kwargs)
Constructs a small MobileNetV3 architecture from `"Searching for MobileNetV3" <https://arxiv.org/abs/1905.02244>`_. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr
mobilenet_v3_small
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/models/mobilenet_v3_paddle.py
Apache-2.0
def get_params(transform_num: int) -> Tuple[int, Tensor, Tensor]: """Get parameters for autoaugment transformation Returns: params required by the autoaugment transformation """ policy_id = int(paddle.randint(low=0, high=transform_num, shape=(1, ))) probs = paddle.rand((2, )) signs = paddle.randint(low=0, high=2, shape=(2, )) return policy_id, probs, signs
Get parameters for autoaugment transformation Returns: params required by the autoaugment transformation
get_params
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/autoaugment.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/autoaugment.py
Apache-2.0
def forward(self, img: Tensor): """ img (PIL Image or Tensor): Image to be transformed. Returns: PIL Image or Tensor: AutoAugmented image. """ fill = self.fill if isinstance(img, Tensor): if isinstance(fill, (int, float)): fill = [float(fill)] * F._get_image_num_channels(img) elif fill is not None: fill = [float(f) for f in fill] transform_id, probs, signs = self.get_params(len(self.transforms)) for i, (op_name, p, magnitude_id) in enumerate(self.transforms[transform_id]): if probs[i] <= p: magnitudes, signed = self._get_op_meta(op_name) magnitude = float(magnitudes[magnitude_id].item()) \ if magnitudes is not None and magnitude_id is not None else 0.0 if signed is not None and signed and signs[i] == 0: magnitude *= -1.0 if op_name == "ShearX": img = F.affine( img, angle=0.0, translate=[0, 0], scale=1.0, shear=[math.degrees(magnitude), 0.0], interpolation=self.interpolation, fill=fill) elif op_name == "ShearY": img = F.affine( img, angle=0.0, translate=[0, 0], scale=1.0, shear=[0.0, math.degrees(magnitude)], interpolation=self.interpolation, fill=fill) elif op_name == "TranslateX": img = F.affine( img, angle=0.0, translate=[ int(F._get_image_size(img)[0] * magnitude), 0 ], scale=1.0, interpolation=self.interpolation, shear=[0.0, 0.0], fill=fill) elif op_name == "TranslateY": img = F.affine( img, angle=0.0, translate=[ 0, int(F._get_image_size(img)[1] * magnitude) ], scale=1.0, interpolation=self.interpolation, shear=[0.0, 0.0], fill=fill) elif op_name == "Rotate": img = F.rotate( img, magnitude, interpolation=self.interpolation, fill=fill) elif op_name == "Brightness": img = F.adjust_brightness(img, 1.0 + magnitude) elif op_name == "Color": img = F.adjust_saturation(img, 1.0 + magnitude) elif op_name == "Contrast": img = F.adjust_contrast(img, 1.0 + magnitude) elif op_name == "Sharpness": img = F.adjust_sharpness(img, 1.0 + magnitude) elif op_name == "Posterize": img = F.posterize(img, int(magnitude)) elif op_name == "Solarize": img = F.solarize(img, magnitude) elif op_name == "AutoContrast": img = F.autocontrast(img) elif op_name == "Equalize": img = F.equalize(img) elif op_name == "Invert": img = F.invert(img) else: raise ValueError( "The provided operator {} is not recognized.".format( op_name)) return img
img (PIL Image or Tensor): Image to be transformed. Returns: PIL Image or Tensor: AutoAugmented image.
forward
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/autoaugment.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/autoaugment.py
Apache-2.0
def to_tensor(pic): """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. See :class:`~paddlevision.transforms.ToTensor` for more details. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ if not (F_pil._is_pil_image(pic) or _is_numpy(pic)): raise TypeError('pic should be PIL Image or ndarray. Got {}'.format( type(pic))) if _is_numpy(pic) and not _is_numpy_image(pic): raise ValueError('pic should be 2/3 dimensional. Got {} dimensions.'. format(pic.ndim)) default_float_dtype = paddle.get_default_dtype() if isinstance(pic, np.ndarray): # handle numpy array if pic.ndim == 2: pic = pic[:, :, None] img = paddle.to_tensor(pic.transpose((2, 0, 1))) # backward compatibility if not img.dtype == default_float_dtype: img = img.astype(dtype=default_float_dtype) return img.divide(paddle.full_like(img, 255)) else: return img if accimage is not None and isinstance(pic, accimage.Image): nppic = np.zeros( [pic.channels, pic.height, pic.width], dtype=np.float32) pic.copyto(nppic) return paddle.to_tensor(nppic).astype(dtype=default_float_dtype) # handle PIL Image mode_to_nptype = {'I': np.int32, 'I;16': np.int16, 'F': np.float32} img = paddle.to_tensor( np.array( pic, mode_to_nptype.get(pic.mode, np.uint8), copy=True)) if pic.mode == '1': img = 255 * img img = img.reshape([pic.size[1], pic.size[0], len(pic.getbands())]) if not img.dtype == default_float_dtype: img = img.astype(dtype=default_float_dtype) # put it from HWC to CHW format img = img.transpose((2, 0, 1)) return img.divide(paddle.full_like(img, 255)) else: # put it from HWC to CHW format img = img.transpose((2, 0, 1)) return img
Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. See :class:`~paddlevision.transforms.ToTensor` for more details. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image.
to_tensor
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py
Apache-2.0
def normalize(tensor: Tensor, mean: List[float], std: List[float], inplace: bool=False) -> Tensor: """Normalize a float tensor image with mean and standard deviation. This transform does not support PIL Image. .. note:: This transform acts out of place by default, i.e., it does not mutates the input tensor. See :class:`~paddlevision.transforms.Normalize` for more details. Args: tensor (Tensor): Float tensor image of size (C, H, W) or (B, C, H, W) to be normalized. mean (sequence): Sequence of means for each channel. std (sequence): Sequence of standard deviations for each channel. inplace(bool,optional): Bool to make this operation inplace. Returns: Tensor: Normalized Tensor image. """ if not isinstance(tensor, paddle.Tensor): raise TypeError('Input tensor should be a paddle tensor. Got {}.'. format(type(tensor))) if not tensor.dtype in (paddle.float16, paddle.float32, paddle.float64): raise TypeError('Input tensor should be a float tensor. Got {}.'. format(tensor.dtype)) if tensor.ndim < 3: raise ValueError( 'Expected tensor to be a tensor image of size (..., C, H, W). Got tensor.shape() = ' '{}.'.format(tensor.shape)) if not inplace: tensor = tensor.clone() dtype = tensor.dtype mean = paddle.to_tensor(mean, dtype=dtype, place=tensor.place) std = paddle.to_tensor(std, dtype=dtype, place=tensor.place) if (std == 0).any(): raise ValueError('std evaluated to zero, leading to division by zero.') if mean.ndim == 1: mean = mean.reshape((-1, 1, 1)) if std.ndim == 1: std = std.reshape((-1, 1, 1)) tensor = tensor.subtract(mean).divide(std) return tensor
Normalize a float tensor image with mean and standard deviation. This transform does not support PIL Image. .. note:: This transform acts out of place by default, i.e., it does not mutates the input tensor. See :class:`~paddlevision.transforms.Normalize` for more details. Args: tensor (Tensor): Float tensor image of size (C, H, W) or (B, C, H, W) to be normalized. mean (sequence): Sequence of means for each channel. std (sequence): Sequence of standard deviations for each channel. inplace(bool,optional): Bool to make this operation inplace. Returns: Tensor: Normalized Tensor image.
normalize
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py
Apache-2.0
def resize(img: Tensor, size: List[int], interpolation: InterpolationMode=InterpolationMode.BILINEAR, max_size: Optional[int]=None, antialias: Optional[bool]=None) -> Tensor: r"""Resize the input image to the given size. If the image is paddle Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions .. warning:: The output image might be different depending on its type: when downsampling, the interpolation of PIL images and tensors is slightly different, because PIL applies antialiasing. This may lead to significant differences in the performance of a network. Therefore, it is preferable to train and serve a model with the same input types. See also below the ``antialias`` parameter, which can help making the output of PIL images and tensors closer. Args: img (PIL Image or Tensor): Image to be resized. size (sequence or int): Desired output size. If size is a sequence like (h, w), the output size will be matched to this. If size is an int, the smaller edge of the image will be matched to this number maintaining the aspect ratio. i.e, if height > width, then image will be rescaled to :math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)`. interpolation (InterpolationMode): Desired interpolation enum defined by :class:`paddlevision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported. For backward compatibility integer values (e.g. ``PIL.Image.NEAREST``) are still acceptable. max_size (int, optional): The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater than ``max_size`` after being resized according to ``size``, then the image is resized again so that the longer edge is equal to ``max_size``. As a result, ``size`` might be overruled, i.e the smaller edge may be shorter than ``size``. antialias (bool, optional): antialias flag. If ``img`` is PIL Image, the flag is ignored and anti-alias is always used. If ``img`` is Tensor, the flag is False by default and can be set to True for ``InterpolationMode.BILINEAR`` only mode. This can help making the output for PIL images and tensors closer. .. warning:: There is no autodiff support for ``antialias=True`` option with input ``img`` as Tensor. Returns: PIL Image or Tensor: Resized image. """ # Backward compatibility with integer value if isinstance(interpolation, int): warnings.warn( "Argument interpolation should be of type InterpolationMode instead of int. " "Please, use InterpolationMode enum.") interpolation = _interpolation_modes_from_int(interpolation) if not isinstance(interpolation, InterpolationMode): raise TypeError("Argument interpolation should be a InterpolationMode") if not isinstance(img, paddle.Tensor): if antialias is not None and not antialias: warnings.warn( "Anti-alias option is always applied for PIL Image input. Argument antialias is ignored." ) pil_interpolation = pil_modes_mapping[interpolation] return F_pil.resize( img, size=size, interpolation=pil_interpolation, max_size=max_size) return F_t.resize( img, size=size, interpolation=interpolation.value, max_size=max_size, antialias=antialias)
Resize the input image to the given size. If the image is paddle Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions .. warning:: The output image might be different depending on its type: when downsampling, the interpolation of PIL images and tensors is slightly different, because PIL applies antialiasing. This may lead to significant differences in the performance of a network. Therefore, it is preferable to train and serve a model with the same input types. See also below the ``antialias`` parameter, which can help making the output of PIL images and tensors closer. Args: img (PIL Image or Tensor): Image to be resized. size (sequence or int): Desired output size. If size is a sequence like (h, w), the output size will be matched to this. If size is an int, the smaller edge of the image will be matched to this number maintaining the aspect ratio. i.e, if height > width, then image will be rescaled to :math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)`. interpolation (InterpolationMode): Desired interpolation enum defined by :class:`paddlevision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported. For backward compatibility integer values (e.g. ``PIL.Image.NEAREST``) are still acceptable. max_size (int, optional): The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater than ``max_size`` after being resized according to ``size``, then the image is resized again so that the longer edge is equal to ``max_size``. As a result, ``size`` might be overruled, i.e the smaller edge may be shorter than ``size``. antialias (bool, optional): antialias flag. If ``img`` is PIL Image, the flag is ignored and anti-alias is always used. If ``img`` is Tensor, the flag is False by default and can be set to True for ``InterpolationMode.BILINEAR`` only mode. This can help making the output for PIL images and tensors closer. .. warning:: There is no autodiff support for ``antialias=True`` option with input ``img`` as Tensor. Returns: PIL Image or Tensor: Resized image.
resize
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py
Apache-2.0
def pad(img: Tensor, padding: List[int], fill: int=0, padding_mode: str="constant") -> Tensor: r"""Pad the given image on all sides with the given "pad" value. If the image is paddle Tensor, it is expected to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric, at most 3 leading dimensions for mode edge, and an arbitrary number of leading dimensions for mode constant Args: img (PIL Image or Tensor): Image to be padded. padding (int or sequence): Padding on each border. If a single int is provided this is used to pad all borders. If sequence of length 2 is provided this is the padding on left/right and top/bottom respectively. If a sequence of length 4 is provided this is the padding for the left, top, right and bottom borders respectively. fill (number or str or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. This value is only used when the padding_mode is constant. Only number is supported for paddle Tensor. Only int or str or tuple value is supported for PIL Image. padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant. - constant: pads with a constant value, this value is specified with fill - edge: pads with the last value at the edge of the image. If input a 5D paddle Tensor, the last 3 dimensions will be padded instead of the last 2 - reflect: pads with reflection of image without repeating the last value on the edge. For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode will result in [3, 2, 1, 2, 3, 4, 3, 2] - symmetric: pads with reflection of image repeating the last value on the edge. For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode will result in [2, 1, 1, 2, 3, 4, 4, 3] Returns: PIL Image or Tensor: Padded image. """ if not isinstance(img, paddle.Tensor): return F_pil.pad(img, padding=padding, fill=fill, padding_mode=padding_mode) return F_t.pad(img, padding=padding, fill=fill, padding_mode=padding_mode)
Pad the given image on all sides with the given "pad" value. If the image is paddle Tensor, it is expected to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric, at most 3 leading dimensions for mode edge, and an arbitrary number of leading dimensions for mode constant Args: img (PIL Image or Tensor): Image to be padded. padding (int or sequence): Padding on each border. If a single int is provided this is used to pad all borders. If sequence of length 2 is provided this is the padding on left/right and top/bottom respectively. If a sequence of length 4 is provided this is the padding for the left, top, right and bottom borders respectively. fill (number or str or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. This value is only used when the padding_mode is constant. Only number is supported for paddle Tensor. Only int or str or tuple value is supported for PIL Image. padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant. - constant: pads with a constant value, this value is specified with fill - edge: pads with the last value at the edge of the image. If input a 5D paddle Tensor, the last 3 dimensions will be padded instead of the last 2 - reflect: pads with reflection of image without repeating the last value on the edge. For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode will result in [3, 2, 1, 2, 3, 4, 3, 2] - symmetric: pads with reflection of image repeating the last value on the edge. For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode will result in [2, 1, 1, 2, 3, 4, 4, 3] Returns: PIL Image or Tensor: Padded image.
pad
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py
Apache-2.0
def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor: """Crop the given image at specified location and output size. If the image is paddle Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. If image size is smaller than output size along any edge, image is padded with 0 and then cropped. Args: img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image. top (int): Vertical component of the top left corner of the crop box. left (int): Horizontal component of the top left corner of the crop box. height (int): Height of the crop box. width (int): Width of the crop box. Returns: PIL Image or Tensor: Cropped image. """ if not isinstance(img, paddle.Tensor): return F_pil.crop(img, top, left, height, width) return F_t.crop(img, top, left, height, width)
Crop the given image at specified location and output size. If the image is paddle Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. If image size is smaller than output size along any edge, image is padded with 0 and then cropped. Args: img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image. top (int): Vertical component of the top left corner of the crop box. left (int): Horizontal component of the top left corner of the crop box. height (int): Height of the crop box. width (int): Width of the crop box. Returns: PIL Image or Tensor: Cropped image.
crop
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py
Apache-2.0
def center_crop(img: Tensor, output_size: List[int]) -> Tensor: """Crops the given image at the center. If the image is paddle Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. If image size is smaller than output size along any edge, image is padded with 0 and then center cropped. Args: img (PIL Image or Tensor): Image to be cropped. output_size (sequence or int): (height, width) of the crop box. If int or sequence with single int, it is used for both directions. Returns: PIL Image or Tensor: Cropped image. """ if isinstance(output_size, numbers.Number): output_size = (int(output_size), int(output_size)) elif isinstance(output_size, (tuple, list)) and len(output_size) == 1: output_size = (output_size[0], output_size[0]) image_width, image_height = _get_image_size(img) crop_height, crop_width = output_size if crop_width > image_width or crop_height > image_height: padding_ltrb = [ (crop_width - image_width) // 2 if crop_width > image_width else 0, (crop_height - image_height) // 2 if crop_height > image_height else 0, (crop_width - image_width + 1) // 2 if crop_width > image_width else 0, (crop_height - image_height + 1) // 2 if crop_height > image_height else 0, ] img = pad(img, padding_ltrb, fill=0) # PIL uses fill value 0 image_width, image_height = _get_image_size(img) if crop_width == image_width and crop_height == image_height: return img crop_top = int(round((image_height - crop_height) / 2.)) crop_left = int(round((image_width - crop_width) / 2.)) return crop(img, crop_top, crop_left, crop_height, crop_width)
Crops the given image at the center. If the image is paddle Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. If image size is smaller than output size along any edge, image is padded with 0 and then center cropped. Args: img (PIL Image or Tensor): Image to be cropped. output_size (sequence or int): (height, width) of the crop box. If int or sequence with single int, it is used for both directions. Returns: PIL Image or Tensor: Cropped image.
center_crop
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py
Apache-2.0
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/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/functional.py
Apache-2.0
def 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/Step1-5/mobilenetv3_paddle/paddlevision/transforms/transforms.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/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/Step1-5/mobilenetv3_paddle/paddlevision/transforms/transforms.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_paddle/paddlevision/transforms/transforms.py
Apache-2.0
def average_checkpoints(inputs): """Loads checkpoints from inputs and returns a model with averaged weights. Original implementation taken from: https://github.com/pytorch/fairseq/blob/a48f235636557b8d3bc4922a6fa90f3a0fa57955/scripts/average_checkpoints.py#L16 Args: inputs (List[str]): An iterable of string paths of checkpoints to load from. Returns: A dict of string keys mapping to various values. The 'model' key from the returned dict should correspond to an OrderedDict mapping string parameter names to torch Tensors. """ params_dict = OrderedDict() params_keys = None new_state = None num_models = len(inputs) for fpath in inputs: with open(fpath, "rb") as f: state = torch.load( f, map_location=( lambda s, _: torch.serialization.default_restore_location(s, "cpu") ), ) # Copies over the settings from the first checkpoint if new_state is None: new_state = state model_params = state["model"] model_params_keys = list(model_params.keys()) if params_keys is None: params_keys = model_params_keys elif params_keys != model_params_keys: raise KeyError("For checkpoint {}, expected list of params: {}, " "but found: {}".format(f, params_keys, model_params_keys)) for k in params_keys: p = model_params[k] if isinstance(p, torch.HalfTensor): p = p.float() if k not in params_dict: params_dict[k] = p.clone() # NOTE: clone() is needed in case of p is a shared parameter else: params_dict[k] += p averaged_params = OrderedDict() for k, v in params_dict.items(): averaged_params[k] = v if averaged_params[k].is_floating_point(): averaged_params[k].div_(num_models) else: averaged_params[k] //= num_models new_state["model"] = averaged_params return new_state
Loads checkpoints from inputs and returns a model with averaged weights. Original implementation taken from: https://github.com/pytorch/fairseq/blob/a48f235636557b8d3bc4922a6fa90f3a0fa57955/scripts/average_checkpoints.py#L16 Args: inputs (List[str]): An iterable of string paths of checkpoints to load from. Returns: A dict of string keys mapping to various values. The 'model' key from the returned dict should correspond to an OrderedDict mapping string parameter names to torch Tensors.
average_checkpoints
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/utils.py
Apache-2.0
def store_model_weights(model, checkpoint_path, checkpoint_key='model', strict=True): """ This method can be used to prepare weights files for new models. It receives as input a model architecture and a checkpoint from the training script and produces a file with the weights ready for release. Examples: from torchvision import models as M # Classification model = M.mobilenet_v3_large(pretrained=False) print(store_model_weights(model, './class.pth')) # Quantized Classification model = M.quantization.mobilenet_v3_large(pretrained=False, quantize=False) model.fuse_model() model.qconfig = torch.quantization.get_default_qat_qconfig('qnnpack') _ = torch.quantization.prepare_qat(model, inplace=True) print(store_model_weights(model, './qat.pth')) # Object Detection model = M.detection.fasterrcnn_mobilenet_v3_large_fpn(pretrained=False, pretrained_backbone=False) print(store_model_weights(model, './obj.pth')) # Segmentation model = M.segmentation.deeplabv3_mobilenet_v3_large(pretrained=False, pretrained_backbone=False, aux_loss=True) print(store_model_weights(model, './segm.pth', strict=False)) Args: model (pytorch.nn.Module): The model on which the weights will be loaded for validation purposes. checkpoint_path (str): The path of the checkpoint we will load. checkpoint_key (str, optional): The key of the checkpoint where the model weights are stored. Default: "model". strict (bool): whether to strictly enforce that the keys in :attr:`state_dict` match the keys returned by this module's :meth:`~torch.nn.Module.state_dict` function. Default: ``True`` Returns: output_path (str): The location where the weights are saved. """ # Store the new model next to the checkpoint_path checkpoint_path = os.path.abspath(checkpoint_path) output_dir = os.path.dirname(checkpoint_path) # Deep copy to avoid side-effects on the model object. model = copy.deepcopy(model) checkpoint = torch.load(checkpoint_path, map_location='cpu') # Load the weights to the model to validate that everything works # and remove unnecessary weights (such as auxiliaries, etc) model.load_state_dict(checkpoint[checkpoint_key], strict=strict) tmp_path = os.path.join(output_dir, str(model.__hash__())) torch.save(model.state_dict(), tmp_path) sha256_hash = hashlib.sha256() with open(tmp_path, "rb") as f: # Read and update hash string value in blocks of 4K for byte_block in iter(lambda: f.read(4096), b""): sha256_hash.update(byte_block) hh = sha256_hash.hexdigest() output_path = os.path.join(output_dir, "weights-" + str(hh[:8]) + ".pth") os.replace(tmp_path, output_path) return output_path
This method can be used to prepare weights files for new models. It receives as input a model architecture and a checkpoint from the training script and produces a file with the weights ready for release. Examples: from torchvision import models as M # Classification model = M.mobilenet_v3_large(pretrained=False) print(store_model_weights(model, './class.pth')) # Quantized Classification model = M.quantization.mobilenet_v3_large(pretrained=False, quantize=False) model.fuse_model() model.qconfig = torch.quantization.get_default_qat_qconfig('qnnpack') _ = torch.quantization.prepare_qat(model, inplace=True) print(store_model_weights(model, './qat.pth')) # Object Detection model = M.detection.fasterrcnn_mobilenet_v3_large_fpn(pretrained=False, pretrained_backbone=False) print(store_model_weights(model, './obj.pth')) # Segmentation model = M.segmentation.deeplabv3_mobilenet_v3_large(pretrained=False, pretrained_backbone=False, aux_loss=True) print(store_model_weights(model, './segm.pth', strict=False)) Args: model (pytorch.nn.Module): The model on which the weights will be loaded for validation purposes. checkpoint_path (str): The path of the checkpoint we will load. checkpoint_key (str, optional): The key of the checkpoint where the model weights are stored. Default: "model". strict (bool): whether to strictly enforce that the keys in :attr:`state_dict` match the keys returned by this module's :meth:`~torch.nn.Module.state_dict` function. Default: ``True`` Returns: output_path (str): The location where the weights are saved.
store_model_weights
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/utils.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/utils.py
Apache-2.0
def __init__( self, inverted_residual_setting: List[InvertedResidualConfig], last_channel: int, num_classes: int=1000, block: Optional[Callable[..., nn.Module]]=None, norm_layer: Optional[Callable[..., nn.Module]]=None, dropout: float=0.2, **kwargs: Any, ) -> None: """ MobileNet V3 main class Args: inverted_residual_setting (List[InvertedResidualConfig]): Network structure last_channel (int): The number of channels on the penultimate layer num_classes (int): Number of classes block (Optional[Callable[..., nn.Module]]): Module specifying inverted residual building block for mobilenet norm_layer (Optional[Callable[..., nn.Module]]): Module specifying the normalization layer to use dropout (float): The droupout probability """ super().__init__() if not inverted_residual_setting: raise ValueError( "The inverted_residual_setting should not be empty") elif not (isinstance(inverted_residual_setting, Sequence) and all([ isinstance(s, InvertedResidualConfig) for s in inverted_residual_setting ])): raise TypeError( "The inverted_residual_setting should be List[InvertedResidualConfig]" ) if block is None: block = InvertedResidual if norm_layer is None: norm_layer = partial(nn.BatchNorm2d, eps=0.001, momentum=0.01) layers: List[nn.Module] = [] # building first layer firstconv_output_channels = inverted_residual_setting[0].input_channels layers.append( ConvNormActivation( 3, firstconv_output_channels, kernel_size=3, stride=2, norm_layer=norm_layer, activation_layer=nn.Hardswish, )) # building inverted residual blocks for cnf in inverted_residual_setting: layers.append(block(cnf, norm_layer)) # building last several layers lastconv_input_channels = inverted_residual_setting[-1].out_channels lastconv_output_channels = 6 * lastconv_input_channels layers.append( ConvNormActivation( lastconv_input_channels, lastconv_output_channels, kernel_size=1, norm_layer=norm_layer, activation_layer=nn.Hardswish, )) self.features = nn.Sequential(*layers) self.avgpool = nn.AdaptiveAvgPool2d(1) self.classifier = nn.Sequential( nn.Linear(lastconv_output_channels, last_channel), nn.Hardswish(inplace=True), nn.Dropout( p=dropout, inplace=True), nn.Linear(last_channel, num_classes), ) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode="fan_out") if m.bias is not None: nn.init.zeros_(m.bias) elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.ones_(m.weight) nn.init.zeros_(m.bias) elif isinstance(m, nn.Linear): nn.init.normal_(m.weight, 0, 0.01) nn.init.zeros_(m.bias)
MobileNet V3 main class Args: inverted_residual_setting (List[InvertedResidualConfig]): Network structure last_channel (int): The number of channels on the penultimate layer num_classes (int): Number of classes block (Optional[Callable[..., nn.Module]]): Module specifying inverted residual building block for mobilenet norm_layer (Optional[Callable[..., nn.Module]]): Module specifying the normalization layer to use dropout (float): The droupout probability
__init__
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/models/mobilenet_v3_torch.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/models/mobilenet_v3_torch.py
Apache-2.0
def to_tensor(pic): """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. This function does not support torchscript. See :class:`~torchvision.transforms.ToTensor` for more details. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image. """ if not (F_pil._is_pil_image(pic) or _is_numpy(pic)): raise TypeError('pic should be PIL Image or ndarray. Got {}'.format( type(pic))) if _is_numpy(pic) and not _is_numpy_image(pic): raise ValueError('pic should be 2/3 dimensional. Got {} dimensions.'. format(pic.ndim)) default_float_dtype = torch.get_default_dtype() if isinstance(pic, np.ndarray): # handle numpy array if pic.ndim == 2: pic = pic[:, :, None] img = torch.from_numpy(pic.transpose((2, 0, 1))).contiguous() # backward compatibility if isinstance(img, torch.ByteTensor): return img.to(dtype=default_float_dtype).div(255) else: return img if accimage is not None and isinstance(pic, accimage.Image): nppic = np.zeros( [pic.channels, pic.height, pic.width], dtype=np.float32) pic.copyto(nppic) return torch.from_numpy(nppic).to(dtype=default_float_dtype) # handle PIL Image mode_to_nptype = {'I': np.int32, 'I;16': np.int16, 'F': np.float32} img = torch.from_numpy( np.array( pic, mode_to_nptype.get(pic.mode, np.uint8), copy=True)) if pic.mode == '1': img = 255 * img img = img.view(pic.size[1], pic.size[0], len(pic.getbands())) # put it from HWC to CHW format img = img.permute((2, 0, 1)).contiguous() if isinstance(img, torch.ByteTensor): return img.to(dtype=default_float_dtype).div(255) else: return img
Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor. This function does not support torchscript. See :class:`~torchvision.transforms.ToTensor` for more details. Args: pic (PIL Image or numpy.ndarray): Image to be converted to tensor. Returns: Tensor: Converted image.
to_tensor
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def pil_to_tensor(pic): """Convert a ``PIL Image`` to a tensor of the same type. This function does not support torchscript. See :class:`~torchvision.transforms.PILToTensor` for more details. Args: pic (PIL Image): Image to be converted to tensor. Returns: Tensor: Converted image. """ if not F_pil._is_pil_image(pic): raise TypeError('pic should be PIL Image. Got {}'.format(type(pic))) if accimage is not None and isinstance(pic, accimage.Image): # accimage format is always uint8 internally, so always return uint8 here nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.uint8) pic.copyto(nppic) return torch.as_tensor(nppic) # handle PIL Image img = torch.as_tensor(np.asarray(pic)) img = img.view(pic.size[1], pic.size[0], len(pic.getbands())) # put it from HWC to CHW format img = img.permute((2, 0, 1)) return img
Convert a ``PIL Image`` to a tensor of the same type. This function does not support torchscript. See :class:`~torchvision.transforms.PILToTensor` for more details. Args: pic (PIL Image): Image to be converted to tensor. Returns: Tensor: Converted image.
pil_to_tensor
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def convert_image_dtype(image: torch.Tensor, dtype: torch.dtype=torch.float) -> torch.Tensor: """Convert a tensor image to the given ``dtype`` and scale the values accordingly This function does not support PIL Image. Args: image (torch.Tensor): Image to be converted dtype (torch.dtype): Desired data type of the output Returns: Tensor: Converted image .. note:: When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly. If converted back and forth, this mismatch has no effect. Raises: RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range of the integer ``dtype``. """ if not isinstance(image, torch.Tensor): raise TypeError('Input img should be Tensor Image') return F_t.convert_image_dtype(image, dtype)
Convert a tensor image to the given ``dtype`` and scale the values accordingly This function does not support PIL Image. Args: image (torch.Tensor): Image to be converted dtype (torch.dtype): Desired data type of the output Returns: Tensor: Converted image .. note:: When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly. If converted back and forth, this mismatch has no effect. Raises: RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range of the integer ``dtype``.
convert_image_dtype
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def to_pil_image(pic, mode=None): """Convert a tensor or an ndarray to PIL Image. This function does not support torchscript. See :class:`~torchvision.transforms.ToPILImage` for more details. Args: pic (Tensor or numpy.ndarray): Image to be converted to PIL Image. mode (`PIL.Image mode`_): color space and pixel depth of input data (optional). .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes Returns: PIL Image: Image converted to PIL Image. """ if not (isinstance(pic, torch.Tensor) or isinstance(pic, np.ndarray)): raise TypeError('pic should be Tensor or ndarray. Got {}.'.format( type(pic))) elif isinstance(pic, torch.Tensor): if pic.ndimension() not in {2, 3}: raise ValueError( 'pic should be 2/3 dimensional. Got {} dimensions.'.format( pic.ndimension())) elif pic.ndimension() == 2: # if 2D image, add channel dimension (CHW) pic = pic.unsqueeze(0) # check number of channels if pic.shape[-3] > 4: raise ValueError( 'pic should not have > 4 channels. Got {} channels.'.format( pic.shape[-3])) elif isinstance(pic, np.ndarray): if pic.ndim not in {2, 3}: raise ValueError( 'pic should be 2/3 dimensional. Got {} dimensions.'.format( pic.ndim)) elif pic.ndim == 2: # if 2D image, add channel dimension (HWC) pic = np.expand_dims(pic, 2) # check number of channels if pic.shape[-1] > 4: raise ValueError( 'pic should not have > 4 channels. Got {} channels.'.format( pic.shape[-1])) npimg = pic if isinstance(pic, torch.Tensor): if pic.is_floating_point() and mode != 'F': pic = pic.mul(255).byte() npimg = np.transpose(pic.cpu().numpy(), (1, 2, 0)) if not isinstance(npimg, np.ndarray): raise TypeError('Input pic must be a torch.Tensor or NumPy ndarray, ' + 'not {}'.format(type(npimg))) if npimg.shape[2] == 1: expected_mode = None npimg = npimg[:, :, 0] if npimg.dtype == np.uint8: expected_mode = 'L' elif npimg.dtype == np.int16: expected_mode = 'I;16' elif npimg.dtype == np.int32: expected_mode = 'I' elif npimg.dtype == np.float32: expected_mode = 'F' if mode is not None and mode != expected_mode: raise ValueError( "Incorrect mode ({}) supplied for input type {}. Should be {}" .format(mode, np.dtype, expected_mode)) mode = expected_mode elif npimg.shape[2] == 2: permitted_2_channel_modes = ['LA'] if mode is not None and mode not in permitted_2_channel_modes: raise ValueError("Only modes {} are supported for 2D inputs". format(permitted_2_channel_modes)) if mode is None and npimg.dtype == np.uint8: mode = 'LA' elif npimg.shape[2] == 4: permitted_4_channel_modes = ['RGBA', 'CMYK', 'RGBX'] if mode is not None and mode not in permitted_4_channel_modes: raise ValueError("Only modes {} are supported for 4D inputs". format(permitted_4_channel_modes)) if mode is None and npimg.dtype == np.uint8: mode = 'RGBA' else: permitted_3_channel_modes = ['RGB', 'YCbCr', 'HSV'] if mode is not None and mode not in permitted_3_channel_modes: raise ValueError("Only modes {} are supported for 3D inputs". format(permitted_3_channel_modes)) if mode is None and npimg.dtype == np.uint8: mode = 'RGB' if mode is None: raise TypeError('Input type {} is not supported'.format(npimg.dtype)) return Image.fromarray(npimg, mode=mode)
Convert a tensor or an ndarray to PIL Image. This function does not support torchscript. See :class:`~torchvision.transforms.ToPILImage` for more details. Args: pic (Tensor or numpy.ndarray): Image to be converted to PIL Image. mode (`PIL.Image mode`_): color space and pixel depth of input data (optional). .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes Returns: PIL Image: Image converted to PIL Image.
to_pil_image
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def normalize(tensor: Tensor, mean: List[float], std: List[float], inplace: bool=False) -> Tensor: """Normalize a float tensor image with mean and standard deviation. This transform does not support PIL Image. .. note:: This transform acts out of place by default, i.e., it does not mutates the input tensor. See :class:`~torchvision.transforms.Normalize` for more details. Args: tensor (Tensor): Float tensor image of size (C, H, W) or (B, C, H, W) to be normalized. mean (sequence): Sequence of means for each channel. std (sequence): Sequence of standard deviations for each channel. inplace(bool,optional): Bool to make this operation inplace. Returns: Tensor: Normalized Tensor image. """ if not isinstance(tensor, torch.Tensor): raise TypeError('Input tensor should be a torch tensor. Got {}.'. format(type(tensor))) if not tensor.is_floating_point(): raise TypeError('Input tensor should be a float tensor. Got {}.'. format(tensor.dtype)) if tensor.ndim < 3: raise ValueError( 'Expected tensor to be a tensor image of size (..., C, H, W). Got tensor.size() = ' '{}.'.format(tensor.size())) if not inplace: tensor = tensor.clone() dtype = tensor.dtype mean = torch.as_tensor(mean, dtype=dtype, device=tensor.device) std = torch.as_tensor(std, dtype=dtype, device=tensor.device) if (std == 0).any(): raise ValueError( 'std evaluated to zero after conversion to {}, leading to division by zero.'. format(dtype)) if mean.ndim == 1: mean = mean.view(-1, 1, 1) if std.ndim == 1: std = std.view(-1, 1, 1) tensor.sub_(mean).div_(std) return tensor
Normalize a float tensor image with mean and standard deviation. This transform does not support PIL Image. .. note:: This transform acts out of place by default, i.e., it does not mutates the input tensor. See :class:`~torchvision.transforms.Normalize` for more details. Args: tensor (Tensor): Float tensor image of size (C, H, W) or (B, C, H, W) to be normalized. mean (sequence): Sequence of means for each channel. std (sequence): Sequence of standard deviations for each channel. inplace(bool,optional): Bool to make this operation inplace. Returns: Tensor: Normalized Tensor image.
normalize
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def resize(img: Tensor, size: List[int], interpolation: InterpolationMode=InterpolationMode.BILINEAR, max_size: Optional[int]=None, antialias: Optional[bool]=None) -> Tensor: r"""Resize the input image to the given size. If the image is torch Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions .. warning:: The output image might be different depending on its type: when downsampling, the interpolation of PIL images and tensors is slightly different, because PIL applies antialiasing. This may lead to significant differences in the performance of a network. Therefore, it is preferable to train and serve a model with the same input types. See also below the ``antialias`` parameter, which can help making the output of PIL images and tensors closer. Args: img (PIL Image or Tensor): Image to be resized. size (sequence or int): Desired output size. If size is a sequence like (h, w), the output size will be matched to this. If size is an int, the smaller edge of the image will be matched to this number maintaining the aspect ratio. i.e, if height > width, then image will be rescaled to :math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)`. .. note:: In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``. interpolation (InterpolationMode): Desired interpolation enum defined by :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported. For backward compatibility integer values (e.g. ``PIL.Image.NEAREST``) are still acceptable. max_size (int, optional): The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater than ``max_size`` after being resized according to ``size``, then the image is resized again so that the longer edge is equal to ``max_size``. As a result, ``size`` might be overruled, i.e the smaller edge may be shorter than ``size``. This is only supported if ``size`` is an int (or a sequence of length 1 in torchscript mode). antialias (bool, optional): antialias flag. If ``img`` is PIL Image, the flag is ignored and anti-alias is always used. If ``img`` is Tensor, the flag is False by default and can be set to True for ``InterpolationMode.BILINEAR`` only mode. This can help making the output for PIL images and tensors closer. .. warning:: There is no autodiff support for ``antialias=True`` option with input ``img`` as Tensor. Returns: PIL Image or Tensor: Resized image. """ # Backward compatibility with integer value if isinstance(interpolation, int): warnings.warn( "Argument interpolation should be of type InterpolationMode instead of int. " "Please, use InterpolationMode enum.") interpolation = _interpolation_modes_from_int(interpolation) if not isinstance(interpolation, InterpolationMode): raise TypeError("Argument interpolation should be a InterpolationMode") if not isinstance(img, torch.Tensor): if antialias is not None and not antialias: warnings.warn( "Anti-alias option is always applied for PIL Image input. Argument antialias is ignored." ) pil_interpolation = pil_modes_mapping[interpolation] return F_pil.resize( img, size=size, interpolation=pil_interpolation, max_size=max_size) return F_t.resize( img, size=size, interpolation=interpolation.value, max_size=max_size, antialias=antialias)
Resize the input image to the given size. If the image is torch Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions .. warning:: The output image might be different depending on its type: when downsampling, the interpolation of PIL images and tensors is slightly different, because PIL applies antialiasing. This may lead to significant differences in the performance of a network. Therefore, it is preferable to train and serve a model with the same input types. See also below the ``antialias`` parameter, which can help making the output of PIL images and tensors closer. Args: img (PIL Image or Tensor): Image to be resized. size (sequence or int): Desired output size. If size is a sequence like (h, w), the output size will be matched to this. If size is an int, the smaller edge of the image will be matched to this number maintaining the aspect ratio. i.e, if height > width, then image will be rescaled to :math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)`. .. note:: In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``. interpolation (InterpolationMode): Desired interpolation enum defined by :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported. For backward compatibility integer values (e.g. ``PIL.Image.NEAREST``) are still acceptable. max_size (int, optional): The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater than ``max_size`` after being resized according to ``size``, then the image is resized again so that the longer edge is equal to ``max_size``. As a result, ``size`` might be overruled, i.e the smaller edge may be shorter than ``size``. This is only supported if ``size`` is an int (or a sequence of length 1 in torchscript mode). antialias (bool, optional): antialias flag. If ``img`` is PIL Image, the flag is ignored and anti-alias is always used. If ``img`` is Tensor, the flag is False by default and can be set to True for ``InterpolationMode.BILINEAR`` only mode. This can help making the output for PIL images and tensors closer. .. warning:: There is no autodiff support for ``antialias=True`` option with input ``img`` as Tensor. Returns: PIL Image or Tensor: Resized image.
resize
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def pad(img: Tensor, padding: List[int], fill: int=0, padding_mode: str="constant") -> Tensor: r"""Pad the given image on all sides with the given "pad" value. If the image is torch Tensor, it is expected to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric, at most 3 leading dimensions for mode edge, and an arbitrary number of leading dimensions for mode constant Args: img (PIL Image or Tensor): Image to be padded. padding (int or sequence): Padding on each border. If a single int is provided this is used to pad all borders. If sequence of length 2 is provided this is the padding on left/right and top/bottom respectively. If a sequence of length 4 is provided this is the padding for the left, top, right and bottom borders respectively. .. note:: In torchscript mode padding as single int is not supported, use a sequence of length 1: ``[padding, ]``. fill (number or str or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. This value is only used when the padding_mode is constant. Only number is supported for torch Tensor. Only int or str or tuple value is supported for PIL Image. padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant. - constant: pads with a constant value, this value is specified with fill - edge: pads with the last value at the edge of the image. If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2 - reflect: pads with reflection of image without repeating the last value on the edge. For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode will result in [3, 2, 1, 2, 3, 4, 3, 2] - symmetric: pads with reflection of image repeating the last value on the edge. For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode will result in [2, 1, 1, 2, 3, 4, 4, 3] Returns: PIL Image or Tensor: Padded image. """ if not isinstance(img, torch.Tensor): return F_pil.pad(img, padding=padding, fill=fill, padding_mode=padding_mode) return F_t.pad(img, padding=padding, fill=fill, padding_mode=padding_mode)
Pad the given image on all sides with the given "pad" value. If the image is torch Tensor, it is expected to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric, at most 3 leading dimensions for mode edge, and an arbitrary number of leading dimensions for mode constant Args: img (PIL Image or Tensor): Image to be padded. padding (int or sequence): Padding on each border. If a single int is provided this is used to pad all borders. If sequence of length 2 is provided this is the padding on left/right and top/bottom respectively. If a sequence of length 4 is provided this is the padding for the left, top, right and bottom borders respectively. .. note:: In torchscript mode padding as single int is not supported, use a sequence of length 1: ``[padding, ]``. fill (number or str or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. This value is only used when the padding_mode is constant. Only number is supported for torch Tensor. Only int or str or tuple value is supported for PIL Image. padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant. - constant: pads with a constant value, this value is specified with fill - edge: pads with the last value at the edge of the image. If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2 - reflect: pads with reflection of image without repeating the last value on the edge. For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode will result in [3, 2, 1, 2, 3, 4, 3, 2] - symmetric: pads with reflection of image repeating the last value on the edge. For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode will result in [2, 1, 1, 2, 3, 4, 4, 3] Returns: PIL Image or Tensor: Padded image.
pad
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor: """Crop the given image at specified location and output size. If the image is torch 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, torch.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 torch Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. If image size is smaller than output size along any edge, image is padded with 0 and then cropped. Args: img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image. top (int): Vertical component of the top left corner of the crop box. left (int): Horizontal component of the top left corner of the crop box. height (int): Height of the crop box. width (int): Width of the crop box. Returns: PIL Image or Tensor: Cropped image.
crop
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/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 torch 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 torch Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions. If image size is smaller than output size along any edge, image is padded with 0 and then center cropped. Args: img (PIL Image or Tensor): Image to be cropped. output_size (sequence or int): (height, width) of the crop box. If int or sequence with single int, it is used for both directions. Returns: PIL Image or Tensor: Cropped image.
center_crop
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/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 torch Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions Notably used in :class:`~torchvision.transforms.RandomResizedCrop`. 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:`torchvision.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 torch Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions Notably used in :class:`~torchvision.transforms.RandomResizedCrop`. 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:`torchvision.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/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def hflip(img: Tensor) -> Tensor: """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, torch.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/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def _get_perspective_coeffs(startpoints: List[List[int]], endpoints: List[List[int]]) -> List[float]: """Helper function to get the coefficients (a, b, c, d, e, f, g, h) for the perspective transforms. In Perspective Transform each pixel (x, y) in the original image gets transformed as, (x, y) -> ( (ax + by + c) / (gx + hy + 1), (dx + ey + f) / (gx + hy + 1) ) Args: startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners ``[top-left, top-right, bottom-right, bottom-left]`` of the original image. endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image. Returns: octuple (a, b, c, d, e, f, g, h) for transforming each pixel. """ a_matrix = torch.zeros(2 * len(startpoints), 8, dtype=torch.float) for i, (p1, p2) in enumerate(zip(endpoints, startpoints)): a_matrix[2 * i, :] = torch.tensor( [p1[0], p1[1], 1, 0, 0, 0, -p2[0] * p1[0], -p2[0] * p1[1]]) a_matrix[2 * i + 1, :] = torch.tensor( [0, 0, 0, p1[0], p1[1], 1, -p2[1] * p1[0], -p2[1] * p1[1]]) b_matrix = torch.tensor(startpoints, dtype=torch.float).view(8) res = torch.linalg.lstsq(a_matrix, b_matrix, driver='gels').solution output: List[float] = res.tolist() return output
Helper function to get the coefficients (a, b, c, d, e, f, g, h) for the perspective transforms. In Perspective Transform each pixel (x, y) in the original image gets transformed as, (x, y) -> ( (ax + by + c) / (gx + hy + 1), (dx + ey + f) / (gx + hy + 1) ) Args: startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners ``[top-left, top-right, bottom-right, bottom-left]`` of the original image. endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image. Returns: octuple (a, b, c, d, e, f, g, h) for transforming each pixel.
_get_perspective_coeffs
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def perspective(img: Tensor, startpoints: List[List[int]], endpoints: List[List[int]], interpolation: InterpolationMode=InterpolationMode.BILINEAR, fill: Optional[List[float]]=None) -> Tensor: """Perform perspective transform of the given image. If the image is torch 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 transformed. startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners ``[top-left, top-right, bottom-right, bottom-left]`` of the original image. endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image. interpolation (InterpolationMode): Desired interpolation enum defined by :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. For backward compatibility integer values (e.g. ``PIL.Image.NEAREST``) are still acceptable. fill (sequence or number, optional): Pixel fill value for the area outside the transformed image. If given a number, the value is used for all bands respectively. .. note:: In torchscript mode single int/float value is not supported, please use a sequence of length 1: ``[value, ]``. Returns: PIL Image or Tensor: transformed Image. """ coeffs = _get_perspective_coeffs(startpoints, endpoints) # Backward compatibility with integer value if isinstance(interpolation, int): warnings.warn( "Argument interpolation should be of type InterpolationMode instead of int. " "Please, use InterpolationMode enum.") interpolation = _interpolation_modes_from_int(interpolation) if not isinstance(interpolation, InterpolationMode): raise TypeError("Argument interpolation should be a InterpolationMode") if not isinstance(img, torch.Tensor): pil_interpolation = pil_modes_mapping[interpolation] return F_pil.perspective( img, coeffs, interpolation=pil_interpolation, fill=fill) return F_t.perspective( img, coeffs, interpolation=interpolation.value, fill=fill)
Perform perspective transform of the given image. If the image is torch 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 transformed. startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners ``[top-left, top-right, bottom-right, bottom-left]`` of the original image. endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image. interpolation (InterpolationMode): Desired interpolation enum defined by :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. For backward compatibility integer values (e.g. ``PIL.Image.NEAREST``) are still acceptable. fill (sequence or number, optional): Pixel fill value for the area outside the transformed image. If given a number, the value is used for all bands respectively. .. note:: In torchscript mode single int/float value is not supported, please use a sequence of length 1: ``[value, ]``. Returns: PIL Image or Tensor: transformed Image.
perspective
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def vflip(img: Tensor) -> Tensor: """Vertically 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: Vertically flipped image. """ if not isinstance(img, torch.Tensor): return F_pil.vflip(img) return F_t.vflip(img)
Vertically 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: Vertically flipped image.
vflip
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def five_crop( img: Tensor, size: List[int]) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]: """Crop the given image into four corners and the central crop. If the image is torch Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions .. Note:: This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your ``Dataset`` returns. Args: img (PIL Image or Tensor): Image to be cropped. size (sequence or int): Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). Returns: tuple: tuple (tl, tr, bl, br, center) Corresponding top left, top right, bottom left, bottom right and center crop. """ if isinstance(size, numbers.Number): size = (int(size), int(size)) elif isinstance(size, (tuple, list)) and len(size) == 1: size = (size[0], size[0]) if len(size) != 2: raise ValueError("Please provide only two dimensions (h, w) for size.") image_width, image_height = _get_image_size(img) crop_height, crop_width = size if crop_width > image_width or crop_height > image_height: msg = "Requested crop size {} is bigger than input size {}" raise ValueError(msg.format(size, (image_height, image_width))) tl = crop(img, 0, 0, crop_height, crop_width) tr = crop(img, 0, image_width - crop_width, crop_height, crop_width) bl = crop(img, image_height - crop_height, 0, crop_height, crop_width) br = crop(img, image_height - crop_height, image_width - crop_width, crop_height, crop_width) center = center_crop(img, [crop_height, crop_width]) return tl, tr, bl, br, center
Crop the given image into four corners and the central crop. If the image is torch Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions .. Note:: This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your ``Dataset`` returns. Args: img (PIL Image or Tensor): Image to be cropped. size (sequence or int): Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). Returns: tuple: tuple (tl, tr, bl, br, center) Corresponding top left, top right, bottom left, bottom right and center crop.
five_crop
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def ten_crop(img: Tensor, size: List[int], vertical_flip: bool=False) -> List[Tensor]: """Generate ten cropped images from the given image. Crop the given image into four corners and the central crop plus the flipped version of these (horizontal flipping is used by default). If the image is torch Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions .. Note:: This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your ``Dataset`` returns. Args: img (PIL Image or Tensor): Image to be cropped. size (sequence or int): Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). vertical_flip (bool): Use vertical flipping instead of horizontal Returns: tuple: tuple (tl, tr, bl, br, center, tl_flip, tr_flip, bl_flip, br_flip, center_flip) Corresponding top left, top right, bottom left, bottom right and center crop and same for the flipped image. """ if isinstance(size, numbers.Number): size = (int(size), int(size)) elif isinstance(size, (tuple, list)) and len(size) == 1: size = (size[0], size[0]) if len(size) != 2: raise ValueError("Please provide only two dimensions (h, w) for size.") first_five = five_crop(img, size) if vertical_flip: img = vflip(img) else: img = hflip(img) second_five = five_crop(img, size) return first_five + second_five
Generate ten cropped images from the given image. Crop the given image into four corners and the central crop plus the flipped version of these (horizontal flipping is used by default). If the image is torch Tensor, it is expected to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions .. Note:: This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your ``Dataset`` returns. Args: img (PIL Image or Tensor): Image to be cropped. size (sequence or int): Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]). vertical_flip (bool): Use vertical flipping instead of horizontal Returns: tuple: tuple (tl, tr, bl, br, center, tl_flip, tr_flip, bl_flip, br_flip, center_flip) Corresponding top left, top right, bottom left, bottom right and center crop and same for the flipped image.
ten_crop
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def adjust_brightness(img: Tensor, brightness_factor: float) -> Tensor: """Adjust brightness of an image. Args: img (PIL Image or Tensor): Image to be adjusted. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, where ... means it can have an arbitrary number of leading dimensions. brightness_factor (float): How much to adjust the brightness. Can be any non negative number. 0 gives a black image, 1 gives the original image while 2 increases the brightness by a factor of 2. Returns: PIL Image or Tensor: Brightness adjusted image. """ if not isinstance(img, torch.Tensor): return F_pil.adjust_brightness(img, brightness_factor) return F_t.adjust_brightness(img, brightness_factor)
Adjust brightness of an image. Args: img (PIL Image or Tensor): Image to be adjusted. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, where ... means it can have an arbitrary number of leading dimensions. brightness_factor (float): How much to adjust the brightness. Can be any non negative number. 0 gives a black image, 1 gives the original image while 2 increases the brightness by a factor of 2. Returns: PIL Image or Tensor: Brightness adjusted image.
adjust_brightness
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def adjust_contrast(img: Tensor, contrast_factor: float) -> Tensor: """Adjust contrast of an image. Args: img (PIL Image or Tensor): Image to be adjusted. If img is torch Tensor, it is expected to be in [..., 3, H, W] format, where ... means it can have an arbitrary number of leading dimensions. contrast_factor (float): How much to adjust the contrast. Can be any non negative number. 0 gives a solid gray image, 1 gives the original image while 2 increases the contrast by a factor of 2. Returns: PIL Image or Tensor: Contrast adjusted image. """ if not isinstance(img, torch.Tensor): return F_pil.adjust_contrast(img, contrast_factor) return F_t.adjust_contrast(img, contrast_factor)
Adjust contrast of an image. Args: img (PIL Image or Tensor): Image to be adjusted. If img is torch Tensor, it is expected to be in [..., 3, H, W] format, where ... means it can have an arbitrary number of leading dimensions. contrast_factor (float): How much to adjust the contrast. Can be any non negative number. 0 gives a solid gray image, 1 gives the original image while 2 increases the contrast by a factor of 2. Returns: PIL Image or Tensor: Contrast adjusted image.
adjust_contrast
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def adjust_saturation(img: Tensor, saturation_factor: float) -> Tensor: """Adjust color saturation of an image. Args: img (PIL Image or Tensor): Image to be adjusted. If img is torch Tensor, it is expected to be in [..., 3, H, W] format, where ... means it can have an arbitrary number of leading dimensions. saturation_factor (float): How much to adjust the saturation. 0 will give a black and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2. Returns: PIL Image or Tensor: Saturation adjusted image. """ if not isinstance(img, torch.Tensor): return F_pil.adjust_saturation(img, saturation_factor) return F_t.adjust_saturation(img, saturation_factor)
Adjust color saturation of an image. Args: img (PIL Image or Tensor): Image to be adjusted. If img is torch Tensor, it is expected to be in [..., 3, H, W] format, where ... means it can have an arbitrary number of leading dimensions. saturation_factor (float): How much to adjust the saturation. 0 will give a black and white image, 1 will give the original image while 2 will enhance the saturation by a factor of 2. Returns: PIL Image or Tensor: Saturation adjusted image.
adjust_saturation
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def adjust_hue(img: Tensor, hue_factor: float) -> Tensor: """Adjust hue of an image. The image hue is adjusted by converting the image to HSV and cyclically shifting the intensities in the hue channel (H). The image is then converted back to original image mode. `hue_factor` is the amount of shift in H channel and must be in the interval `[-0.5, 0.5]`. See `Hue`_ for more details. .. _Hue: https://en.wikipedia.org/wiki/Hue Args: img (PIL Image or Tensor): Image to be adjusted. If img is torch Tensor, it is expected to be in [..., 3, H, W] format, where ... means it can have an arbitrary number of leading dimensions. If img is PIL Image mode "1", "L", "I", "F" and modes with transparency (alpha channel) are not supported. hue_factor (float): How much to shift the hue channel. Should be in [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in HSV space in positive and negative direction respectively. 0 means no shift. Therefore, both -0.5 and 0.5 will give an image with complementary colors while 0 gives the original image. Returns: PIL Image or Tensor: Hue adjusted image. """ if not isinstance(img, torch.Tensor): return F_pil.adjust_hue(img, hue_factor) return F_t.adjust_hue(img, hue_factor)
Adjust hue of an image. The image hue is adjusted by converting the image to HSV and cyclically shifting the intensities in the hue channel (H). The image is then converted back to original image mode. `hue_factor` is the amount of shift in H channel and must be in the interval `[-0.5, 0.5]`. See `Hue`_ for more details. .. _Hue: https://en.wikipedia.org/wiki/Hue Args: img (PIL Image or Tensor): Image to be adjusted. If img is torch Tensor, it is expected to be in [..., 3, H, W] format, where ... means it can have an arbitrary number of leading dimensions. If img is PIL Image mode "1", "L", "I", "F" and modes with transparency (alpha channel) are not supported. hue_factor (float): How much to shift the hue channel. Should be in [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in HSV space in positive and negative direction respectively. 0 means no shift. Therefore, both -0.5 and 0.5 will give an image with complementary colors while 0 gives the original image. Returns: PIL Image or Tensor: Hue adjusted image.
adjust_hue
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def adjust_gamma(img: Tensor, gamma: float, gain: float=1) -> Tensor: r"""Perform gamma correction on an image. Also known as Power Law Transform. Intensities in RGB mode are adjusted based on the following equation: .. math:: I_{\text{out}} = 255 \times \text{gain} \times \left(\frac{I_{\text{in}}}{255}\right)^{\gamma} See `Gamma Correction`_ for more details. .. _Gamma Correction: https://en.wikipedia.org/wiki/Gamma_correction Args: img (PIL Image or Tensor): PIL Image to be adjusted. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, where ... means it can have an arbitrary number of leading dimensions. If img is PIL Image, modes with transparency (alpha channel) are not supported. gamma (float): Non negative real number, same as :math:`\gamma` in the equation. gamma larger than 1 make the shadows darker, while gamma smaller than 1 make dark regions lighter. gain (float): The constant multiplier. Returns: PIL Image or Tensor: Gamma correction adjusted image. """ if not isinstance(img, torch.Tensor): return F_pil.adjust_gamma(img, gamma, gain) return F_t.adjust_gamma(img, gamma, gain)
Perform gamma correction on an image. Also known as Power Law Transform. Intensities in RGB mode are adjusted based on the following equation: .. math:: I_{\text{out}} = 255 \times \text{gain} \times \left(\frac{I_{\text{in}}}{255}\right)^{\gamma} See `Gamma Correction`_ for more details. .. _Gamma Correction: https://en.wikipedia.org/wiki/Gamma_correction Args: img (PIL Image or Tensor): PIL Image to be adjusted. If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format, where ... means it can have an arbitrary number of leading dimensions. If img is PIL Image, modes with transparency (alpha channel) are not supported. gamma (float): Non negative real number, same as :math:`\gamma` in the equation. gamma larger than 1 make the shadows darker, while gamma smaller than 1 make dark regions lighter. gain (float): The constant multiplier. Returns: PIL Image or Tensor: Gamma correction adjusted image.
adjust_gamma
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def affine(img: Tensor, angle: float, translate: List[int], scale: float, shear: List[float], interpolation: InterpolationMode=InterpolationMode.NEAREST, fill: Optional[List[float]]=None, resample: Optional[int]=None, fillcolor: Optional[List[float]]=None) -> Tensor: """Apply affine transformation on the image keeping image center invariant. If the image is torch 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 transform. angle (number): rotation angle in degrees between -180 and 180, clockwise direction. translate (sequence of integers): horizontal and vertical translations (post-rotation translation) scale (float): overall scale shear (float or sequence): shear angle value in degrees between -180 to 180, clockwise direction. If a sequence is specified, the first value corresponds to a shear parallel to the x axis, while the second value corresponds to a shear parallel to the y axis. interpolation (InterpolationMode): Desired interpolation enum defined by :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. For backward compatibility integer values (e.g. ``PIL.Image.NEAREST``) are still acceptable. fill (sequence or number, optional): Pixel fill value for the area outside the transformed image. If given a number, the value is used for all bands respectively. .. note:: In torchscript mode single int/float value is not supported, please use a sequence of length 1: ``[value, ]``. fillcolor (sequence, int, float): deprecated argument and will be removed since v0.10.0. Please use the ``fill`` parameter instead. resample (int, optional): deprecated argument and will be removed since v0.10.0. Please use the ``interpolation`` parameter instead. Returns: PIL Image or Tensor: Transformed image. """ if resample is not None: warnings.warn( "Argument resample is deprecated and will be removed since v0.10.0. Please, use interpolation instead" ) interpolation = _interpolation_modes_from_int(resample) # Backward compatibility with integer value if isinstance(interpolation, int): warnings.warn( "Argument interpolation should be of type InterpolationMode instead of int. " "Please, use InterpolationMode enum.") interpolation = _interpolation_modes_from_int(interpolation) if fillcolor is not None: warnings.warn( "Argument fillcolor is deprecated and will be removed since v0.10.0. Please, use fill instead" ) fill = fillcolor if not isinstance(angle, (int, float)): raise TypeError("Argument angle should be int or float") if not isinstance(translate, (list, tuple)): raise TypeError("Argument translate should be a sequence") if len(translate) != 2: raise ValueError("Argument translate should be a sequence of length 2") if scale <= 0.0: raise ValueError("Argument scale should be positive") if not isinstance(shear, (numbers.Number, (list, tuple))): raise TypeError( "Shear should be either a single value or a sequence of two values") if not isinstance(interpolation, InterpolationMode): raise TypeError("Argument interpolation should be a InterpolationMode") if isinstance(angle, int): angle = float(angle) if isinstance(translate, tuple): translate = list(translate) if isinstance(shear, numbers.Number): shear = [shear, 0.0] if isinstance(shear, tuple): shear = list(shear) if len(shear) == 1: shear = [shear[0], shear[0]] if len(shear) != 2: raise ValueError( "Shear should be a sequence containing two values. Got {}".format( shear)) img_size = _get_image_size(img) if not isinstance(img, torch.Tensor): # center = (img_size[0] * 0.5 + 0.5, img_size[1] * 0.5 + 0.5) # it is visually better to estimate the center without 0.5 offset # otherwise image rotated by 90 degrees is shifted vs output image of torch.rot90 or F_t.affine center = [img_size[0] * 0.5, img_size[1] * 0.5] matrix = _get_inverse_affine_matrix(center, angle, translate, scale, shear) pil_interpolation = pil_modes_mapping[interpolation] return F_pil.affine( img, matrix=matrix, interpolation=pil_interpolation, fill=fill) translate_f = [1.0 * t for t in translate] matrix = _get_inverse_affine_matrix([0.0, 0.0], angle, translate_f, scale, shear) return F_t.affine( img, matrix=matrix, interpolation=interpolation.value, fill=fill)
Apply affine transformation on the image keeping image center invariant. If the image is torch 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 transform. angle (number): rotation angle in degrees between -180 and 180, clockwise direction. translate (sequence of integers): horizontal and vertical translations (post-rotation translation) scale (float): overall scale shear (float or sequence): shear angle value in degrees between -180 to 180, clockwise direction. If a sequence is specified, the first value corresponds to a shear parallel to the x axis, while the second value corresponds to a shear parallel to the y axis. interpolation (InterpolationMode): Desired interpolation enum defined by :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. For backward compatibility integer values (e.g. ``PIL.Image.NEAREST``) are still acceptable. fill (sequence or number, optional): Pixel fill value for the area outside the transformed image. If given a number, the value is used for all bands respectively. .. note:: In torchscript mode single int/float value is not supported, please use a sequence of length 1: ``[value, ]``. fillcolor (sequence, int, float): deprecated argument and will be removed since v0.10.0. Please use the ``fill`` parameter instead. resample (int, optional): deprecated argument and will be removed since v0.10.0. Please use the ``interpolation`` parameter instead. Returns: PIL Image or Tensor: Transformed image.
affine
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def to_grayscale(img, num_output_channels=1): """Convert PIL image of any mode (RGB, HSV, LAB, etc) to grayscale version of image. This transform does not support torch Tensor. Args: img (PIL Image): PIL Image to be converted to grayscale. num_output_channels (int): number of channels of the output image. Value can be 1 or 3. Default is 1. Returns: PIL Image: Grayscale version of the image. - if num_output_channels = 1 : returned image is single channel - if num_output_channels = 3 : returned image is 3 channel with r = g = b """ if isinstance(img, Image.Image): return F_pil.to_grayscale(img, num_output_channels) raise TypeError("Input should be PIL Image")
Convert PIL image of any mode (RGB, HSV, LAB, etc) to grayscale version of image. This transform does not support torch Tensor. Args: img (PIL Image): PIL Image to be converted to grayscale. num_output_channels (int): number of channels of the output image. Value can be 1 or 3. Default is 1. Returns: PIL Image: Grayscale version of the image. - if num_output_channels = 1 : returned image is single channel - if num_output_channels = 3 : returned image is 3 channel with r = g = b
to_grayscale
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def rgb_to_grayscale(img: Tensor, num_output_channels: int=1) -> Tensor: """Convert RGB image to grayscale version of image. If the image is torch Tensor, it is expected to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions Note: Please, note that this method supports only RGB images as input. For inputs in other color spaces, please, consider using meth:`~torchvision.transforms.functional.to_grayscale` with PIL Image. Args: img (PIL Image or Tensor): RGB Image to be converted to grayscale. num_output_channels (int): number of channels of the output image. Value can be 1 or 3. Default, 1. Returns: PIL Image or Tensor: Grayscale version of the image. - if num_output_channels = 1 : returned image is single channel - if num_output_channels = 3 : returned image is 3 channel with r = g = b """ if not isinstance(img, torch.Tensor): return F_pil.to_grayscale(img, num_output_channels) return F_t.rgb_to_grayscale(img, num_output_channels)
Convert RGB image to grayscale version of image. If the image is torch Tensor, it is expected to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions Note: Please, note that this method supports only RGB images as input. For inputs in other color spaces, please, consider using meth:`~torchvision.transforms.functional.to_grayscale` with PIL Image. Args: img (PIL Image or Tensor): RGB Image to be converted to grayscale. num_output_channels (int): number of channels of the output image. Value can be 1 or 3. Default, 1. Returns: PIL Image or Tensor: Grayscale version of the image. - if num_output_channels = 1 : returned image is single channel - if num_output_channels = 3 : returned image is 3 channel with r = g = b
rgb_to_grayscale
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def erase(img: Tensor, i: int, j: int, h: int, w: int, v: Tensor, inplace: bool=False) -> Tensor: """ Erase the input Tensor Image with given value. This transform does not support PIL Image. Args: img (Tensor Image): Tensor image of size (C, H, W) to be erased i (int): i in (i,j) i.e coordinates of the upper left corner. j (int): j in (i,j) i.e coordinates of the upper left corner. h (int): Height of the erased region. w (int): Width of the erased region. v: Erasing value. inplace(bool, optional): For in-place operations. By default is set False. Returns: Tensor Image: Erased image. """ if not isinstance(img, torch.Tensor): raise TypeError('img should be Tensor Image. Got {}'.format(type(img))) if not inplace: img = img.clone() img[..., i:i + h, j:j + w] = v return img
Erase the input Tensor Image with given value. This transform does not support PIL Image. Args: img (Tensor Image): Tensor image of size (C, H, W) to be erased i (int): i in (i,j) i.e coordinates of the upper left corner. j (int): j in (i,j) i.e coordinates of the upper left corner. h (int): Height of the erased region. w (int): Width of the erased region. v: Erasing value. inplace(bool, optional): For in-place operations. By default is set False. Returns: Tensor Image: Erased image.
erase
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0
def gaussian_blur(img: Tensor, kernel_size: List[int], sigma: Optional[List[float]]=None) -> Tensor: """Performs Gaussian blurring on the image by given kernel. If the image is torch 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 blurred kernel_size (sequence of ints or int): Gaussian kernel size. Can be a sequence of integers like ``(kx, ky)`` or a single integer for square kernels. .. note:: In torchscript mode kernel_size as single int is not supported, use a sequence of length 1: ``[ksize, ]``. sigma (sequence of floats or float, optional): Gaussian kernel standard deviation. Can be a sequence of floats like ``(sigma_x, sigma_y)`` or a single float to define the same sigma in both X/Y directions. If None, then it is computed using ``kernel_size`` as ``sigma = 0.3 * ((kernel_size - 1) * 0.5 - 1) + 0.8``. Default, None. .. note:: In torchscript mode sigma as single float is not supported, use a sequence of length 1: ``[sigma, ]``. Returns: PIL Image or Tensor: Gaussian Blurred version of the image. """ if not isinstance(kernel_size, (int, list, tuple)): raise TypeError( 'kernel_size should be int or a sequence of integers. Got {}'. format(type(kernel_size))) if isinstance(kernel_size, int): kernel_size = [kernel_size, kernel_size] if len(kernel_size) != 2: raise ValueError( 'If kernel_size is a sequence its length should be 2. Got {}'. format(len(kernel_size))) for ksize in kernel_size: if ksize % 2 == 0 or ksize < 0: raise ValueError( 'kernel_size should have odd and positive integers. Got {}'. format(kernel_size)) if sigma is None: sigma = [ksize * 0.15 + 0.35 for ksize in kernel_size] if sigma is not None and not isinstance(sigma, (int, float, list, tuple)): raise TypeError( 'sigma should be either float or sequence of floats. Got {}'. format(type(sigma))) if isinstance(sigma, (int, float)): sigma = [float(sigma), float(sigma)] if isinstance(sigma, (list, tuple)) and len(sigma) == 1: sigma = [sigma[0], sigma[0]] if len(sigma) != 2: raise ValueError( 'If sigma is a sequence, its length should be 2. Got {}'.format( len(sigma))) for s in sigma: if s <= 0.: raise ValueError( 'sigma should have positive values. Got {}'.format(sigma)) t_img = img if not isinstance(img, torch.Tensor): if not F_pil._is_pil_image(img): raise TypeError('img should be PIL Image or Tensor. Got {}'.format( type(img))) t_img = to_tensor(img) output = F_t.gaussian_blur(t_img, kernel_size, sigma) if not isinstance(img, torch.Tensor): output = to_pil_image(output) return output
Performs Gaussian blurring on the image by given kernel. If the image is torch 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 blurred kernel_size (sequence of ints or int): Gaussian kernel size. Can be a sequence of integers like ``(kx, ky)`` or a single integer for square kernels. .. note:: In torchscript mode kernel_size as single int is not supported, use a sequence of length 1: ``[ksize, ]``. sigma (sequence of floats or float, optional): Gaussian kernel standard deviation. Can be a sequence of floats like ``(sigma_x, sigma_y)`` or a single float to define the same sigma in both X/Y directions. If None, then it is computed using ``kernel_size`` as ``sigma = 0.3 * ((kernel_size - 1) * 0.5 - 1) + 0.8``. Default, None. .. note:: In torchscript mode sigma as single float is not supported, use a sequence of length 1: ``[sigma, ]``. Returns: PIL Image or Tensor: Gaussian Blurred version of the image.
gaussian_blur
python
PaddlePaddle/models
tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
https://github.com/PaddlePaddle/models/blob/master/tutorials/mobilenetv3_prod/Step1-5/mobilenetv3_ref/torchvision/transforms/functional.py
Apache-2.0