Spaces:
Sleeping
Sleeping
File size: 12,682 Bytes
9bf4bd7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
# Copyright (c) OpenMMLab. All rights reserved.
import warnings
from typing import Any, Dict, List, Optional, Tuple, Union
import imgaug
import imgaug.augmenters as iaa
import numpy as np
import torchvision.transforms as torchvision_transforms
from mmcv.transforms import Compose
from mmcv.transforms.base import BaseTransform
from PIL import Image
from mmocr.registry import TRANSFORMS
from mmocr.utils import poly2bbox
@TRANSFORMS.register_module()
class ImgAugWrapper(BaseTransform):
"""A wrapper around imgaug https://github.com/aleju/imgaug.
Find available augmenters at
https://imgaug.readthedocs.io/en/latest/source/overview_of_augmenters.html.
Required Keys:
- img
- gt_polygons (optional for text recognition)
- gt_bboxes (optional for text recognition)
- gt_bboxes_labels (optional for text recognition)
- gt_ignored (optional for text recognition)
- gt_texts (optional)
Modified Keys:
- img
- gt_polygons (optional for text recognition)
- gt_bboxes (optional for text recognition)
- gt_bboxes_labels (optional for text recognition)
- gt_ignored (optional for text recognition)
- img_shape (optional)
- gt_texts (optional)
Args:
args (list[list or dict]], optional): The argumentation list. For
details, please refer to imgaug document. Take
args=[['Fliplr', 0.5], dict(cls='Affine', rotate=[-10, 10]),
['Resize', [0.5, 3.0]]] as an example. The args horizontally flip
images with probability 0.5, followed by random rotation with
angles in range [-10, 10], and resize with an independent scale in
range [0.5, 3.0] for each side of images. Defaults to None.
fix_poly_trans (dict): The transform configuration to fix invalid
polygons. Set it to None if no fixing is needed.
Defaults to dict(type='FixInvalidPolygon').
"""
def __init__(
self,
args: Optional[List[Union[List, Dict]]] = None,
fix_poly_trans: Optional[dict] = dict(type='FixInvalidPolygon')
) -> None:
assert args is None or isinstance(args, list) and len(args) > 0
if args is not None:
for arg in args:
assert isinstance(arg, (list, dict)), \
'args should be a list of list or dict'
self.args = args
self.augmenter = self._build_augmentation(args)
self.fix_poly_trans = fix_poly_trans
if fix_poly_trans is not None:
self.fix = TRANSFORMS.build(fix_poly_trans)
def transform(self, results: Dict) -> Dict:
"""Transform the image and annotation data.
Args:
results (dict): Result dict containing the data to transform.
Returns:
dict: The transformed data.
"""
# img is bgr
image = results['img']
aug = None
ori_shape = image.shape
if self.augmenter:
aug = self.augmenter.to_deterministic()
if not self._augment_annotations(aug, ori_shape, results):
return None
results['img'] = aug.augment_image(image)
results['img_shape'] = (results['img'].shape[0],
results['img'].shape[1])
if getattr(self, 'fix', None) is not None:
results = self.fix(results)
return results
def _augment_annotations(self, aug: imgaug.augmenters.meta.Augmenter,
ori_shape: Tuple[int,
int], results: Dict) -> Dict:
"""Augment annotations following the pre-defined augmentation sequence.
Args:
aug (imgaug.augmenters.meta.Augmenter): The imgaug augmenter.
ori_shape (tuple[int, int]): The ori_shape of the original image.
results (dict): Result dict containing annotations to transform.
Returns:
bool: Whether the transformation has been successfully applied. If
the transform results in empty polygon/bbox annotations, return
False.
"""
# Assume co-existence of `gt_polygons`, `gt_bboxes` and `gt_ignored`
# for text detection
if 'gt_polygons' in results:
# augment polygons
transformed_polygons, removed_poly_inds = self._augment_polygons(
aug, ori_shape, results['gt_polygons'])
if len(transformed_polygons) == 0:
return False
results['gt_polygons'] = transformed_polygons
# remove instances that are no longer inside the augmented image
results['gt_bboxes_labels'] = np.delete(
results['gt_bboxes_labels'], removed_poly_inds, axis=0)
results['gt_ignored'] = np.delete(
results['gt_ignored'], removed_poly_inds, axis=0)
# TODO: deal with gt_texts corresponding to clipped polygons
if 'gt_texts' in results:
results['gt_texts'] = [
text for i, text in enumerate(results['gt_texts'])
if i not in removed_poly_inds
]
# Generate new bboxes
bboxes = [poly2bbox(poly) for poly in transformed_polygons]
results['gt_bboxes'] = np.zeros((0, 4), dtype=np.float32)
if len(bboxes) > 0:
results['gt_bboxes'] = np.stack(bboxes)
return True
def _augment_polygons(self, aug: imgaug.augmenters.meta.Augmenter,
ori_shape: Tuple[int, int], polys: List[np.ndarray]
) -> Tuple[List[np.ndarray], List[int]]:
"""Augment polygons.
Args:
aug (imgaug.augmenters.meta.Augmenter): The imgaug augmenter.
ori_shape (tuple[int, int]): The shape of the original image.
polys (list[np.ndarray]): The polygons to be augmented.
Returns:
tuple(list[np.ndarray], list[int]): The augmented polygons, and the
indices of polygons removed as they are out of the augmented image.
"""
imgaug_polys = []
for poly in polys:
poly = poly.reshape(-1, 2)
imgaug_polys.append(imgaug.Polygon(poly))
imgaug_polys = aug.augment_polygons(
[imgaug.PolygonsOnImage(imgaug_polys, shape=ori_shape)])[0]
new_polys = []
removed_poly_inds = []
for i, poly in enumerate(imgaug_polys.polygons):
# Sometimes imgaug may produce some invalid polygons with no points
if not poly.is_valid or poly.is_out_of_image(imgaug_polys.shape):
removed_poly_inds.append(i)
continue
new_poly = []
try:
poly = poly.clip_out_of_image(imgaug_polys.shape)[0]
except Exception as e:
warnings.warn(f'Failed to clip polygon out of image: {e}')
for point in poly:
new_poly.append(np.array(point, dtype=np.float32))
new_poly = np.array(new_poly, dtype=np.float32).flatten()
# Under some conditions, imgaug can generate "polygon" with only
# two points, which is not a valid polygon.
if len(new_poly) <= 4:
removed_poly_inds.append(i)
continue
new_polys.append(new_poly)
return new_polys, removed_poly_inds
def _build_augmentation(self, args, root=True):
"""Build ImgAugWrapper augmentations.
Args:
args (dict): Arguments to be passed to imgaug.
root (bool): Whether it's building the root augmenter.
Returns:
imgaug.augmenters.meta.Augmenter: The built augmenter.
"""
if args is None:
return None
if isinstance(args, (int, float, str)):
return args
if isinstance(args, list):
if root:
sequence = [
self._build_augmentation(value, root=False)
for value in args
]
return iaa.Sequential(sequence)
arg_list = [self._to_tuple_if_list(a) for a in args[1:]]
return getattr(iaa, args[0])(*arg_list)
if isinstance(args, dict):
if 'cls' in args:
cls = getattr(iaa, args['cls'])
return cls(
**{
k: self._to_tuple_if_list(v)
for k, v in args.items() if not k == 'cls'
})
else:
return {
key: self._build_augmentation(value, root=False)
for key, value in args.items()
}
raise RuntimeError('unknown augmenter arg: ' + str(args))
def _to_tuple_if_list(self, obj: Any) -> Any:
"""Convert an object into a tuple if it is a list."""
if isinstance(obj, list):
return tuple(obj)
return obj
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(args = {self.args}, '
repr_str += f'fix_poly_trans = {self.fix_poly_trans})'
return repr_str
@TRANSFORMS.register_module()
class TorchVisionWrapper(BaseTransform):
"""A wrapper around torchvision transforms. It applies specific transform
to ``img`` and updates ``height`` and ``width`` accordingly.
Required Keys:
- img (ndarray): The input image.
Modified Keys:
- img (ndarray): The modified image.
- img_shape (tuple(int, int)): The shape of the image in (height, width).
Warning:
This transform only affects the image but not its associated
annotations, such as word bounding boxes and polygons. Therefore,
it may only be applicable to text recognition tasks.
Args:
op (str): The name of any transform class in
:func:`torchvision.transforms`.
**kwargs: Arguments that will be passed to initializer of torchvision
transform.
"""
def __init__(self, op: str, **kwargs) -> None:
assert isinstance(op, str)
obj_cls = getattr(torchvision_transforms, op)
self.torchvision = obj_cls(**kwargs)
self.op = op
self.kwargs = kwargs
def transform(self, results):
"""Transform the image.
Args:
results (dict): Result dict from the data loader.
Returns:
dict: Transformed results.
"""
assert 'img' in results
# BGR -> RGB
img = results['img'][..., ::-1]
img = Image.fromarray(img)
img = self.torchvision(img)
img = np.asarray(img)
img = img[..., ::-1]
results['img'] = img
results['img_shape'] = img.shape[:2]
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(op = {self.op}'
for k, v in self.kwargs.items():
repr_str += f', {k} = {v}'
repr_str += ')'
return repr_str
@TRANSFORMS.register_module()
class ConditionApply(BaseTransform):
"""Apply transforms according to the condition. If the condition is met,
true_transforms will be applied, otherwise false_transforms will be
applied.
Args:
condition (str): The string that can be evaluated to a boolean value.
true_transforms (list[dict]): Transforms to be applied if the condition
is met. Defaults to [].
false_transforms (list[dict]): Transforms to be applied if the
condition is not met. Defaults to [].
"""
def __init__(self,
condition: str,
true_transforms: Union[Dict, List[Dict]] = [],
false_transforms: Union[Dict, List[Dict]] = []):
self.condition = condition
self.true_transforms = Compose(true_transforms)
self.false_transforms = Compose(false_transforms)
def transform(self, results: Dict) -> Optional[Dict]:
"""Transform the image.
Args:
results (dict):Result dict containing the data to transform.
Returns:
dict: Transformed results.
"""
if eval(self.condition):
return self.true_transforms(results) # type: ignore
else:
return self.false_transforms(results)
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(condition = {self.condition}, '
repr_str += f'true_transforms = {self.true_transforms}, '
repr_str += f'false_transforms = {self.false_transforms})'
return repr_str
|