transform
data.transform.transform
ROIHandler
ImageLoader
여러 형태의 데이터를 입력으로 받아, 전처리 과정을 거쳐 PIL Image 혹은 np.ndarray 로 return 합니다. 현재 지원하는 데이터는 다음과 같습니다. - 데이터 타입: [image path, np.ndarray, PIL Image] - color: ["RGB", "Gray"] - bit: [8, 16]
입력으로 받은 데이터에 따른 출력값은 다음과 같습니다. | image path | np.ndarray | PIL | RGB; 8 | PIL(RGB;8) | PIL(RGB;8) | PIL(RGB;8) | RGB;16 | PIL(RGB;8) | PIL(RGB;8) | - | Gray; 8 | PIL(L;8) | PIL(L;8) | PIL(L;8) | Gray;16 | PIL(L;8) | PIL(L;8) | PIL(L;8) |
Note1
PIL은 RGB;16을 지원하지 않습니다. 따라서 PIL(RGB;16)은 입력으로 들어올 수 없습니다.
Note2
PIL은 "I;16" 모드로 Gray;16을 지원하지만, PIL 내부의 convert 함수를 써서 Gray;8로 변환시 값이 overflow 나는 issue가 있습니다.
Note3
이미지는 기본적으로 np.ndarray로 로드되며, PIL.Image.Image로 로드하려면 to_numpy=False를 세팅하세요.
Note4
image_mode는 "RGB", "L" 중 하나를 지원하며, multipage (이미지 리스트) 인 경우 각 페이지의 모드를 리스트로 입력하세요.
예시: 1, 3번째 페이지는 RGB 이고 2번째 페이지는 L 인 경우 image_mode = ["RGB", "L", "RGB"]
Source code in SaigeToolkit/data/transform/image_load.py
call_method
make [PIL Image or np.ndarray] from PIL.Image, np.ndarray, or path string
Parameters:
-
image(Union[Image, ndarray, str, List]) –PIL.Image, array, path string or list of it.
Returns:
-
Dict(Dict) –{ "image": Union[PIL.Image.Image, np.ndarray, List[PIL.Image.Image], List[np.ndarray]], **input_dict, }
Source code in SaigeToolkit/data/transform/image_load.py
load_from_path
Loading function using PIL.Image library. This function is introduced because {exif_transpose} must be processed. {exif_transpose} fix rotated image binary data using {EXIF} information. Without {exif_transpose}, network would accidently learn randomly rotated image data.
Parameters:
-
path(str) –path to image file
Returns:
-
Union[Image, ndarray]–Union[Image.Image, np.ndarray]: image
Source code in SaigeToolkit/data/transform/image_load.py
_convert_16_to_8
staticmethod
이미지 픽셀당 비트수를 16에서 8로 변화합니다. 입출력 데이터 타입이 같습니다. (pil로 받으면 pil을 ndarray로 받을 시 ndarray를 출력합니다.)
Source code in SaigeToolkit/data/transform/image_load.py
Resizer
Resizer(size: Optional[Union[ImageSizeType, int]] = None, scale: Optional[Union[int, float]] = None, area_sqrt: Optional[Union[int, float]] = None, max_size: Optional[Union[ImageSizeType, int]] = None, round: Optional[int] = None, round_type: str = 'round', resampling: str = 'bilinear', image_only: bool = False, use_cv2_for_numpy: bool = True)
Module for resizing PIL, torch, numpy images Resizer의 작동 방식은 다음과 같습니다. 1. target size 계산 2. target size 미세 조정 3. 데이터에 resize 적용
Args에 따라 1, 2번의 작동 방식이 달라집니다. 1. target size 계산 - resize 될 target size를 계산합니다. - target size는 4개의 args에 영향을 받을 수 있습니다. (size, scale, area_sqrt, max_size) 하나의 Resizer는 4개중 하나의 args만 사용할 수 있으며, 2개 이상의 args가 None이 아닐시 error를 raise 합니다. 1-1. size: image를 size로 resize 합니다. aspect ratio가 변경될 수 있습니다. 1-2. scale: image를 scale배로 늘리거나 줄입니다. aspect ratio는 유지됩니다. 1-3. area_sqrt: image의 면적이 area_sqrt^2이 되도록 이미지를 늘리거나 줄입니다. aspect ratio는 유지됩니다. 1-4. max_size: image의 size가 max_size보다 클 경우 max_size로 resize 합니다. aspect ratio를 유지하기 위해, width/height중 더 많이 줄어야 하는 비율에 맞추어 전체를 resize합니다.
- target size 미세 조정
- resize된 이미지가 특정 값의 배수가 되도록 target size를 미세 조정 합니다. model의 입력으로 넣을 때, image size가 특정 값의 배수가 되어야 하기 때문에 필요합니다.
-
- target size 계산의 size parameter와 함께 사용할 수 없습니다. (고정 size이기 때문)
- target size 미세 조정은 총 2개의 args에 영향을 받을 수 있습니다. (round, round_type) round가 None이면 미세 조정을 하지 않습니다, round_type에 따라 다른 방식의 미세 조정을 적용합니다. 2-1. round: 미세 조정시 반올림합니다. (target size보다 작거나 크거나 같습니다.) 2-2. floor: 미세 조정시 내림합니다. (target size보다 작거나 같습니다.) 2-3. ceil: 미세 조정시 올림합니다. (target size보다 크거나 같습니다.)
- 미세 조정된 target_size의 width혹은 height가 0이 될 경우, round 값으로 변경해줍니다. (ex. size=(3, 3), round=8이면 round_type에 상관없이 size=(8, 8)이 됨.)
Parameters:
-
size(Optional[Union[ImageSizeType, int]], default:None) –target image size. Defaults to None.
-
scale(Optional[Union[int, float]], default:None) –target image scale. Defaults to None.
-
area_sqrt(Optional[Union[int, float]], default:None) –target image sqrt area. Defaults to None.
-
max_size(Optional[Union[ImageSizeType, int]], default:None) –target maximum image size. Defaults to None.
-
round(Optional[int], default:None) –round image size. Defaults to None.
-
round_type(Optional[str], default:'round') –type of round image. One of ["round", "floor", "ceil"]. Defaults to "round".
-
resampling(str, default:'bilinear') –One of ["nearest", "bilinear", "bicubic"]. Defaults to "bilinear".
-
image_only(bool, default:False) –to resize image only. Defaults to False.
-
use_cv2_for_numpy(bool, default:True) –use cv2 instead of PIL for faster numpy array image resizing. Defaults to True.
Raises:
-
ResizerParameterValueError–target size parameter가 2개 이상 들어오면 error를 raise 합니다. round_type이 ["round", "floor", "ceil"]안에 없으면 error를 raise 합니다. size와 미세조정 parameter가 함께 들어오면 error를 raise 합니다.
Source code in SaigeToolkit/data/transform/resize.py
compute_input_size
staticmethod
compute_input_size(data: Dict) -> ImageSizeType
target size를 계산하기 위해 input size를 가져옵니다. Note: data에 image 혹은 mask data는 있다고 가정하며, 둘의 size는 같다고 가정합니다.
Source code in SaigeToolkit/data/transform/resize.py
compute_target_size
compute_target_size(input_size: Union[ImageSizeType, ndarray]) -> ImageSizeType
compute resize target size from input image size
Parameters:
-
input_size(Union[ImageSizeType, ndarray]) –(width, height)
Returns:
-
ImageSizeType(ImageSizeType) –(width, height)
Source code in SaigeToolkit/data/transform/resize.py
InspectionSizeResizer
InspectionSizeResizer(inspection_size_wh: Optional[ImageSizeType] = None, resizer: Optional[Resizer] = None)
Bases: Resizer
원본 이미지가 inspection_size를 넘지 않도록 resize 했을 때의 image scale만큼 resize를 해주는 resizer를 생성하는 class 입니다.
inspection_size는 원본 이미지에 대해 적용하지만, 실제 연산은 ROI가 먼저 계산되기 때문에, 원본 이미지가 inspection_size를 넘지 않도록 resize 했을 때의 image scale을 미리 계산해두고, 해당 scale만큼 resize를 하는 resizer를 생성하여 계산합니다.
Source code in SaigeToolkit/data/transform/resize.py
StackedResizerHandler
StackedResizerHandler(resizer_list: List[Optional[Resizer]])
같은 image에 대해 여러번의 resize가 연속적으로 적용될 때, 여러개의 resize를 하나로 묶어서 최종 target size로 한번에 resize를 해주는 class입니다.
Source code in SaigeToolkit/data/transform/resize.py
Transform
Transform(image_mode: Union[str, List[str]] = 'RGB', inspection_size_wh: Optional[ImageSizeType] = None, roi: Optional[Dict] = None, resize: Optional[Dict] = None, augmentation: Optional[Dict] = None, roi_mask_first: bool = True)
Source code in SaigeToolkit/data/transform/transform.py
__call__
data Dict에 transform을 적용합니다.
Parameters:
-
data(Dict) –data Dictionary
-
warmup(bool, default:False) –InferenceHandler warmup시에 사용하는 파라미터 입니다. True일 경우, 현재 transform을 적용했을 때 나올 수 있는 가장 큰 image size로 transform을 적용합니다. Transform operation 중 ROI의 경우 input image에 따라 output size가 매번 바뀔 수 있기 때문에 해당 옵션이 추가되었습니다. Defaults to False.
Returns:
-
Dict(Dict) –transform이 적용된 데이터 Dict입니다.
Source code in SaigeToolkit/data/transform/transform.py
get_resize_scale
classmethod
before_transform_image_size -> after_transform_input_size가 되기 위한 scale을 구합니다. before_transform_image_size * scale = after_transform_input_size
Parameters:
-
transform_params(Dict) –transform시에 저장해둔 parameter 입니다.
Returns:
-
List[float]–List[float]: before_transform_image_size * scale = after_transform_input_size인 scale scale: [scale_width, scale_height]
Source code in SaigeToolkit/data/transform/transform.py
_get_next_revert_operation
staticmethod
다음으로 할 revert operation을 가져옵니다. operation_stack에서 operation이 제거되지는 않습니다.
Parameters:
-
transform_params(Dict) –transform시에 저장해둔 parameter 입니다.
Returns:
-
Optional[Operation]–Optional[Operation]: 남아있는 revert operation이 있으면 operation을 없으면 None을 반환합니다.
Source code in SaigeToolkit/data/transform/transform.py
revert
classmethod
summary
Parameters:
-
data(Dict) –revert operation을 적용할 data dictionary입니다. data는 다음과 같은 구조를 지닙니다. { "key1": { "data" (Union[np.ndarray, torch.Tensor, List[Dict]]): 실제 data입니다. "data_type" (str): 해당 data의 type 입니다. 현재 ["array", "objects"]를 지원합니다. }, "key2": { "data" (Union[np.ndarray, torch.Tensor, List[Dict]]): 실제 data입니다. "data_type" (str): 해당 data의 type 입니다. 현재 ["array", "objects"]를 지원합니다. }, ... }
-
transform_params(Dict) –transform시에 저장해둔 parameter 입니다.
-
operation(Optional[Operation], default:None) –transform에서 revert가 가능한 operation 입니다. Enum class인 Transform.Operation에 있는 항목들을 지원합니다. operation이 None이 아닐 시, 해당 operation 까지 revert를 적용하고, None일 시, 그 다음 revert operation을 적용합니다. Defaults to None.
Raises:
-
RevertOperationNotFoundError–args로 넣은 operation이 남은 revert operation 중에 없을 때 에러를 발생합니다.
Returns:
-
Dict(Dict) –revert operation이 적용된 data dictionary 입니다. 구조는 Args의 data와 같습니다.
Source code in SaigeToolkit/data/transform/transform.py
is_oversized
staticmethod
InspectionSize 연산에서 resize 되었는지 여부를 판단
Source code in SaigeToolkit/data/transform/transform.py
translate_polygon
translate_polygon(polygons: PolygonType, offset: Tuple[int]) -> PolygonType
Translate polyfon from [(x1, y1), ... ] to [(x1 - x_offset), (y1 - y_offset), ...]
Source code in SaigeToolkit/data/transform/polygon_function.py
build_augmentation
build_augmentation(config: Dict) -> Augmentation
Source code in SaigeToolkit/data/transform/augmentation/builder.py
resize_polygon
resize_polygon(polygons: PolygonType, image_size: Tuple[int], tw: int, th: int) -> PolygonType
Resize polygon from (w, h) to (tw, th)
Source code in SaigeToolkit/data/transform/polygon_function.py
resize_array
resize_array(array: Union[Tensor, ndarray], target_size: ImageSizeType, resampling: str = 'nearest') -> Union[Tensor, ndarray]
[HW, BHW]의 array를 resize합니다.
Parameters:
-
array(Union[Tensor, ndarray]) –array data [HW, BHW]
-
target_size(ImageSizeType) –[W, H]
-
resampling(str, default:'nearest') –resampling method. Defaults to "nearest".
Returns:
-
Union[Tensor, ndarray]–Union[torch.Tensor, np.ndarray]: resized array
Source code in SaigeToolkit/data/transform/image_function.py
add_constant_margin_array
add_constant_margin_array(array: Union[Tensor, ndarray], left: int, top: int, right: int, bottom: int, value: Union[float, int]) -> Union[Tensor, ndarray]
array에 left, top, right, bottom 만큼 constant value로 padding 합니다.
Parameters:
-
array(Union[Tensor, ndarray]) –array data [HW, BHW]
-
left(int) –array의 왼쪽 padding size 입니다.
-
top(int) –array의 위쪽 padding size 입니다.
-
right(int) –array의 오른쪽 padding size 입니다.
-
bottom(int) –array의 아래쪽 padding size 입니다.
-
value(Union[float, int]) –padding된 영역에 들어갈 value 입니다.