data
Module diagram
classDiagram
class data {
}
class batch_sampler {
}
class balanced_sampler {
}
class base_sampler {
}
class builder {
}
class class_sampler {
}
class collate {
}
class crop {
}
class base_cropper {
}
class builder {
}
class edge_cropper {
}
class ocr_cropper {
}
class polygon_cropper {
}
class dataclass {
}
class box {
}
class segment {
}
class dataset {
}
class base_dataset {
}
class builder {
}
class platform_reader {
}
class saige_vision_reader {
}
class srproj_dataset {
}
class srproj_reader {
}
class process_config {
}
class sampler {
}
class builder {
}
class infinite_random_sampler {
}
class transform {
}
class augmentation {
}
class api {
}
class augment_function {
}
class augment_transform {
}
class base_transform {
}
class builder {
}
class compose {
}
class base_compose {
}
class builder {
}
class compose {
}
class box_function {
}
class function_util {
}
class image_function {
}
class image_load {
}
class polygon_function {
}
class resize {
}
class roi {
}
class api {
}
class roi_calculator {
}
class roi_handler {
}
class transform {
}
class typevar {
}
batch_sampler --> builder
balanced_sampler --> base_sampler
builder --> balanced_sampler
builder --> base_sampler
builder --> class_sampler
class_sampler --> base_sampler
crop --> builder
builder --> base_cropper
builder --> edge_cropper
builder --> ocr_cropper
builder --> polygon_cropper
edge_cropper --> base_cropper
polygon_cropper --> base_cropper
dataset --> builder
builder --> base_dataset
builder --> srproj_dataset
srproj_dataset --> base_dataset
srproj_dataset --> srproj_reader
sampler --> builder
builder --> infinite_random_sampler
augmentation --> builder
api --> augment_function
augment_transform --> augment_function
augment_transform --> base_transform
builder --> augment_transform
builder --> builder
builder --> compose
compose --> base_compose
box_function --> polygon_function
box_function --> typevar
function_util --> typevar
image_function --> typevar
image_load --> image_function
polygon_function --> augment_function
polygon_function --> typevar
resize --> box_function
resize --> image_function
resize --> polygon_function
resize --> typevar
roi --> api
roi --> roi_handler
api --> roi_handler
roi_handler --> roi_calculator
transform --> augmentation
transform --> image_function
transform --> image_load
transform --> resize
transform --> roi_handler
data
데이터 처리 및 변환, 샘플링 등 data 관련 기능을 제공합니다.
- batch_samper: torch dataloader와 호환 가능한 커스텀 batch sampler를 관리하는 모듈입니다.
- sampler: torch dataloader와 호환 가능한 커스텀 sampler를 관리하는 모듈입니다.
- dataset: 커스텀 데이터셋을 정의하고 관리하는 모듈입니다.
- transform: Data augmentation을 위한 Transform 클래스 및 여러 Data Transform들을 하나로 묶어서 관리해주는 Compose 클래스를 제공합니다.
- crop: 데이터셋에 포함되어 이미지 crop을 수행하는 Cropper 클래스를 제공합니다.
- dataclass: Box, Segment 등 각종 커스텀 데이터 클래스를 정의하고 관리하는 모듈입니다.
batch_sampler
torch dataloader와 호환 가능한 커스텀 batch sampler를 관리하는 모듈입니다.
BatchSampler 클래스를 상속받아 새로운 batch sampler를 정의할 수 있습니다.
balanced_sampler
BalancedSampler
BalancedSampler(dataset: Dataset, balance_keys: Optional[List[str]] = None, balance_ratios: Optional[List[float]] = None, calculate_patch_number: bool = False, shuffle: bool = True, **kwargs)
Bases: BatchSampler
Sampler implementation for weighted API dataset balancing.
Sampler class is used to specify the sequence of indices/keys used in data loading. This class represents iterable objects over the indices to datasets.
When __iter__ is called, Sampler creates self.buffer, a sequence of data indices
which is balanced to has exact same number of data sample from each data subset.
If balance_ratio is given, sampler autmatically re-weights each subset. Otherwise,
each subset will be balanced to be equal size.
Attributes:
-
dataset(Dataset) –dataset instance to be sampled
-
calculate_patch_number(bool) –whether update number of patches in dataset, after sampling
-
subset_data_indices(List[List[int]]) –split data indices, based on subset descriminator
-
multipliers(ndarray) –number of repeats for each data subset
-
remainers(ndarray) –number of remainers for each data subset
-
shuffle(bool) –whether shuffle output data indices after sampling
-
buffer(ndarray) –data indices for one epoch (accept duplication)
Note
Given:
-
dataset: Dataset with number of sample 300. which can be splitted into two subsets using given key set[key_a, key_b].subset_a: Data subset with number of sample 100, corresponds tokey_a.subset_b: Data subset with number of sample 200, corresponds tokey_b.
The word
correspondsmeans that eachdomain,source, andcategoryvalue parsed from the key is same to that of metadata information of each data in subset.
Output:
iterator: An iterator with 200 indices from subset_a and 200 indices from subset_b. The max element of iterator will be 299, which is len(subset_a) + len(subset_b) - 1.
The iterator must be directly fed to torch.utils.data.DataLoader class initializer
with name sample, along with torch.utils.data.ApiDataset object.
Examples:
loader = torch.utils.data.DataLoader(
dataset=torch.utils.data.ApiDataset(...),
shuffle=False,
batch_sampler=BalancedDatasetSampler(
dataset,
balance_keys=["Document/AI_HUB", "Document/CJ"],
balance_ratios=[0.6, 0.3],
),
)
Reference: https://pytorch.org/docs/stable/data.html#data-loading-order-and-sampler
initializing balance sampler
Parameters:
-
dataset(Dataset) –dataset to be sampled. directly set to class attribute.
-
balance_keys(List[str], default:None) –domain-source-categoty keys as subset descriminator. Defaults to None.
-
balance_ratios(Optional[List[float]], default:None) –balance of subsets. if None, subsets are equally sampled. Defaults to None.
-
calculate_patch_number(bool, default:False) –boolean to calculate patch_number after sampling. directly set to class attribute. Defaults to False.
-
shuffle(bool, default:True) –boolean to shuffle data sample. Defaults to True.
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
calculate_patch_number
instance-attribute
calculate_patch_number = True if crop_fn is not None else calculate_patch_number
balance_state
instance-attribute
_build_default_balance_keys
Build default balance_keys which is grouping all domain-source-category separately
Parameters:
-
dataset(Dataset) –dataset instance. should have
filesattribute (SaigeDataset). each file data should have domain, source, category information, which would be used as subset descriminator.
Returns:
-
List[str]–List[str]: balance_key list example: ["Document/AI_HUB", "Document/CJ"]
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
_extract_domain_source_category_from_key
A function that parses given key for balancing.
empty string between slash (/) or "None" string will be treated as None-key
This function assumes target key is in the form of ...
"{domain}" # or ...
"{domain}/{source}" # or ...
"{domain}/{source}/{category}"
"''/None/{category}"
Parameters:
-
key(str) –Key string for separating datasets into subsets.
Returns:
-
List[List[str]]–List[List[str]]: domain_source_category_list. Key string parsed into list.
-
List[List[str]]–(ex)
-
List[List[str]]–```
-
List[List[str]]–["Document", None, None]
-
List[List[str]]–["Document", "AI_HUB", None]
-
List[List[str]]–["Document", "AI_HUB", "상.하수도관리"]
-
List[List[str]]–[None, None, "상.하수도관리"]
-
List[List[str]]–```
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
_split_dataset_indices_using_keys
A function that splits dataset using given keys.
Each key contains metadata info: domain, source, and category.
This key information will be used to separate total dataset into specific subsets.
For each data in dataset, check whether data's domain, source, and category corresponds to the key information.
For example, if a key is given as below:
Then the subset will be generated containing only index of data with metadata of:
For another example, if a key is given as below:
Then the subset will be generated containing only index of data with metadata of:
This generation process will be repeated for each key in target_keys.
Parameters:
-
target_keys(List[str]) –List key for subset balancing.
Returns:
-
List[List[int]]–List[List[int]]: subset_data_indices. List of data index list. Each element represents a subset of dataset.
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
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 | |
match_identifier
Check data identifier matches non-None target identifier identifier: [domain, source, category]
Parameters:
-
id_data(Optional[str]) –data item identifier
-
id_target(Optional[str]) –balance target subset identifier
Returns:
-
bool(bool) –whether id's are matched
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
_update_subset_sizes
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
_calculate_subset_weights
Calculate subset multiplier and remainer using following two variables: balance_ratios, subset_size_ratios
balance_ratios: resultant data exposure ratio by subsets subset_size_ratios: data sizes ratio between subsets
Parameters:
-
balance_ratios(ndarray) –resultant data exposure ratio by subsets
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
generate_buffer
Creates index list of data instances, which is already balanced.
Exact result can be always different even when shuffle=False when non-zero element
in self.balance_state[key]["remainer"] exists.
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
_update_dataset_num_patch
Updates n_patch attribute in dataset, when indices is updated. (due to changes in remainer items)
Parameters:
-
indices(Union[deque, List[int]]) –file indices for calculating data patch number
Returns:
-
int(int) –number of patches in files
Source code in SaigeToolkit/data/batch_sampler/balanced_sampler.py
base_sampler
Batch sampler 클래스의 기본이 되는 추상 클래스를 정의한 모듈입니다.
BatchSampler 클래스를 상속받아 새로운 batch sampler를 정의할 수 있습니다.
Naive sampler는 가장 기본적인 sampler 구현 예시로, 데이터셋의 인덱스를 순서대로 배치로 묶어 반환합니다.
BatchSampler
BatchSampler(dataset: Dataset, batch_size: int = 1, repeat: bool = False, shuffle: bool = False, drop_last: bool = False)
Bases: Registerable, ABC
Baseclass for all batch_sampler classes.
Attributes:
-
dataset(Dataset) –dataset to sample from.
-
batch_size(int) –batch size.
-
repeat(bool) –repeat data when data is not enough for batch size.
-
shuffle(bool) –shuffle data.
-
drop_last(bool) –drop last data when data is not enough for batch size.
Note
batch_size,shuffle, anddrop_lastshould be popped from dataloader config, then passed to the batch sampler config.repeat: for SaigeVision2 api, should be set asTrue.- if number of data is enough for batch size, then
repeatis neglected.
- if number of data is enough for batch size, then
drop_last: for SaigeVision2 api, should be set asTrue.- to prevent the last batch from being smaller than the specified batch size.
- if
False, even whenrepeatis set asTrue, the last batch will be smaller than the specified batch size.
- for Training,
shuffleshould be set asTrue.drop_lastandrepeatare optional.
- for Validation,
repeat,shuffle, anddrop_lastshould be set asFalse.
Examples:
cfg_sampler.update(
{
"shuffle": cfg_dataloader.pop("shuffle", False),
"drop_last": cfg_dataloader.pop("drop_last", False),
"batch_size": cfg_dataloader.pop("batch_size", 1),
}
)
batch_sampler = build_batch_sampler(dataset=dataset, **cfg_sampler)
dataloader = build_dataloader(
dataset,
collate_fn=collate_fn,
batch_sampler=batch_sampler,
**cfg_dataloader,
)
Source code in SaigeToolkit/data/batch_sampler/base_sampler.py
__iter__
Source code in SaigeToolkit/data/batch_sampler/base_sampler.py
_get_processed_buffer
_shuffle_and_repeat_buffer
Source code in SaigeToolkit/data/batch_sampler/base_sampler.py
_batch_buffer
Source code in SaigeToolkit/data/batch_sampler/base_sampler.py
__len__
NaiveSampler
NaiveSampler(dataset: Dataset, batch_size: int = 1, repeat: bool = False, shuffle: bool = False, drop_last: bool = False)
Bases: BatchSampler
Naive sampler implementation with buffer extension feature added.
Source code in SaigeToolkit/data/batch_sampler/base_sampler.py
builder
build_batch_sampler
build_batch_sampler(_target_: str, **config) -> BatchSampler
class_sampler
ClassBalancedSampler
Bases: BatchSampler
Sampler implementation for simple class balancing.
Uses class_index value in dataset file dictionaries.
When more than one classes exist in single image, the multiplier of
the rarest class within image will be applied to the data.
Raises:
-
IndexError–Will be raised when class index exceeds MAX_NUM_CLS.
Notes
- TODO: Weighted balancing.
- TODO: Cropper applicability.
Source code in SaigeToolkit/data/batch_sampler/class_sampler.py
_make_weights_for_balanced_classes
Source code in SaigeToolkit/data/batch_sampler/class_sampler.py
generate_buffer
Source code in SaigeToolkit/data/batch_sampler/class_sampler.py
collate
images_to_4d_tensor
images_to_4d_tensor(images: List[Union[ndarray, Image, List]], device: device = default_device, apply_contiguous_div255: bool = True) -> Tensor
Converts a list of images to a 4D tensor.
Parameters:
-
images(List[Union[ndarray, Image, List]]) –images to convert.
-
device(device, default:default_device) –device to move the tensor to. Defaults to cpu.
-
apply_contiguous_div255(bool, default:True) –whether to apply contiguous_div255. Defaults to True.
Returns:
-
Tensor–torch.Tensor: 4D tensor of images.
Source code in SaigeToolkit/data/collate.py
_contiguous_div255
_merge_multipage_to_n_channel_array
Source code in SaigeToolkit/data/collate.py
crop
데이터 전처리를 위한 cropper 클래스를 제공합니다.
모든 cropper 클래스는 BaseCropper 클래스를 상속받아 구현되어 있으며, get_n_patch와 call 메소드를 구현해야 합니다.
- get_n_patch 메소드는 이미지를 잘라낼 때 몇 개의 패치로 나눌지를 결정합니다.
- call 메소드는 이미지를 입력받아 패치로 나누어 반환합니다.
사용 방식에 대해서는 dataset/base_dataset.py를 참고해주세요.
base_cropper
Cropper 클래스의 추상화를 위한 BaseCropper 클래스를 제공합니다.
모든 Cropper 클래스는 BaseCropper 클래스를 상속받아 구현되어야 하며, get_n_patch와 call 메소드를 구현해야 합니다.
BaseCropper
Bases: ABC
get_n_patch
abstractmethod
builder
CROPPER_IMPLEMENTATION
module-attribute
CROPPER_IMPLEMENTATION = {'ocr': OcrCropper, 'polygon': PolygonCropper, 'edge': EdgeCropper}
get_crop_fn
get_crop_fn(_target_: Optional[str] = None, **cfg_crop: dict) -> Optional[BaseCropper]
getting crop function
Parameters:
-
cfg_crop(dict, default:{}) –config dict for building cropper
Returns:
-
Optional[BaseCropper]–Optional[BaseCropper]: saige cropper object. if cfg_crop is None, return None
Source code in SaigeToolkit/data/crop/builder.py
get_crop_class
get_crop_class(cfg_crop_name: str) -> Type[BaseCropper]
getting crop class from name
Parameters:
-
cfg_crop_name(str) –cropper name
Returns:
-
Type[BaseCropper]–Type[BaseCropper]: cropper class
Source code in SaigeToolkit/data/crop/builder.py
edge_cropper
Crop image patches along the contour of mask (or polygon)
Imported from DefectGeneration repository. generation/data/crop/edge_cropper.py
WindowState
Bases: Enum
relation state enum between center point and target point
WindowManager
Manager for cropping window size, relation and window coordinates.
Attributes:
-
width(int) –window width for image patch.
-
half_width(int) –half of window width for image patch.
-
height(int) –window height for image patch.
-
half_height(int) –half of window height for image patch.
-
strict_inner_patch(bool) –whether not allowing outer area of image.
Source code in SaigeToolkit/data/crop/edge_cropper.py
check_window
check_window(point: Iterable[int], center: Iterable[int]) -> WindowState
check whether target point is inside of window, returns WindowState
Parameters:
-
point(Iterable[int]) –target point to be checked
-
center(Iterable[int]) –reference center point
Returns:
-
WindowState(WindowState) –relation state enum
Source code in SaigeToolkit/data/crop/edge_cropper.py
is_in_window
is target point inside of window
Parameters:
-
point(Iterable[int]) –target point to be checked
-
center(Iterable[int]) –reference center point
Returns:
-
bool(bool) –boolean result
Source code in SaigeToolkit/data/crop/edge_cropper.py
is_in_any_window
is target point inside of any of windows
Parameters:
-
point(Iterable[int]) –target point to be checked
-
center(Iterable[int]) –list of reference center points
Returns:
-
bool(bool) –boolean result
Source code in SaigeToolkit/data/crop/edge_cropper.py
get_coordinates_from_center
get_coordinates_from_center(h_center: int, w_center: int, h: int, w: int) -> Tuple[int, int, int, int]
get left/right top/bottom coordinates from picked center point.
Parameters:
-
h_center(int) –picked center point h-coordinate
-
w_center(int) –picked center point w-coordinate
-
h(int) –image size height
-
w(int) –image size width
Returns:
-
Tuple[int, int, int, int]–Tuple[int, int, int, int]: (crop_left, crop_top, crop_right, crop_bottom)
Source code in SaigeToolkit/data/crop/edge_cropper.py
CenterWithSatellite
dataclass
CenterWithSatellite(point: Iterable[int], window_manager: WindowManager, satellite: Optional[Iterable[int]] = None)
Center point with 'satellites'. 'Satellites' is a point within center point's window, but not the center point. Also intra distance between 'satellites' should shorter than window size.
Attributes:
-
coordinate(Iterable[int]) –center point coordinate
-
window_manager(WindowManager) –WindowManager
-
max_width_distance(int) –max width-wise positive distance of satellites
-
max_height_distance(int) –max height-wise positive distance of satellites
-
min_width_distance(int) –max width-wise negative distance of satellites
-
min_height_distance(int) –max height-wise negative distance of satellites
-
satellite_points(List[Dict[str, any]]) –satellite_points data
Source code in SaigeToolkit/data/crop/edge_cropper.py
calculate_relation_as_satellite
calculate_relation_as_satellite(point: Iterable[int]) -> Union[Dict[str, Any], List[Dict[str, Any]]]
calculate relation between target point and center point. case 1: If target point is outside of center point's window, target point should be considered as next center point candidate.
case 2
Even when target point is in the window, check whether distance between satellites is larger than window size. If so, target point should be considered as next center point candidate.
Parameters:
-
point(Iterable[int]) –target point to be checked
Returns:
-
Union[Dict[str, Any], List[Dict[str, Any]]]–Union[Dict[str, Any], List[Dict[str, Any]]]: Dict[str, Any]: simple relation between center point and target point List[Dict[str, Any]]: reltations between satellite points and target point
Source code in SaigeToolkit/data/crop/edge_cropper.py
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 | |
_compare_point_and_calculate_error
Refactored from the original code from Defect Generation (Function extracted).
Source code in SaigeToolkit/data/crop/edge_cropper.py
EdgeCropper
EdgeCropper(crop_w: int = 512, crop_h: int = 512, random_sample: bool = False, patch_per_polygon: int = 1, strict_inner_patch: bool = True, ok_patch_prob: float = 0.01)
Bases: BaseCropper
Crop image patches along the contour of mask (or polygon)
Attributes:
-
window_manager(WindowManager) –WindowManager
-
random_sample(bool) –whether randomly select the first point of each polygon
-
patch_per_polygon(bool) –number of repeat for cropping patches around each polygon.
Source code in SaigeToolkit/data/crop/edge_cropper.py
window_manager
instance-attribute
window_manager = WindowManager(crop_w, crop_h, strict_inner_patch)
init_centers
get_n_patch
PolygonCropper crops all polygon areas {self.patch_per_polygon} times per polygons, and also crops random position of image {self.random_patch_per_img} times per images. Therefore, resultant number of patches is weighted-sum result as coded below.
Parameters:
-
polygons(List[ndarray]) –polygons of single image in dataset.
Returns:
-
int(int) –number of patches to be cropped in single image
Source code in SaigeToolkit/data/crop/edge_cropper.py
__call__
__call__(image: Union[Image, ndarray], mask: Union[Image, ndarray], polygons: Optional[List[ndarray]] = None, **kwargs) -> List[dict]
crop image into image patches.
Parameters:
-
image(Union[Image, ndarray]) –original image
-
polygons(List[ndarray], default:None) –polygon data (# of polygons, (4, 2)) polygon should have 4 points
-
mask(Union[Image, ndarray]) –segmentation mask image
Returns:
-
List[dict]–List[dict]: list of cropped image data dict
Source code in SaigeToolkit/data/crop/edge_cropper.py
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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 | |
get_data_dict_from_center_point
get_data_dict_from_center_point(image: Union[Image, ndarray], mask: Union[Image, ndarray], center, **kwargs)
Source code in SaigeToolkit/data/crop/edge_cropper.py
pick_centers_from_polygon
Source code in SaigeToolkit/data/crop/edge_cropper.py
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 | |
get_proper_point
get_proper_point(state_as_satellite: Union[Dict[str, Any], List[Dict[str, Any]]], must_contain_coordinate: List[Iterable[int]], point_in: Iterable[int], point_out: Iterable[int]) -> Optional[Iterable[int]]
get proper next center point that contains every must_contain_coordinate
Parameters:
-
state_as_satellite(Union[Dict[str, Any], List[Dict[str, Any]]]) –relation between center point(s) and target point.
-
must_contain_coordinate(List[Iterable[int]]) –points should be in next window
-
point_in(Iterable[int]) –point inside window from previous boundary
-
point_out(Iterable[int]) –point outside window from previous boundary
Returns:
-
Optional[Iterable[int]]–Optional[Iterable[int]]: proper next center (or None)
Source code in SaigeToolkit/data/crop/edge_cropper.py
get_destination_point
get_destination_point(relation: WindowState, point_ref: Iterable[int], point_in: Iterable[int], point_out: Iterable[int]) -> ndarray
calculate point a-window-away from reference point
Parameters:
-
relation(WindowState) –relation between reference point and next center
-
point_ref(Iterable[int]) –reference point to calculate next center
-
point_in(Iterable[int]) –point inside window from previous boundary
-
point_out(Iterable[int]) –point outside window from previous boundary
Returns:
-
ndarray–np.ndarray: result destination point
Source code in SaigeToolkit/data/crop/edge_cropper.py
remove_inner_points_and_get_outer_points
remove_inner_points_and_get_outer_points(center: Iterable[int], points: List[Iterable[int]]) -> Tuple[List[Iterable[int]], Iterable[int], Iterable[int]]
once center decided, check other points and remove insiders.
Parameters:
-
center(Iterable[int]) –next center coordinate
-
points(List[Iterable[int]]) –current points on polygon
Returns:
-
Tuple[List[Iterable[int]], Iterable[int], Iterable[int]]–Tuple[List[Iterable[int]], Iterable[int], Iterable[int]]: - List[Iterable[int]]: clean-up'd polygon points - Iterable[int]: boundary point (positive direction) - Iterable[int]: boundary point (negative direction)
Source code in SaigeToolkit/data/crop/edge_cropper.py
subdivide_points_into_min_resolution
subdivide_points_into_min_resolution(points: List[Iterable[int]], width_resolution: int = 32, height_resolution: int = 32) -> List[Iterable[int]]
refine cv2.findContours result. long straight edge in mask results in long distance between two points.
Parameters:
-
points(List[Iterable[int]]) –cv2.findContours result
-
width_resolution(int, default:32) –maximum distance width-wise. Defaults to 32.
-
height_resolution(int, default:32) –maximum distance height-wise. Defaults to 32.
Returns:
-
List[Iterable[int]]–List[Iterable[int]]: refined polygon points
Source code in SaigeToolkit/data/crop/edge_cropper.py
get_mid_point
In case failed to get next center point, get mid point from remaining polygon points.
Parameters:
-
points(List[Iterable[int]]) –remaining polygon points
Returns:
-
Iterable[int]–Iterable[int]: next center point (mid)
Source code in SaigeToolkit/data/crop/edge_cropper.py
ocr_cropper
OcrCropper
OcrCropper(chr_height: int = 32, crop_jitter: Optional[float] = None, crop_jitter_rate: Optional[List[float]] = None, save_polygons: bool = False)
Cropper class for OCR task.
Attributes:
-
chr_height(int) –cropped image patch is resized to be the same height as chr_height.
-
crop_jitter(Optional[float]) –if not None, cropping box is jittered horizontally with ratio crop_jitter.
-
crop_jitter_rate(Optional[List[float]]) –if not None, cropping box points are jittered to any direction with ratio crop_jitter_rate.
-
save_polygons(bool) –whether polygon label is preserved after cropping.
initializing OcrCropper. all initializing input is set to class attribute.
Parameters:
-
chr_height(int, default:32) –Defaults to 32.
-
crop_jitter(Optional[float], default:None) –Defaults to None.
-
crop_jitter_rate(Optional[List[float]], default:None) –Defaults to None.
-
save_polygons(bool, default:False) –Defaults to False.
Source code in SaigeToolkit/data/crop/ocr_cropper.py
get_n_patch
OcrCropper only crops all polygon areas, unlike SegCropper. Therefore, resultant number of patches is simply equals to number of polygons.
Parameters:
-
polygons(List[List[ndarray]]) –polygons of all images in dataset.
Returns:
-
int(int) –total number of patches to be cropped
Source code in SaigeToolkit/data/crop/ocr_cropper.py
__call__
__call__(image: Union[Image, ndarray], polygons: List[ndarray], strings: List[str], ignore: List[bool], is_vertical: Optional[List[bool]] = None, **kwargs) -> List[dict]
crop image into image patches. polygon, string, ignore data should be same length.
Parameters:
-
image(Union[Image, ndarray]) –original image
-
polygons(List[ndarray]) –polygon data (# of polygons, (4, 2)) polygon should have 4 points
-
strings(List[str]) –string data
-
ignore(List[bool]) –ignore notation data
-
is_vertical(List[bool], default:None) –is_vertical notation data
Returns:
-
List[dict]–List[dict]: list of cropped image data dict
Source code in SaigeToolkit/data/crop/ocr_cropper.py
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 | |
calculate_width_height
calculate width and heights for every four polygon points (2 tops and 2 bots). Assuming that polygon is composed of top-points and bot-points, and every top and bot points are paired.
Parameters:
-
tops(ndarray) –top points of polygon
-
bots(ndarray) –bot points of polygon
Returns:
-
Tuple[List[ndarray], List[ndarray]]–Tuple[List[np.ndarray]]: width and height list for every four points.
Source code in SaigeToolkit/data/crop/ocr_cropper.py
jitter_polygon
jittering polygon points and split into tops and bots points
Parameters:
-
polygon(ndarray) –original polygon data
Returns:
-
Tuple[ndarray, ndarray]–Tuple[np.ndarray, np.ndarray]: jittered tops, bots points
Source code in SaigeToolkit/data/crop/ocr_cropper.py
polygon_cropper
PolygonCropper
PolygonCropper(mode: str = 'center', crop_w: int = 512, crop_h: int = 512, patch_per_polygon: int = 1, random_patch_per_img: int = 1, max_patch_per_img: Optional[int] = None, force_random_patch_normal: bool = False, strict_inner_patch: bool = False, fixed_polygon_order: bool = False)
Bases: BaseCropper
Crop image patches using polygons
Attributes:
-
mode(str) –cropping mode. ["center", "defectrandom"] available
-
crop_w(int) –cropping width for image patch.
-
crop_h(int) –cropping height for image patch.
-
half_w(int) –half of cropping width.
-
half_h(int) –half of cropping height.
-
patch_per_polygon(int) –number of repeat for cropping patch around each polygon.
-
random_patch_per_img(int) –number of random patch cropping per image.
-
force_random_patch_normal(bool) –whether random patch should not contain polygon area.
-
strict_inner_patch(bool) –whether not allowing outer area of image.
-
fixed_polygon_order(bool) –whether order of polygons is fixed during cropping.
All input is directly set to class attribute.
Parameters:
-
mode(str, default:'center') –Defaults to "center".
-
crop_w(int, default:512) –Defaults to 512.
-
crop_h(int, default:512) –Defaults to 512.
-
patch_per_polygon(int, default:1) –Defaults to 1.
-
random_patch_per_img(int, default:1) –Defaults to 1.
-
force_random_patch_normal(bool, default:False) –Defaults to False.
-
strict_inner_patch(bool, default:False) –Defaults to False.
-
fixed_polygon_order(bool, default:False) –Defaults to False.
Source code in SaigeToolkit/data/crop/polygon_cropper.py
get_n_patch
PolygonCropper crops all polygon areas {self.patch_per_polygon} times per polygons, and also crops random position of image {self.random_patch_per_img} times per images. Therefore, resultant number of patches is weighted-sum result as coded below.
Parameters:
-
polygons(List[ndarray]) –polygons of single image in dataset.
Returns:
-
int(int) –number of patches to be cropped in single image
Source code in SaigeToolkit/data/crop/polygon_cropper.py
pick_point
picking cropping center point.
Parameters:
-
polygon(ndarray) –original polygon data
Raises:
-
NotImplementedError–only two modes ["center", "defectrandom"] available
Returns:
-
Tuple[int, int]–Tuple[int, int]: picked point, (h_center, w_center)
Source code in SaigeToolkit/data/crop/polygon_cropper.py
get_coordinates_from_center
get_coordinates_from_center(h_center: int, w_center: int, h: int, w: int) -> Tuple[int, int, int, int]
get left/right top/bottom coordinates from picked center point.
Parameters:
-
h_center(int) –picked center point h-coordinate
-
w_center(int) –picked center point w-coordinate
-
h(int) –image size height
-
w(int) –image size width
Returns:
-
Tuple[int, int, int, int]–Tuple[int, int, int, int]: (crop_left, crop_top, crop_right, crop_bottom)
Source code in SaigeToolkit/data/crop/polygon_cropper.py
__call__
__call__(image: Union[Image, ndarray], mask: Union[Image, ndarray], polygons: Optional[List[ndarray]] = None, **kwargs) -> List[dict]
crop image into image patches.
Parameters:
-
image(Union[Image, ndarray]) –original image
-
polygons(List[ndarray], default:None) –polygon data (# of polygons, (4, 2)) polygon should have 4 points
-
mask(Union[Image, ndarray]) –segmentation mask image
Returns:
-
List[dict]–List[dict]: list of cropped image data dict
Source code in SaigeToolkit/data/crop/polygon_cropper.py
dataclass
커스텀 데이터 클래스 구현과 관련 메서드를 포함한 모듈입니다.
box
boxes_datas
module-attribute
boxes_datas = {'xyxy': [[1, 2, 4, 6], [22, 28, 36, 62], [13, 39, 14, 78], [42, 24, 81, 46]], 'xywh': [[1, 2, 3, 4], [22, 28, 14, 34], [13, 39, 1, 39], [42, 24, 39, 22]], 'ccwh': [[2.5, 4, 3, 4], [29, 45, 14, 34], [13.5, 58.5, 1, 39], [61.5, 35, 39, 22]]}
NumpyBoxes
Bases: ndarray
__new__
__new__(input_array, coordinate: str, dtype=None) -> NumpyBoxes
__array_finalize__
__array_function__
Source code in SaigeToolkit/data/dataclass/box.py
convert_coordinate
convert_coordinate(coordinate: str) -> NumpyBoxes
to_numpy
to_tensor
_check_boxes
staticmethod
convert_coordinate
convert_coordinate(boxes: Union[ndarray, Tensor], source_coordinate: str, target_coordinate: str) -> Union[ndarray, Tensor]
Source code in SaigeToolkit/data/dataclass/box.py
test_init_box
test_init_box(box_data, coordinate) -> NumpyBoxes
test_base_function
test_base_function(boxes: NumpyBoxes)
Source code in SaigeToolkit/data/dataclass/box.py
test_convert_coordinate
test_convert_coordinate(boxes: NumpyBoxes, coordinate, answer)
test_to_other_data
test_to_other_data(boxes: NumpyBoxes, answer)
segment
contours_area_methods
module-attribute
contours_area_methods = {'exact': compute_contours_area_exact, 'fast': compute_contours_area_fast, 'fast_plus': compute_contours_area_fast_plus, 'fast_plusplus': compute_contours_area_fast_plusplus}
SegmentBox
dataclass
from_xywh
classmethod
from_xywh(left, top, width, height) -> SegmentBox
from_xyxy
classmethod
from_xyxy(left, top, right, bottom) -> SegmentBox
Segment
Segment(bounding_box: Optional[SegmentBox] = None, bitmap: Optional[ndarray] = None, contours: Optional[Contours] = None, class_index: Optional[int] = None)
Segment 타입을 정의합니다. (= SegmentedObject) Segmentation 라벨링 혹은 모델의 예측 결과로 나오는 연결된 픽셀 덩어리이며, 1개의 outer polygon과 여러개의 inner polygon (도넛 형태인 경우) 으로 구성된 오브젝트입니다.
해당 오브젝트를 표현하는 방식은 2가지가 존재하며, segment를 이용해 어떤 연산을 수행하는가에 따라 다른 표현 방식이 필요합니다. 1. bounding_box & bitmap: SegmentBox & np.ndarray 2. contours: Sequence[np.ndarray]
Segment 오브젝트를 생성하기 위해서는 1가지 표현의 데이터만 필요하고, 다른 표현이 필요한 연산의 경우 lazy 한 방식으로 해당 표현을 계산합니다.
Segment 오브젝트 생성 시 bounding_box, bitmap 과 contours가 모두 주어진 경우, 서로 일치하는지 확인하지 않습니다.
Segment 오브젝트 생성 시 bounding_box, bitmap 표현이 주어진 경우 모든 픽셀이 연결되어 있는지 확인하지 않습니다.
Parameters:
-
bounding_box(Optional[SegmentBox], default:None) –description. Defaults to None.
-
bitmap(Optional[Bitmap], default:None) –description. Defaults to None.
-
contours(Optional[Contours], default:None) –description. Defaults to None.
-
class_index(Optional[int], default:None) –description. Defaults to None.
Source code in SaigeToolkit/data/dataclass/segment.py
from_xyhw_and_bitmap
classmethod
from_xyhw_and_bitmap(bounding_box: List[int], bitmap: Bitmap, class_index: Optional[int] = None, contours: Optional[Contours] = None, **ignore) -> Segment
Source code in SaigeToolkit/data/dataclass/segment.py
from_any
classmethod
Source code in SaigeToolkit/data/dataclass/segment.py
get_bounding_box_from_contours
get_bounding_box_from_contours(contours: Contours) -> SegmentBox
contours의 bounding box를 구합니다.
convert_contours_to_box_and_bitmap
convert_contours_to_box_and_bitmap(contours: Contours, bounding_box: Optional[SegmentBox] = None) -> Tuple[SegmentBox, Bitmap]
contours를 bounding_box 와 bitmap representation으로 변환합니다
Source code in SaigeToolkit/data/dataclass/segment.py
convert_box_and_bitmap_to_contours
convert_box_and_bitmap_to_contours(bitmap: Bitmap, bounding_box: Optional[SegmentBox] = None) -> Contours
bounding_box 와 bitmap을 contours representation으로 변환합니다
Source code in SaigeToolkit/data/dataclass/segment.py
compute_box_intersection
compute_box_intersection(box1: SegmentBox, box2: SegmentBox) -> Optional[SegmentBox]
intersecting box를 계산합니다. 겹치지 않는 경우 None
Source code in SaigeToolkit/data/dataclass/segment.py
to_segments
List[Union[Segment, Dict]]를을 List[Segment]들로 변환합니다
merge_segments
여러 Segment들을 하나의 Segment로 합칩니다. (union)
Source code in SaigeToolkit/data/dataclass/segment.py
compute_contours_area_exact
compute_contours_area_exact(contours: Contours) -> int
bounding box 크기의 이미지에 contour를 그린 뒤 픽셀 개수 카운트
compute_contours_area_fast
compute_contours_area_fast(contours: Contours) -> int
cv2.contourArea() 로 contour 면적 계산: contour 테두리를 0.5 픽셀 제외하고 계산되는 듯. average error: 17.08%
Source code in SaigeToolkit/data/dataclass/segment.py
compute_contours_area_fast_plus
compute_contours_area_fast_plus(contours: Contours) -> int
cv2.contourArea() 로 contour 면적 계산, outer의 경우 cv2.arcLength() 더해줌 average error: 1.50%
Source code in SaigeToolkit/data/dataclass/segment.py
compute_contours_area_fast_plusplus
compute_contours_area_fast_plusplus(contours: Contours) -> int
cv2.contourArea() + cv2.arcLength() 로 contour 면적 계산 average error: 1.58%
Source code in SaigeToolkit/data/dataclass/segment.py
compute_contours_area
compute_contours_area(contours: Contours, method: str) -> int
contours의 면적을 계산합니다. 참고: https://www.notion.so/65e5a56b2b8744bea087b1a0d2f9bfbf
Source code in SaigeToolkit/data/dataclass/segment.py
compute_segment_intersection_area
두 Segment 사이의 겹치는 영역 넓이를 계산합니다. bounding_box를 이용해 겹치는 박스를 먼저 계산한 뒤 해당 박스만 잘라서 겹치는 픽셀 수를 셉니다.
Source code in SaigeToolkit/data/dataclass/segment.py
compute_segment_score
compute_segment_score(segment: Segment, scoremap: ndarray, method: str = 'mean', return_float: bool = False) -> Union[float, int]
scoremap 중 segment 영역의 score를 대표하는 값을 계산합니다.
Source code in SaigeToolkit/data/dataclass/segment.py
compute_segment_properties_and_apply_threshold
compute_segment_properties_and_apply_threshold(segment: Segment, calc_area_and_apply_threshold: bool = False, area_method: str = 'fast_plus', area_threshold: int = 0, calc_score_and_apply_threshold: bool = False, scoremap: Optional[ndarray] = None, score_method: str = 'mean', score_threshold: Union[float, int] = 0, score_as_float: bool = False) -> Optional[Dict]
API 계산 결과로 필요한 Segment의 property 들을 계산하고 threshold를 적용합니다. threshold에 걸리지 않는 경우 각 property들의 Dict를, threshold 에 걸리는 경우 None을 리턴합니다. 계산 로직은 다음과 순서로 적용됩니다.
calc_object_area_and_apply_threshold=True인 경우- area 계산
- area_threshold 적용
calc_object_score_and_apply_threshold=True인 경우- score 계산
- score_threshold 적용
- 아래 항목들 계산
- bounding_box
- bounding_rotated_box
- fitted_ellipse
Parameters:
-
segment(Segment) –segment
Returns:
-
Optional[Dict]–Optional[Dict]: segment property dictionary. threshold에 걸려서 필터링 된 경우 None
Source code in SaigeToolkit/data/dataclass/segment.py
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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 | |
scale_segments_properties
scale_segment_properties
Source code in SaigeToolkit/data/dataclass/segment.py
translate_segments_properties
translate_segments_properties(segments_properties: List[Dict], left: int, top: int, **kwargs) -> List[Dict]
Source code in SaigeToolkit/data/dataclass/segment.py
translate_segment_properties
Source code in SaigeToolkit/data/dataclass/segment.py
dataset
커스텀 데이터셋 구현과 각종 데이터 로드 메서드를 제공합니다.
모든 데이터셋 구현은 SaigeDataset 클래스를 상속받아야 합니다.
base_dataset
모든 데이터셋 구현에 사용되는 기본 클래스를 정의합니다.
DummyAttribute
ABCMeta
Bases: ABCMeta
"abstract_attribute" from:\ https://stackoverflow.com/questions/23831510/abstract-attribute-not-property/50381071#50381071
__call__
Source code in SaigeToolkit/data/dataset/base_dataset.py
SaigeDataset
SaigeDataset(crop: Optional[dict] = None, transform: Optional[dict] = None, collate: Optional[Callable[[List[dict]], dict]] = None, device: device = torch.device('cpu'), **neglect: dict)
Bases: Dataset
Saige's basic dataset class.
Attributes:
-
crop_fn(Optional[Callable[[dict], List[dict]]) –function cropping image data into image patch data.
-
transform(Type[Transform]) –transform class for transforming to a single image data.
-
to_tensor(Callable[[Union[Image.Image, np.ndarray], torch.Tensor]) –data returning as Tensor type
-
n_patch(int) –number of patches when crop_fn is used.
-
collate_function(Callable[[List[dict]], dict]) –function list of data collating into one batch data
initializing Saige base dataset.
Parameters:
-
crop(Optional[dict], default:None) –config for crop function. Defaults to None.
-
transform(Optional[dict], default:None) –config for transforming to a single raw data
-
collate(Optional[Callable[[List[dict]], dict]], default:None) –list of data collating into one batch data. if None, torch.utils basic collate function would be used. Defaults to None.
-
device(device, default:device('cpu')) –gpu device
Source code in SaigeToolkit/data/dataset/base_dataset.py
collate_function
instance-attribute
collate_function = {'resize': resize_collate, 'padding': padding_collate}[collate]
__len__
data_on_memory
To store data in RAM memory (faster data loading),
put all loaded data ( use self.load_raw_data() ) in list self.data_on_memory.
Or define self.data_on_memory as empty list to load data from filesystem everytime.
Source code in SaigeToolkit/data/dataset/base_dataset.py
stack_data_on_memory
Stack all data on RAM memory for quick-loading purpose. output would be saved on class attribute.
Returns:
-
List[dict]–List[dict]: Entire data list-dict.
Source code in SaigeToolkit/data/dataset/base_dataset.py
load_raw_data
load_image
Source code in SaigeToolkit/data/dataset/base_dataset.py
load_label
abstractmethod
__getitem__
dataset default getitem function. data is first loaded, then processed as following order: resize, augmentation, transform to torch.Tensor. data could be loaded from file_system (load_raw_data) or RAM memory (data_on_memory).
Parameters:
-
index(int) –data item index.
Returns:
-
Union[dict, List[dict]]–Union[dict, List[dict]]: single data, or cropped data list when crop_fn exists.
Source code in SaigeToolkit/data/dataset/base_dataset.py
process_data
data processing after raw loading.
- resize: Resize Image and Label
- btw_resize_aug: Dummy function for user customization
- augmentation: Process augmentation defined in util/augmentation
- btw_aug_transform: Dummy function for user customization
- to_tensor: Transform data to torch tensor
Parameters:
-
data(dict) –raw data dict
Returns:
-
dict(dict) –processed data dict
Source code in SaigeToolkit/data/dataset/base_dataset.py
to_tensor
to_tensor items in data into torch.Tensor (if convertible)
Parameters:
-
data(dict, default:{}) –raw data dict
Returns:
-
dict(dict) –tensorized data dict
Source code in SaigeToolkit/data/dataset/base_dataset.py
resize_collate
Example collate function with resizing items.
Parameters:
-
batch(List[dict]) –list of data dicts
Returns:
-
dict(dict) –resized-and-collated data dict
Source code in SaigeToolkit/data/dataset/base_dataset.py
padding_collate
Example collate function with padding items.
Parameters:
-
batch(List[dict]) –list of data dicts
Returns:
-
dict(dict) –padded-and-collated data dict
Source code in SaigeToolkit/data/dataset/base_dataset.py
calculate_patch_number
When crop_fn is activated, calculate number of text patches.
Parameters:
-
files(Optional[List[dict]], default:None) –list of meta data dict. if None, calculate patch_number from self.files attribute. Defaults to None.
Returns:
-
int(int) –number of patches in meta data list
files
Source code in SaigeToolkit/data/dataset/base_dataset.py
builder
build_dataset
build_dataset(_target_, **cfg_dataset: dict) -> SaigeDataset
build dataset from config["dataset"]
Parameters:
-
cfg_dataset(dict, default:{}) –config dict for building dataset
Returns:
-
SaigeDataset(SaigeDataset) –dataset object
Source code in SaigeToolkit/data/dataset/builder.py
platform_reader
request_vision_projects
Data platform으로부터 project 정보들을 가져옵니다.
Parameters:
-
ip(str) –API서버에 접근하기 위한 IP 주소입니다.
-
port(int) –API서버에 접근하기 위한 PORT 번호입니다.
-
project_ids(list) –project 정보를 가져오기 위한 project_id의 list입니다.
Returns:
-
List[dict]–List[dict]: project 정보를 dict형태로 저장한 list를 반환합니다.
[ { "project_id": int, "class_info": List[str], "dataset": { "train_images": { "{image_id}": { "path": str, "width": int, "height": int, "client": str, # Dataset metadata "end_user": str, # Dataset metadata "domain": str, # Dataset metadata "class_index": int, # CLS only have this key "labels" : [ # DET, SEG only have this key { "class_index": int, "bounding_box": List[int], # DET only have this key "contours": List[List[int]] # SEG only have this key }, ..., # times number of labels ] }, ..., # times number of images }, "validation_images": {...}, "Not split: {...} } }, ..., # times number of projects ]
Source code in SaigeToolkit/data/dataset/platform_reader.py
saige_vision_reader
load_labels
Source code in SaigeToolkit/data/dataset/saige_vision_reader.py
load_label_cls
load_label_iad
load_label_det
박스 별 dict를 concat 되어있는 bboxes, labels, scores로 변환합니다.
Source code in SaigeToolkit/data/dataset/saige_vision_reader.py
load_label_seg
Source code in SaigeToolkit/data/dataset/saige_vision_reader.py
load_label_ocr
Source code in SaigeToolkit/data/dataset/saige_vision_reader.py
srproj_dataset
SrprojDataset
SrprojDataset(code: Union[str, List[Union[str, dict]]], mode: Optional[str] = None, two_class: bool = False, split: str = 'Training', preload_data_on_memory: bool = False, srproj_params: Optional[dict] = None, **cfg_dataset: dict)
Bases: SaigeDataset
Dataset class with building data from srproj file. Basic structure of dataset class is defined in SaigeDataset. SrprojDataset class only defines data loading from srproj file.
Attributes:
-
files(List[dict]) –meta_data dict list from srproj file.
-
n_classes(int) –number of classes of data. fix to 2 if two_class mode is on.
-
classes(List[str]) –list of class names for each class index. meta_data: only contains information about
how to load data -
n_patch(int) –number of patches when crop_fn is used.
-
data_on_memory(List[dict]) –list of loaded data dicts if
preload_data_on_memoryis activated
initializing SrprojDataset
Parameters:
-
code(Union[str, List[Union[str, dict]]]) –dataset code(s) with srproj params. 여러 srproj를 사용하는 경우, 각 srproj_param을 dictionary 형태로 추가할 수 있습니다. 이 경우, "srproj_params" 파라미터를 각자의 srproj_param으로 업데이트 하여 사용합니다.
-
mode(Optional[str], default:None) –data label type. Defaults to None.
-
two_class(bool, default:False) –two_class mode selector. Defaults to False.
-
split(str, default:'Training') –["Training", "Validation"]. Defaults to "Training".
-
preload_data_on_memory(bool, default:False) –whether pre-load all data and save on RAM memory. Defaults to False.
-
srproj_params(dict, default:None) –read_srproj함수에 전달하는 추가적인 파라미터들 입니다. 현재는 이미지 경로 핸들링을 위한 파라미터들이 있으며, 지속적으로 추가될 수 있습니다. -
cfg_dataset(dict, default:{}) –config dicts for mother class
Source code in SaigeToolkit/data/dataset/srproj_dataset.py
data_on_memory
instance-attribute
load_label
load label data from file-system
Parameters:
-
file(dict) –meta data dict
Returns:
-
dict(dict) –label data as dict
Source code in SaigeToolkit/data/dataset/srproj_dataset.py
srproj_reader
path_interpreter
data path interpreter
Parameters:
-
code(str) –dataset code (rule: {domain}-{source}-{category}) (ex) sample dataset for cls: "test_directory-sample-cls")
Raises:
-
RuntimeError–invalid classifier keys (code) for srproj code.
-
Exception–wrong type of input code
Returns:
-
Tuple[str, str, str, str]–Tuple[str, str, str, str]: absolute path for dataset, domain, source, category
Source code in SaigeToolkit/data/dataset/srproj_reader.py
read_srproj
read_srproj(code: str, split: str, two_class: bool = False, mode: Optional[str] = None, use_absolute_path: bool = False, srproj_image_directory: Optional[str] = None, system_image_directory: Optional[str] = None, get_class_colors: bool = False, skip_problematic_files: bool = False) -> Tuple[List[Dict], int, Union[List[str], List[Dict]]]
read srproj dataset from file-system.
Parameters:
-
code(str) –dataset code.
-
split(str) –split dataset, "Training" or "Validation".
-
two_class(bool, default:False) –load data as two class mode (ex) normal <-> abnormal)
-
mode(Optional[str], default:None) –select data label type.
-
use_absolute_path(bool, default:False) –use the image path in srproj as is.
-
srproj_image_directory(Optional[str], default:None) –srproj 파일에 작성된 이미지 경로를 현재 시스템 상의 이미지 경로로 변환하기 위해 치환해야 하는 이미지 폴더 경로. None이면 SaigeDatabase 규칙 사용.
-
system_image_directory(Optional[str], default:None) –코드가 구동되는 시스템 상의 이미지 폴더 경로. None이면 SaigeDatabase 규칙 사용.
-
get_class_colors(bool)–srproj에 정의된 각 클래스의 color를 받을지 여부. True이면
-
skip_problematic_files(bool)–srproj 파일에 작성된 이미지 경로로부터 이미지들을 읽을 때, 해당 파라미터가 True 라면, 파일이 실제 존재하지 않거나, 읽다가 문제가 발생할 경우 해당 파일을 제외하고 나머지 파일을 계속 읽음. 만약, False라면 Error를 raise 함.
Returns:
-
Tuple[List[Dict], int, Union[List[str], List[Dict]]]–Tuple[List[Dict], int, Union[List[str], List[Dict]]]: list of meta data dicts, number of classes, and list of class names or dict
Note
.sproj 파일에는 각 이미지들의 경로와 라벨 정보 등이 포함되어 있습니다.
이때 이미지 경로는 해당 파일을 생성한 PC 기준의 절대 경로로 작성되어 있기 때문에, 현재 이 코드가 실행되는 시스템에서의 경로로 변환해 주어야 합니다.
현재 이미지 경로 변환 옵션은 3가지가 존재합니다.
1. sproj를 생성한 PC에서 코드를 실행하는 경우,
use_absolute_path= True로 세팅하면 srproj에 작성된 이미지 경로를 그대로 사용합니다.
2. 이미지와 srproj가 SaigeDatabase 룰에 맞게 구성된 경우,
이미지는 images 폴더에 하위에 있고 (root/images/.../xxx.png)
srproj는 images 폴더보다 한 단계 아래 경로에 있어야 합니다 (root/projects/xxx.srproj)
이때는srproj_image_directory= None,system_image_directory= None 으로 설정합니다.
3. 이미지와 srproj가 SaigeDatabase 룰을 따르지 않는 경우,srproj_image_directory와system_image_directory`를 설정하면
srproj에 작성된 이미지 경로를 다음 규칙으로 변환합니다:
{srproj_image_directory}/.../xxx.png -> {system_image_directory}/.../xxx.png
Source code in SaigeToolkit/data/dataset/srproj_reader.py
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 | |
check_label
check all data label is valid. If any data is corrupted, pop out from meta data list.
Parameters:
-
files(List[Dict]) –meta data list to be checked
-
mode(str) –label data type
Returns:
-
List[Dict]–List[Dict]: cleaned meta data list
Source code in SaigeToolkit/data/dataset/srproj_reader.py
load_srproj_label
load single data dict from srproj meta data.
Parameters:
-
file(Dict) –single meta data dict
-
use_crop_fn(bool, default:False) –Whether to use the crop function. Defaults to False.
Raises:
-
NotImplementedError–only four modes are available. ["Classification", "Detection", "Segmentation", "OpticalCharacterRecognition"]
Returns:
-
Dict(Dict) –label data as dict
Source code in SaigeToolkit/data/dataset/srproj_reader.py
load_label_cls
load_label_det
load detection label
Parameters:
-
file(Dict) –meta data for detection label
Returns:
-
Dict(Dict) –
Source code in SaigeToolkit/data/dataset/srproj_reader.py
load_label_seg
load segmentation label
Parameters:
-
file(Dict) –meta data for segmentation label
-
return_polygon(bool, default:True) –whether return polygon data. Defaults to True.
-
mask_to_pil(bool, default:False) –whether return mask as PIL.Image. Defaults to False.
Returns:
-
Dict(Dict) –segmentation label data dict
Source code in SaigeToolkit/data/dataset/srproj_reader.py
load_label_ocr
load ocr label
Parameters:
-
file(Dict) –meta data for ocr label
Returns:
-
Dict(Dict) –ocr label data dict
Source code in SaigeToolkit/data/dataset/srproj_reader.py
_refine_kie_labels
Source code in SaigeToolkit/data/dataset/srproj_reader.py
merge_srproj_classes
Source code in SaigeToolkit/data/dataset/srproj_reader.py
convert_srproj_class_color_to_rgb
srproj의 각 클래스 색 코드를 rgb 값으로 변환합니다.
process_config
process_data_config
split training/validation configs from entier data config dict. you can edit cfg by split to override some configs in cfg_data entire config example) data: code: A.srproj validation: <- code: B.srproj <- this will override base config {"code": "A.srproj"}
Parameters:
-
cfg_data(dict) –entire config
Returns:
-
Tuple[dict, dict]–Tuple[dict, dict]: training and validation configs
Source code in SaigeToolkit/data/process_config.py
sampler
Pytorch dataloader와 호환 가능한 커스텀 sampler 클래스를 제공합니다. 모든 구현은 torch.utils.data.Sampler 및 그 하위 구현의 인터페이스를 따릅니다.
builder
SAMPLER_IMPLEMENTATION
module-attribute
SAMPLER_IMPLEMENTATION = {'InfiniteRandomSampler': InfiniteRandomSampler}
build_sampler
build_sampler(_target_: Optional[str], data_source: Optional[Sized], **cfg_sampler: dict) -> Optional[Sampler]
Parameters:
-
cfg_sampler(dict, default:{}) –config dict for building sampler
Returns:
-
Optional[Sampler]–Optional[Sampler]: sampler object instance. if cfg_sampler is None, return None
Notes
Follows the interface of torch.utils.data.Sampler.
Source code in SaigeToolkit/data/sampler/builder.py
get_sampler_class
Source code in SaigeToolkit/data/sampler/builder.py
infinite_random_sampler
InfiniteRandomSampler
Bases: RandomSampler
Infinitely samples elements randomly. If without replacement, then sample from a shuffled dataset.
If with replacement, then user can specify :attr:num_samples to draw.
Parameters:
-
data_source(Dataset) –dataset to sample from
-
replacement(bool) –samples are drawn on-demand with replacement if
True, default=False -
num_samples(int) –number of samples to draw, default=
len(dataset). -
generator(Generator) –Generator used in sampling.
Assume that this DataLoader is used for training with shuffle=True.
We use InfiniteRandomSampler to make the DataLoader to infinitely sample the dataset.
This prevents the "drop_last" and the "prefeching" problem across epochs.
Be careful that you should stop the training loop by counting the number of steps manually.
The DataLoader will never stop by itself.
NOTE: Note that this sampler has infinite length and thus you should be careful when calculating the current epoch. We recommend you to use step//steps_per_epoch to calculate the current epoch.
__iter__
Source code in SaigeToolkit/data/sampler/infinite_random_sampler.py
transform
End-to-end 데이터 변환을 지원하는 Transform 클래스를 제공하는 모듈입니다.
Transfrom 클래스는 다음과 같은 순서로 transform을 적용합니다. 1. load PIL Image 2. 원본 이미지가 inspection_size_wh를 넘지 않도록 resize 했을 때의 image scale 계산 3. ROI 적용 (crop) @. roi_mask_first=True인 경우 ROI 적용 (blind mask) 4. 2번과 resize_factor를 하나로 묶어서 resize @. roi_mask_first=False인 경우 ROI 적용 (blind mask) 5. data augmentation
Note
roi_mask_first 옵션에 따라서 ROI의 blind mask를 적용하는 시점이 달라집니다. - roi_mask_first=True: ROI crop -> ROI mask -> resize - roi_mask_first=False: ROI crop -> resize -> ROI mask 일반적으로 resize 후에 mask를 적용하는 것이 더 효율적입니다.
augmentation
Data augmentation을 위한 기본 BaseTransform 클래스 및 Transform 구현, 그리고 여러 Data Transform들을 하나로 묶어서 관리해주는 기본 BaseCompose 클래스 및 Compose 구현을 제공합니다.
api
Image Augmentation Preview를 위한 API를 제공합니다.
ImageProcessor 클래스를 통해 각 augmentation들이 특정 파라미터 값에 대해 이미지를 어떻게 변형 시키는지 확인할 수 있습니다.
_APIDecorator
ImageProcessor에서 정의된 함수들을 decorate 해주는 헬퍼입니다.
staticmethod 와 decorator를 함께 사용할 경우 Cythonize시 제대로 동작하지 않는 이슈를 해결하기 위한 패치입니다. 참고: https://github.com/cython/cython/issues/1434
ImageProcessor의 각 함수에 다음과 같은 decorator를 씌우는 것과 동일한 역할을 합니다.
@staticmethod
@error_handler
@support_multi_image
@support_3dim_gray_image
def image_processor_function(image: np.ndarray, ...):
...
__init_subclass__
Source code in SaigeToolkit/data/transform/augmentation/api.py
support_3dim_gray_image
staticmethod
Source code in SaigeToolkit/data/transform/augmentation/api.py
support_multi_image
staticmethod
Source code in SaigeToolkit/data/transform/augmentation/api.py
ImageProcessor
Bases: _APIDecorator
Image Augmentation Preview를 위한 API 입니다. 각 augmentation들이 특정 파라미터 값에 대해 이미지를 어떻게 변형 시키는지 확인할 수 있습니다.
Note1
일반적으로 학습 시에는 파라미터를 특정 값이 아닌 범위로 설정하여 해당 범위에서 매번 랜덤한 값을 선택해 이미지에 적용합니다.
따라서 preview API의 입력 파라미터와 학습 시 넘겨주는 파라미터는 대부분 값 vs 범위의 차이를 가지게 됩니다.
예를 들어 preview API에서 rotate의 경우 angle (float) 값을 받지만, 학습 config에서는 angle_limit (List[float]) 범위를 받게됩니다.
각 augmentation을 학습에 사용시 필요한 config는 각 함수 설명의 Trainer Config 섹션을 참고하세요.
Note2
API 기획상, augmentation의 실제 자유도보다, 유저가 설정할 수 있는 파라미터가 적은 경우가 있습니다. (각 변 혹은 꼭짓점 마다 독립적으로 적용되는 ratio_jitter나 perspective_transform의 경우) 이러한 augmentation들은 api 호출 시, '값'을 입력 받아서, 이 '값'으로 부터 정의된 '범위'에서 필요한 값들을 랜덤하게 샘플링하게 됩니다. 이러한 augmentation들의 preview 함수를 정의할 때는, 인풋에 fixed_aug_params를 받을 수 있도록 해주어야합니다. (ImageProcessor.ratio_jitter 참고)
Usage
rotate augmentation preview 예제입니다. 상세 설명은 각 함수 설명 참고.
vertical_flip
image를 상하로 뒤집습니다.
Parameters:
-
image(ndarray) –
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Source code in SaigeToolkit/data/transform/augmentation/api.py
horizontal_flip
image를 좌우로 뒤집습니다.
Parameters:
-
image(ndarray) –
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Source code in SaigeToolkit/data/transform/augmentation/api.py
rotate
image를 angle만큼 회전시킵니다.
Parameters:
-
image(ndarray) – -
angle(float, default:0.0) –회전하는 각도 입니다. 유효 범위는 다음과 같습니다. [-360.0, 360.0]. Defaults to 0.0.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Source code in SaigeToolkit/data/transform/augmentation/api.py
random_rotate90
image를 [0, 90, 180, 270] 중 랜덤한 각도만큼 회전시킵니다.
NOTE
- 모든 이미지 픽셀은 유지되며, 회전 후 이미지 크기가 변경될 수 있습니다.
- 예시: factor가 1일 경우 90도 회전하며, 이미지 사이즈는 (W, H) -> (H, W)로 변경됩니다.
Parameters:
-
image(ndarray) – -
factor(int, default:0) –회전하는 각도 입니다. factor에 90을 곱한 값만큼 회전합니다. (ex. factor가 1일 경우 90도) 유효범위는 다음과 같습니다 [0, 3]. Defaults to 0.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Source code in SaigeToolkit/data/transform/augmentation/api.py
color_jitter
color_jitter(image: ndarray, brightness: float = 1.0, contrast: float = 1.0, saturation: float = 1.0, hue: float = 0.0) -> Tuple[ndarray, None]
image의 밝기 (brightness), 대비 (contrast), 채도 (saturation), 색상 (hue)을 변경합니다.
Parameters:
-
image(ndarray) – -
brightness(float, default:1.0) –밝기를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [0.01, 10.00]. Defaults to 1.0.
-
contrast(float, default:1.0) –대비를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [0.01, 10.00]. Defaults to 1.0.
-
saturation(float, default:1.0) –채도를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [0.01, 10.00]. Defaults to 1.0.
-
hue(float, default:0.0) –색상을 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [-0.50, 0.50]. Defaults to 0.0.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Example
Trainer Config
Source code in SaigeToolkit/data/transform/augmentation/api.py
blur
image에 averaging blur를 적용합니다.
Parameters:
-
image(ndarray) – -
ksize(int, default:1) –blur kernel의 크기 입니다. 유효 범위는 다음과 같습니다. [1, 100]. Defaults to 1.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Source code in SaigeToolkit/data/transform/augmentation/api.py
gaussian_blur
image에 gaussian blur를 적용합니다.
Parameters:
-
image(ndarray) – -
ksize(int, default:1) –blur kernel의 크기 입니다. 유효 범위는 다음과 같습니다. [1, 100]. Defaults to 1.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Source code in SaigeToolkit/data/transform/augmentation/api.py
adjust_brightness
image의 밝기 (brightness)를 변경합니다.
Parameters:
-
image(ndarray) – -
brightness(float, default:0.0) –밝기를 변화 강도입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Trainer Config
Source code in SaigeToolkit/data/transform/augmentation/api.py
adjust_contrast
image의 대비 (contrast)를 변경합니다.
Parameters:
-
image(ndarray) – -
contrast(float, default:0.0) –대비 변화 강도입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Trainer Config
Source code in SaigeToolkit/data/transform/augmentation/api.py
adjust_hue
image의 색조 (hue)를 변경합니다.
Parameters:
-
image(ndarray) – -
hue(float, default:0.0) –색조 변화 강도입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Source code in SaigeToolkit/data/transform/augmentation/api.py
adjust_saturation
image의 채도 (saturation)를 변경합니다.
Parameters:
-
image(ndarray) – -
saturation(float, default:0.0) –채도 변화 강도입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Trainer Config
Source code in SaigeToolkit/data/transform/augmentation/api.py
adjust_gamma
image의 gamma를 조절하여 밝기를 변화시킵니다.
Parameters:
-
image(ndarray) – -
gamma(float, default:0.0) –조절할 gamma value 입니다. 유효 범위는 다음과 같습니다. [-1.0, 1.0]. Defaults to 0.0.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Source code in SaigeToolkit/data/transform/augmentation/api.py
adjust_brightness_contrast
adjust_brightness_contrast(image: ndarray, brightness: float = 0.0, contrast: float = 0.0) -> Tuple[ndarray, None]
image의 밝기 (brightness), 대비 (contrast)를 변경합니다.
Parameters:
-
image(ndarray) – -
brightness(float, default:0.0) –밝기를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.
-
contrast(float, default:0.0) –대비를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Example
Trainer Config
Source code in SaigeToolkit/data/transform/augmentation/api.py
iso_noise
Apply camera sensor noise.
Parameters:
-
image(ndarray) – -
color_shift(float, default:0.0) –variance range for color hue change. Measured as a fraction of 360 degree Hue angle in HLS colorspace. 유효 범위는 다음과 같습니다. [0.00, 1.00]. Defaults to 0.0.
-
intensity(float, default:0.0) –Multiplicative factor that control strength of color and luminace noise. 유효 범위는 다음과 같습니다. [0.00, 2.00]. Defaults to 0.0.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Example
Trainer Config
Source code in SaigeToolkit/data/transform/augmentation/api.py
ratio_jitter
ratio_jitter(image: ndarray, proportion: Optional[int] = 0, fixed_aug_params: Optional[Dict] = None) -> Tuple[ndarray, Dict]
image에 random하게 padding과 crop을 한 뒤, 원래 size로 resize 하는 과정을 통해 image의 가로 세로 비율을 변경합니다. NOTE: 프리뷰에서는 네변에 각각 [0, proportion] 범위에서 crop 혹은 padding한 예시를 보여줍니다.
Parameters:
-
image(ndarray) – -
proportion(int, default:0) –padding 혹은 crop을 할 비율(단위: 백분율)입니다. 유효 범위는 다음과 같습니다. [0, 50]. Defaults to 0. (
fixed_aug_params=None일 때만 작동합니다.) -
fixed_aug_params(Dict, default:None) –각 변에 대해서 고정된 crop 혹은 padding을 직접 정해주고자 할 때 사용합니다.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
Dict(Dict) –
각 변에 대해 crop 혹은 padding할 비율을 직접 설정
각 변에 [-proportion, proportion] 범위에서 랜덤하게 crop 혹은 padding 적용
Source code in SaigeToolkit/data/transform/augmentation/api.py
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 | |
zoom
image에 zoom in/out 효과를 줍니다.
Parameters:
-
image(ndarray) – -
ratio(float, default:1.0) –zoom in/out 할 비율입니다. 1보다 크면 zoom in을 1보다 작으면 zoom out을 합니다. 유효 범위는 다음과 같습니다. [0.01, 100.00]. Defaults to 1.0.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Source code in SaigeToolkit/data/transform/augmentation/api.py
random_resized_crop_and_pad
random_resized_crop_and_pad(image: ndarray, scale: float = 1.0, aspect_ratio: float = 1.0, height: Optional[int] = None, width: Optional[int] = None) -> Tuple[ndarray, None]
원본 image의 scale 비율의 면적을 가지면서 가로 세로 비가 aspect_ratio인 image를 random하게 crop 한 뒤, (crop image가 원본 image 보다 커지는 경우 padding을 통해 해결합니다.) 크기가 (height, width)가 되도록 resize를 합니다.
Parameters:
-
image(ndarray) – -
scale(float, default:1.0) –crop할 image의 면적을 나타내는 값입니다. 실제 면적은 [원본 이미지의 면적 * scale] 입니다. 유효 범위는 다음과 같습니다. [0.01, 1.00]. Defaults to 1.0.
-
aspect_ratio(float, default:1.0) –crop할 image의 가로 세로 비를 나타내는 값입니다. 유효 범위는 다음과 같습니다. [0.10, 10.00]. Defaults to 1.0.
-
height(int, default:None) –crop image를 resize할 height 입니다. None인 경우 입력 이미지의 원본 height를 사용합니다.
-
width(int, default:None) –crop image를 resize할 width 입니다. None인 경우 입력 이미지의 원본 width를 사용합니다.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Example
Trainer Config
{
"_target_": "random_resized_crop_and_pad",
"scale_limit": List[float], # scale 최소 최대 범위
"aspect_ratio_limit": List[float], # aspect_ratio 최소 최대 범위
"height": Optional[int], # crop 후 resize할 이미지 height (None인 경우 원본 height 사용)
"width": Optional[int], # crop 후 resize할 이미지 width (None인 경우 원본 width 사용)
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
light_reflect
image에 원형 빛을 비춘 것 같은 효과를 줍니다.
Parameters:
-
image(ndarray) – -
radius(float, default:0.0) –원형 빛의 반지름 크기 입니다. 유효 범위는 다음과 같습니다. [0.00, 1.00]. Defaults to 0.0.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
NoneType(None) –None
Source code in SaigeToolkit/data/transform/augmentation/api.py
perspective_transform
perspective_transform(image: ndarray, intensity: Optional[int] = 0, fixed_aug_params: Optional[Dict] = None) -> Tuple[ndarray, Dict]
이미지를 투영 변환(Perspective Transform)합니다. image를 다른 각도(시점)에서 바라본 형태로 변환합니다. Perspective Transform 을 위한 네개의 도착점의 좌표 (offset)은 다음과 같이 샘플링됩니다. offset_top_left: 원본 이미지의 좌측 상단 모서리를 얼마만큼 중심부로 이동시킬 지에 대한 실수 값이 들어있습니다. 즉, Perspective Transform 의 좌측 상단점의 도착점은 아래와 같이 계산할 수 있습니다.
```
x` = 0 + width * offset_top_left[0]
y` = 0 + height * offset_top_left[1]
point_dst = (x`, y`)
```
offset_bottom_right
offset_top_left 와 동일하되 우측 하단 점을 나타냅니다.
Perspective Transform 의 우측 하단점의 도착점은 아래와 같이 계산할 수 있습니다.
offset_top_right: offset_top_left 와 동일하되 우측 상단 점을 나타냅니다.
offset_bottom_left: offset_top_left 와 동일하되 좌측 하단 점을 나타냅니다.
Parameters:
-
image(ndarray) – -
intensity(int, default:0) –perspective transform 을 적용 강도(단위: 백분율)입니다. intensity 범위 내에서 랜덤한 값으로 샘플된 네개의 offset 을 이용해 perspective transform 을 수행합니다. 유효 범위는 [0, 49] 로, 각 도착지 점들은 이미지의 중간 선을 지나칠 수 없습니다. 이를 통해 이미지가 반전되는 정도의 왜곡을 방지합니다. Defaults to 0. (
fixed_aug_params=None일 때만 작동합니다.) -
fixed_aug_params(Dict, default:None) –각 꼭짓점에 대해서 offset 비율을 직접 정해주고자 할 때 사용합니다.
Returns:
-
ndarray–np.ndarray: augmentation이 적용된 image 입니다.
-
Dict(Dict) –
각 꼭짓점의 offset 비율을 직접 설정
각 꼭짓점에 [0, intensity] 범위에서 랜덤하게 offset 비율을 적용
Trainer Config
Source code in SaigeToolkit/data/transform/augmentation/api.py
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 | |
augment_function
INTERPOLATE_METHOD_CV2
module-attribute
vertical_flip
horizontal_flip
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
rotate
rotate(image: Union[ImageType, MaskType], angle: float = 0, interpolation: int = cv2.INTER_LINEAR, border_mode: int = cv2.BORDER_REFLECT_101, value: Union[int, float, List[int], List[float]] = 0, crop_border: bool = False) -> Union[ImageType, MaskType]
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
random_rotate90
color_jitter
color_jitter(image: ImageType, brightness: float = 1.0, contrast: float = 1.0, saturation: float = 1.0, hue: float = 0, order: List[int] = [0, 1, 2, 3]) -> ImageType
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
blur
gaussian_blur
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
adjust_gamma
adjust_brightness_contrast
adjust_brightness_contrast(image: ImageType, brightness: float = 0.0, contrast: float = 0.0, brightness_by_max: bool = True) -> ImageType
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
adjust_brightness
adjust_brightness(image: ImageType, brightness: float = 0.0, brightness_by_max: bool = True) -> ImageType
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
adjust_contrast
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
adjust_hue
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
adjust_saturation
adjust_saturation
Parameters:
-
image(ImageType) –입력 이미지
-
saturation(float, default:0.0) –변형 강도, [-1.0, 1.0] 범위, Defaults to 0.0.
Returns:
-
ImageType(ImageType) –결과 이미지
Note
Ablumentation의 AF.shift_hsv()와 다른 알고리즘을 사용합니다. AF.shift_hsv()의 경우 색이 없는 픽셀을 붉은 색으로 변형합니다. 이 함수의 경우 색이 없는 픽셀은 변형하지 않습니다.
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
iso_noise
iso_noise(image: ImageType, color_shift: float = 0.05, intensity: float = 0.5, random_state: Optional[int] = None) -> ImageType
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
image_compression
sharpen
multiplicative_noise
ratio_jitter
ratio_jitter(image: ImageType, proportion_left: float = 0.0, proportion_right: float = 0.0, proportion_top: float = 0.0, proportion_bottom: float = 0.0, resampling: str = 'bilinear', border_mode: int = cv2.BORDER_CONSTANT, value: Union[int, float, List[int], List[float]] = 0) -> Union[ImageType, MaskType]
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
_zoom_in
_zoom_in(image: ImageType, ratio: float = 1.0, h_start: float = 0.0, w_start: float = 0.0, resampling: str = 'bilinear') -> Union[ImageType, MaskType]
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
_zoom_out
_zoom_out(image: ImageType, ratio: float = 1.0, h_start: float = 0.0, w_start: float = 0.0, resampling: str = 'bilinear', border_mode: int = cv2.BORDER_CONSTANT, value: Union[int, float, List[int], List[float]] = 0) -> Union[ImageType, MaskType]
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
zoom
zoom(image: ImageType, ratio: float = 1.0, h_start: float = 0.0, w_start: float = 0.0, resampling: str = 'bilinear', border_mode: int = cv2.BORDER_CONSTANT, value: Union[int, float, List[int], List[float]] = 0) -> Union[ImageType, MaskType]
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
random_resized_crop
random_resized_crop(image: ImageType, h_scale: float = 1.0, w_scale: float = 1.0, h_start: float = 0.0, w_start: float = 0.0, resampling: str = 'bilinear') -> Union[ImageType, MaskType]
Crop the given image to given scale and then resize it to original size.
Parameters:
-
image(ImageType) –original image
-
h_scale(float, default:1.0) –crop height scale. Defaults to 1.0.
-
w_scale(float, default:1.0) –crop width scale. Defaults to 1.0.
-
h_start(float, default:0.0) –crop height start ratio. Defaults to 0.0.
-
w_start(float, default:0.0) –crop width start ratio. Defaults to 0.0.
-
resampling(str, default:'bilinear') –interpolation method. Defaults to "bilinear".
Returns:
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
random_resized_crop_and_pad
random_resized_crop_and_pad(image: ImageType, scale: float = 1.0, aspect_ratio: float = 1.0, h_start: float = 0.0, w_start: float = 0.0, height: Optional[int] = None, width: Optional[int] = None, resampling: str = 'bilinear', border_mode: int = cv2.BORDER_CONSTANT, value: Union[int, float, List[int], List[float]] = 0) -> Union[ImageType, MaskType]
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
light_reflect
light_reflect(image: ImageType, xc: float, yc: float, x_radius: float, y_radius: float, angle: float) -> ImageType
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
perspective_transform
perspective_transform(image: ImageType, offset_top_left: OffsetType, offset_top_right: OffsetType, offset_bottom_right: OffsetType, offset_bottom_left: OffsetType, interpolate_method: str = 'nearest')
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
calculate_transform_matrix
calculate_transform_matrix(width: int, height: int, offset_top_left: OffsetType, offset_top_right: OffsetType, offset_bottom_right: OffsetType, offset_bottom_left: OffsetType) -> ndarray
Calculates the perspective transformation matrix using the given width, height, and corner points of a rectangle.
Parameters:
-
width(int) –Width of the original image.
-
height(int) –Height of the original image.
-
offset_top_left(OffsetType) – -
offset_bottom_right(OffsetType) – -
offset_top_right(OffsetType) –The offset ratio of the top-left corner point.
-
offset_bottom_left(OffsetType) –The offset ratio of the bottom-left corner point.
Returns:
-
ndarray–np.ndarray: The 4x3 perspective transform matrix.
Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
erase
erase(image: ImageType, x: int, y: int, w: int, h: int, v: ndarray)
augment_transform
Implement ImageTransform classes for image augmentation.
ImageTransform
Bases: BaseTransform
Image와 라벨에 적용되는 Transform 입니다.
Source code in SaigeToolkit/data/transform/augmentation/base_transform.py
apply_to_image
apply_to_mask
apply_to_bboxes
apply_to_bboxes(bboxes: BBoxesType, **params) -> BBoxesType
apply_to_polygons
apply_to_polygons(polygons: PolygonType, **params) -> PolygonType
ImageSizeParams
get_params_from_data
get_params_from_data(data_for_params: ParamsType) -> ParamsType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
ToNumpy
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/base_transform.py
apply_to_image
ToPil
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/base_transform.py
apply_to_image
VerticalFlip
Bases: ImageSizeParams, ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/base_transform.py
apply_to_image
apply_to_mask
apply_to_bboxes
apply_to_bboxes(bboxes: BBoxesType, image_size: Tuple[int], **params) -> BBoxesType
apply_to_polygons
apply_to_polygons(polygons: PolygonType, image_size: Tuple[int], **params) -> PolygonType
HorizontalFlip
Bases: ImageSizeParams, ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/base_transform.py
apply_to_image
apply_to_mask
apply_to_bboxes
apply_to_bboxes(bboxes: BBoxesType, image_size: Tuple[int], **params) -> BBoxesType
apply_to_polygons
apply_to_polygons(polygons: PolygonType, image_size: Tuple[int], **params) -> PolygonType
Rotate
Rotate(angle_limit: Optional[List[float]] = None, interpolation: int = cv2.INTER_LINEAR, border_mode: int = cv2.BORDER_CONSTANT, value: Union[int, float, List[int], List[float]] = 0, mask_value: Union[int, float] = 0, crop_border: bool = False, **kwargs)
Bases: ImageSizeParams, ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
apply_to_image
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_mask
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_bboxes
apply_to_bboxes(bboxes: BBoxesType, image_size: Tuple[int], angle: float = 0, **params) -> BBoxesType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_polygons
apply_to_polygons(polygons: PolygonType, angle: float, image_size: Tuple[int], **params) -> PolygonType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
RandomRotate90
Bases: ImageSizeParams, ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
apply_to_image
apply_to_mask
apply_to_bboxes
apply_to_bboxes(bboxes: BBoxesType, image_size: Tuple[int], factor: int = 0, **params) -> BBoxesType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_polygons
apply_to_polygons(polygons: PolygonType, image_size: Tuple[int], factor: int = 0, **params) -> PolygonType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
ColorJitter
ColorJitter(brightness_limit: Optional[List[float]] = None, contrast_limit: Optional[List[float]] = None, saturation_limit: Optional[List[float]] = None, hue_limit: Optional[List[float]] = None, **kwargs)
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_image
apply_to_image(image: ImageType, brightness: float = 1.0, contrast: float = 1.0, saturation: float = 1.0, hue: float = 0, order: List[int] = [0, 1, 2, 3], **params) -> ImageType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
Blur
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
GaussianBlur
GaussianBlur(ksize_limit: Optional[List[int]] = None, sigma_limit: Optional[List[float]] = None, **kwargs)
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
apply_to_image
AdjustBrightness
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
apply_to_image
AdjustContrast
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
apply_to_image
AdjustHue
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
AdjustSaturation
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
apply_to_image
AdjustGamma
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
apply_to_image
AdjustBrightnessContrast
AdjustBrightnessContrast(brightness_limit: Optional[List[float]] = None, contrast_limit: Optional[List[float]] = None, brightness_by_max: bool = True, **kwargs)
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
IsoNoise
IsoNoise(color_shift_limit: Optional[List[float]] = None, intensity_limit: Optional[List[float]] = None, **kwargs)
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
JpegCompression
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
apply_to_image
Sharpen
Sharpen(alpha_limit: Optional[List[int]] = None, lightness_limit: Optional[List[int]] = None, **kwargs)
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
_generate_sharpening_matrix
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_image
MultiplicativeNoise
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
_generate_multiplier
_generate_multiplier(image: ImageType, multiplier: ndarray, random_seed: int) -> ndarray
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_image
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
RatioJitter
RatioJitter(proportion_limit: Optional[Union[List[float], int, float]] = None, resampling: str = 'bilinear', border_mode: int = cv2.BORDER_CONSTANT, value: Union[int, float, List[int], List[float]] = 0, mask_value: Union[int, float] = 0, **kwargs)
Bases: ImageSizeParams, ImageTransform
crop, pad, and resize to original image size
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_image
apply_to_image(image: ImageType, proportion_left: float, proportion_right: float, proportion_top: float, proportion_bottom: float, **params) -> ImageType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_mask
apply_to_mask(mask: MaskType, proportion_left: float, proportion_right: float, proportion_top: float, proportion_bottom: float, **params) -> MaskType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_bboxes
apply_to_bboxes(bboxes: BBoxesType, image_size: Tuple[int], proportion_left: float, proportion_right: float, proportion_top: float, proportion_bottom: float, **params) -> BBoxesType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_polygons
apply_to_polygons(polygons: PolygonType, image_size: Tuple[int], proportion_left: float, proportion_right: float, proportion_top: float, proportion_bottom: float, **params) -> PolygonType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
Zoom
Zoom(ratio_limit: Optional[List[float]] = None, resampling: str = 'bilinear', border_mode: int = cv2.BORDER_CONSTANT, value: Union[int, float, List[int], List[float]] = 0, mask_value: Union[int, float] = 0, **kwargs)
Bases: ImageSizeParams, ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_image
apply_to_image(image: ImageType, ratio: float, h_start: float, w_start: float, **params) -> ImageType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_mask
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_bboxes
apply_to_bboxes(bboxes: BBoxesType, image_size: Tuple[int], ratio: float, h_start: float, w_start: float, **params) -> BBoxesType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_polygons
apply_to_polygons(polygons: PolygonType, image_size: Tuple[int], ratio: float, h_start: float, w_start: float, **params) -> PolygonType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
RandomResizedCrop
RandomResizedCrop(scale_limit: Optional[List[float]] = None, aspect_ratio_limit: Optional[List[float]] = None, resampling: str = 'bilinear', **kwargs)
Bases: ImageSizeParams, ImageTransform
Crop a random part of the input and rescale it to original size
Parameters:
-
scale_limit(Optional[List[float]], default:None) –range of size of the origin size cropped. Defaults to [0.45, 1.00].
-
aspect_ratio_limit(Optional[List[float]], default:None) –range of aspect ratio of the origin aspect ratio cropped. Defaults to [0.50, 2.00].
-
resampling(str, default:'bilinear') –interpolation method. Defaults to "bilinear".
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_image
apply_to_image(image: ImageType, h_scale: float, w_scale: float, h_start: float, w_start: float, **params) -> ImageType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_mask
apply_to_mask(mask: MaskType, h_scale: float, w_scale: float, h_start: float, w_start: float, **params) -> MaskType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_bboxes
apply_to_bboxes(bboxes: BBoxesType, **params) -> BBoxesType
apply_to_polygons
apply_to_polygons(polygons: PolygonType, **params) -> PolygonType
RandomResizedCropAndPad
RandomResizedCropAndPad(scale_limit: Optional[List[float]] = None, aspect_ratio_limit: Optional[List[float]] = None, height: Optional[int] = None, width: Optional[int] = None, resampling: str = 'bilinear', border_mode: int = cv2.BORDER_CONSTANT, value: Union[int, float, List[int], List[float]] = 0, mask_value: Union[int, float] = 0, **kwargs)
Bases: ImageSizeParams, ImageTransform
pad, crop and resize to original image size
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_image
apply_to_image(image: ImageType, scale: float, aspect_ratio: float, h_start: float, w_start: float, **params) -> ImageType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_mask
apply_to_mask(mask: MaskType, scale: float, aspect_ratio: float, h_start: float, w_start: float, **params) -> MaskType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_bboxes
apply_to_bboxes(bboxes: BBoxesType, image_size: Tuple[int], scale: float, aspect_ratio: float, h_start: float, w_start: float, **params) -> BBoxesType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_polygons
apply_to_polygons(polygons: PolygonType, image_size: Tuple[int], scale: float, aspect_ratio: float, h_start: float, w_start: float, **params) -> PolygonType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
LightReflect
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
PerspectiveTransform
Bases: ImageSizeParams, ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_image
apply_to_image(image: ImageType, offset_top_left: OffsetType, offset_top_right: OffsetType, offset_bottom_right: OffsetType, offset_bottom_left: OffsetType, **params) -> ImageType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_mask
apply_to_mask(mask: MaskType, offset_top_left: OffsetType, offset_top_right: OffsetType, offset_bottom_right: OffsetType, offset_bottom_left: OffsetType, **params) -> MaskType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_bboxes
apply_to_bboxes(bboxes: BBoxesType, image_size: Tuple[int], offset_top_left: OffsetType, offset_top_right: OffsetType, offset_bottom_right: OffsetType, offset_bottom_left: OffsetType, **params) -> BBoxesType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_polygons
apply_to_polygons(polygons: PolygonType, image_size: Tuple[int], offset_top_left: OffsetType, offset_top_right: OffsetType, offset_bottom_right: OffsetType, offset_bottom_left: OffsetType, **params) -> PolygonType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
RandomErasing
RandomErasing(scale: Tuple[float, float] = (0.02, 0.33), ratio: Tuple[float, float] = (0.2, 3.3), value: Union[int, Tuple[int, int, int], str] = 0, randomly_select_values: bool = False, **kwargs)
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
_get_random_erase_params
This is modified version of get_params of random erasing see: https://pytorch.org/vision/main/_modules/torchvision/transforms/transforms.html#RandomErasing.forward
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
get_apply_params
get_apply_params() -> ParamsType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
apply_to_image
apply_to_image(image: ImageType, x_in_ratio: float, y_in_ratio: float, h_in_ratio: float, w_in_ratio: float, value: Union[int, Tuple[int, int, int], str], **params) -> ImageType
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
Grayscale
Bases: ImageTransform
Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
base_transform
Data augmentation을 위한 기본 Transform의 interface를 정의합니다.
BaseTransform
Transform의 기본 interface를 정의합니다.
Source code in SaigeToolkit/data/transform/augmentation/base_transform.py
__call__
Source code in SaigeToolkit/data/transform/augmentation/base_transform.py
get_apply_params
get_apply_params() -> ParamsType
get_params_from_data
get_params_from_data(data_for_params: ParamsType) -> ParamsType
이 함수는 input으로부터 parameter들을 뽑을 때 사용됩니다.
Parameters:
-
data_for_params(ParamsType) –params을 추출할 데이터를 입력으로 갖습니다.
Returns:
-
ParamsType(ParamsType) –params로 쓰일 데이터를 반환합니다.
Source code in SaigeToolkit/data/transform/augmentation/base_transform.py
apply_with_params
apply_with_params(params: ParamsType, **data) -> ParamsType
Source code in SaigeToolkit/data/transform/augmentation/base_transform.py
builder
_types
module-attribute
_types = {None: {__name__: _nCiEfor _type in _types}, None: {pascal_to_snake(__name__): _WFj4for _type in _types}}
Augmentation
Source code in SaigeToolkit/data/transform/augmentation/builder.py
__call__
Source code in SaigeToolkit/data/transform/augmentation/builder.py
build_augmentation
build_augmentation(config: Dict) -> Augmentation
Source code in SaigeToolkit/data/transform/augmentation/builder.py
compose
여러 Data Transform들을 하나로 묶어서 관리해주는 기본 BaseCompose 클래스 및 Compose 구현을 제공합니다.
base_compose
Data augmentation을 위한 기본 Compose의 interface를 정의합니다.
BaseCompose
BaseCompose(transforms: Sequence[Union[BaseTransform, BaseCompose]], prob: float = 1.0)
여러 Data Transform들을 하나로 묶어서 관리해주는 Compose의 기본 interface를 정의합니다.
Source code in SaigeToolkit/data/transform/augmentation/compose/base_compose.py
__call__
Source code in SaigeToolkit/data/transform/augmentation/compose/base_compose.py
apply
__len__
__getitem__
__getitem__(index: int) -> Union[BaseTransform, BaseCompose]
builder
_types
module-attribute
_types = {None: {__name__: _FLqTfor _type in _types}, None: {pascal_to_snake(__name__): _iky6for _type in _types}}
build_compose
build_compose(_target_: str, transforms: List[BaseTransform], **config) -> BaseCompose
compose
Compose
Compose(transforms: Sequence[Union[BaseTransform, BaseCompose]], prob: float = 1.0)
Bases: BaseCompose
Source code in SaigeToolkit/data/transform/augmentation/compose/base_compose.py
SomeOf
Bases: BaseCompose
Source code in SaigeToolkit/data/transform/augmentation/compose/compose.py
apply
Source code in SaigeToolkit/data/transform/augmentation/compose/compose.py
box_function
preserve_coordinates
Box augmentation이 (left, top, right, bottom) coordinate system을 기반으로 구현 되어있기 때문에, input bboxes의 coordinate system을 확인하고 augmentation에 맞는 coordinate system으로 변환하고, augmentation이 끝나면 다시 기존 coordinate system으로 변경하여 출력합니다.
-
np.ndarray의 경우 coordinate system을 체크할 수 없기 때문에 (left, top, right, bottom) coordinate system이라고 가정합니다.
-
NumpyBBoxes의 경우 NumpyBBoxes 내부 변수 coordinate과 내부 함수 convert_coordinate를 활용하여 구현됩니다.
Source code in SaigeToolkit/data/transform/box_function.py
resize_box
resize_box(bboxes: BBoxesType, image_size: Tuple[int], tw: int, th: int) -> BBoxesType
bbox resize from (w, h) to (tw, th)
Source code in SaigeToolkit/data/transform/box_function.py
crop_box
crop_box(bboxes: BBoxesType, cropping_box: Union[ndarray, List[int]]) -> BBoxesType
bbox crop. An image is cropped at (new_left, new_top, new_right, new_bottom)
Source code in SaigeToolkit/data/transform/box_function.py
hflip_box
hflip_box(bboxes: BBoxesType, image_size: Tuple[int]) -> BBoxesType
vflip_box
vflip_box(bboxes: BBoxesType, image_size: Tuple[int]) -> BBoxesType
rotate
rotate(bboxes: BBoxesType, angle: Union[float, int], image_size: Tuple[int], target_size: Optional[Tuple[int]] = None, clipping: bool = True) -> BBoxesType
Source code in SaigeToolkit/data/transform/box_function.py
rotate90
rotate90(bboxes: BBoxesType, factor: int, image_size: Tuple[int], clipping: bool = True) -> BBoxesType
Source code in SaigeToolkit/data/transform/box_function.py
translate_box
translate_box(bboxes: BBoxesType, offset: Tuple[int], image_size: Tuple[int]) -> BBoxesType
Source code in SaigeToolkit/data/transform/box_function.py
ratio_jitter
ratio_jitter(bboxes: BBoxesType, image_size: Tuple[int], proportion_left: float = 0.0, proportion_right: float = 0.0, proportion_top: float = 0.0, proportion_bottom: float = 0.0) -> BBoxesType
Source code in SaigeToolkit/data/transform/box_function.py
zoom
zoom(bboxes: BBoxesType, image_size: Tuple[int], ratio: float = 1.0, h_start: float = 0.0, w_start: float = 0.0) -> BBoxesType
Source code in SaigeToolkit/data/transform/box_function.py
random_resized_crop_and_pad
random_resized_crop_and_pad(bboxes: BBoxesType, image_size: Tuple[int], scale: float = 1.0, aspect_ratio: float = 1.0, h_start: float = 0.0, w_start: float = 0.0, height: Optional[int] = None, width: Optional[int] = None) -> BBoxesType
Source code in SaigeToolkit/data/transform/box_function.py
perspective_transform
perspective_transform(bboxes: BBoxesType, image_size: Tuple[int], offset_top_left: OffsetType, offset_top_right: OffsetType, offset_bottom_right: OffsetType, offset_bottom_left: OffsetType) -> BBoxesType
Source code in SaigeToolkit/data/transform/box_function.py
function_util
Define utility functions for data augmentation.
check_value
Source code in SaigeToolkit/data/transform/function_util.py
check_range
check_range(data: Union[Sequence[int], Sequence[float]], min_value: Union[int, float], max_value: Union[int, float])
Source code in SaigeToolkit/data/transform/function_util.py
ratio_to_value
Source code in SaigeToolkit/data/transform/function_util.py
support_gray
Source code in SaigeToolkit/data/transform/function_util.py
support_rgba
Source code in SaigeToolkit/data/transform/function_util.py
support_3dim_gray_image
Source code in SaigeToolkit/data/transform/function_util.py
support_multi_image
Source code in SaigeToolkit/data/transform/function_util.py
image_function
RESAMPLE_PIL
module-attribute
RESAMPLE_CV2
module-attribute
RESAMPLE_TORCH
module-attribute
read_image_size
read_image_size(image: Union[Image, Tensor, ndarray]) -> ImageSizeType
image size: (W, H)
Source code in SaigeToolkit/data/transform/image_function.py
resize_image
resize_image(image: Union[Image, Tensor, ndarray], target_size: ImageSizeType, resampling: str = 'bilinear', use_cv2_for_numpy: bool = True) -> Union[Image, Tensor, ndarray]
이미지를 resize합니다.
Parameters:
-
image(Union[Image, Tensor, ndarray]) –image data
-
target_size(ImageSizeType) –[W, H]
-
resampling(str, default:'bilinear') –resampling method. Defaults to "bilinear".
-
use_cv2_for_numpy(bool, default:True) –use cv2 instead of PIL for faster numpy array image resizing. Defaults to True.
Returns:
-
Union[Image, Tensor, ndarray]–Union[Image.Image, torch.Tensor, np.ndarray]: resized image
Source code in SaigeToolkit/data/transform/image_function.py
resize_mask
resize_mask(mask: Union[Image, Tensor, ndarray], target_size: ImageSizeType) -> Union[Image, Tensor, ndarray]
mask 이미지를 resize합니다. (NEAREST resampling)
Parameters:
-
mask(Union[Image, Tensor, ndarray]) –mask image
-
target_size(ImageSizeType) –[W, H]
Returns:
-
Union[Image, Tensor, ndarray]–Union[Image.Image, torch.Tensor, np.ndarray]: resized mask image
Source code in SaigeToolkit/data/transform/image_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
crop
crop(image: Union[Image, Tensor, ndarray], coordinates: Union[List[int], Tuple[int, int, int, int]]) -> Union[Image, Tensor, ndarray]
이미지의 coordinates 좌표영역을 크롭합니다. coordinates가 이미지를 벗어나는 경우 zero padding 합니다.
Parameters:
-
image(Union[Image, Tensor, ndarray]) –image
-
coordinates(Union[List[int], Tuple[int, int, int, int]]) –[left, top, right, bottom]
Returns:
-
Union[Image, Tensor, ndarray]–Union[Image.Image, torch.Tensor, np.ndarray]: cropped image
Source code in SaigeToolkit/data/transform/image_function.py
add_constant_margin
add_constant_margin(image: Union[Image, Tensor, ndarray], left: int, top: int, right: int, bottom: int, value: Union[float, int]) -> Union[Image, Tensor, ndarray]
image에 left, top, right, bottom 만큼 constant value로 padding 합니다.
Parameters:
-
image(Union[Image, Tensor, ndarray]) –image
-
left(int) –image의 왼쪽 padding size 입니다.
-
top(int) –image의 위쪽 padding size 입니다.
-
right(int) –image의 오른쪽 padding size 입니다.
-
bottom(int) –image의 아래쪽 padding size 입니다.
-
value(Union[float, int]) –padding된 영역에 들어갈 value 입니다.
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 입니다.
Source code in SaigeToolkit/data/transform/image_function.py
fill_pixels_with_mask
fill_pixels_with_mask(image: Union[Image, ndarray], bool_mask: ndarray, value: Union[int, float] = 0) -> Union[Image, ndarray]
image 중 bool_mask=True인 픽셀들을 value로 채웁니다.
Parameters:
-
image(Union[Image, ndarray]) –image (HW or HWC)
-
bool_mask(ndarray) –boolean mask (HW)
-
value(Union[int, float], default:0) –. Defaults to 0.
Returns:
-
Union[Image, ndarray]–Union[Image.Image, np.ndarray]: 결과 이미지
Note
- image가 Image.Image인 경우, 결과 이미지도 Image.Image로 반환합니다.
- image의 값이 inplace로 변경됩니다. 값이 변경되지 않길 원한다면, copy를 해주세요.
Source code in SaigeToolkit/data/transform/image_function.py
to_numpy
Source code in SaigeToolkit/data/transform/image_function.py
to_pil
Source code in SaigeToolkit/data/transform/image_function.py
convert_image_mode
convert_image_mode(image: Union[Image, ndarray], mode: str, copy: bool = False) -> Union[Image, ndarray]
convert image mode
Parameters:
-
image(Union[Image, ndarray]) –image
-
mode(str) –"RGB" or "L"
-
copy(bool, default:False) –to copy data. Defaults to False.
Returns:
-
Union[Image, ndarray]–Union[Image.Image, np.ndarray]: converted image
Note
RGB -> L 변환 시 Image.Image와 np.ndarray 연산 결과가 다를 수 있음. (PIL과 cv2 에서 변환식은 L = R * 299/1000 + G * 587/1000 + B * 114/1000 로 동일하나 소숫점 처리 방식이 다름)
Source code in SaigeToolkit/data/transform/image_function.py
image_load
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__
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
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
load_from_array
Source code in SaigeToolkit/data/transform/image_load.py
load_from_pil
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
_is_16bit
staticmethod
Source code in SaigeToolkit/data/transform/image_load.py
polygon_function
vertical_flip
vertical_flip(polygons: PolygonType, image_size: Tuple[int]) -> PolygonType
horizontal_flip
horizontal_flip(polygons: PolygonType, image_size: Tuple[int]) -> PolygonType
rotate
rotate(polygons: PolygonType, angle: float, image_size: Tuple[int], target_size: Optional[Tuple[int]] = None) -> PolygonType
Source code in SaigeToolkit/data/transform/polygon_function.py
rotate90
rotate90(polygons: PolygonType, factor: int, image_size: Tuple[int]) -> PolygonType
Source code in SaigeToolkit/data/transform/polygon_function.py
ratio_jitter
ratio_jitter(polygons: PolygonType, image_size: Tuple[int], proportion_left: float, proportion_right: float, proportion_top: float, proportion_bottom: float) -> PolygonType
Source code in SaigeToolkit/data/transform/polygon_function.py
zoom
zoom(polygons: PolygonType, image_size: Tuple[int], ratio: float, h_start: float, w_start: float) -> PolygonType
Source code in SaigeToolkit/data/transform/polygon_function.py
random_resized_crop_and_pad
random_resized_crop_and_pad(polygons: PolygonType, image_size: Tuple[int], scale: float, aspect_ratio: float, h_start: float, w_start: float, h_target: Optional[int] = None, w_target: Optional[int] = None, **params) -> PolygonType
Source code in SaigeToolkit/data/transform/polygon_function.py
perspective_transform
perspective_transform(polygons: PolygonType, image_size: Tuple[int], offset_top_left: OffsetType, offset_top_right: OffsetType, offset_bottom_right: OffsetType, offset_bottom_left: OffsetType) -> PolygonType
Source code in SaigeToolkit/data/transform/polygon_function.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
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
resize
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
round_functions
class-attribute
instance-attribute
__call__
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
apply_with_params
classmethod
apply_with_params(data: Dict, input_size: ImageSizeType, target_size: ImageSizeType, resampling: str, image_only: bool, use_cv2_for_numpy: bool = True) -> Dict
Source code in SaigeToolkit/data/transform/resize.py
apply_to_image
staticmethod
apply_to_image(image, target_size: ImageSizeType, resampling: str, use_cv2_for_numpy: bool = True)
Source code in SaigeToolkit/data/transform/resize.py
apply_to_mask
staticmethod
apply_to_mask(mask, target_size: ImageSizeType)
apply_to_bboxes
staticmethod
apply_to_bboxes(bboxes, input_size: ImageSizeType, target_size: ImageSizeType)
apply_to_polygons
staticmethod
apply_to_polygons(polygons, input_size: ImageSizeType, target_size: ImageSizeType)
Source code in SaigeToolkit/data/transform/resize.py
_compute_target_size
classmethod
_compute_target_size(input_size: Union[ImageSizeType, ndarray], 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') -> ImageSizeType
Source code in SaigeToolkit/data/transform/resize.py
_preprocess_size
staticmethod
_preprocess_size(size: Optional[Union[ImageSizeType, int]] = None) -> ImageSizeType
Source code in SaigeToolkit/data/transform/resize.py
_check_parameter
classmethod
_check_parameter(size: Optional[Union[ImageSizeType, int]], scale: Optional[Union[int, float]], area_sqrt: Optional[Union[int, float]], max_size: Optional[Union[ImageSizeType, int]], round: Optional[int], round_type: str) -> None
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
_check_inspection_size_type
_check_inspection_size_type(inspection_size_wh: Optional[ImageSizeType]) -> None
Source code in SaigeToolkit/data/transform/resize.py
_check_inspection_size_value
_check_inspection_size_value(inspection_size_wh: Optional[ImageSizeType]) -> None
Source code in SaigeToolkit/data/transform/resize.py
set_scale_from_data
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
is_empty
instance-attribute
is_empty = len(resizer_list) == 0 or all(x is None for x in resizer_list)
__call__
Source code in SaigeToolkit/data/transform/resize.py
roi
ROI 좌표 계산 및 ROI 크롭, blind_mask 적용을 수행하는 ROIHandler 클래스를 제공합니다. Set-ROI 기능을 위한 API 클래스인 ROIHandlerAPI도 제공합니다.
api
ROIHandlerAPI
Set-ROI 기능을 위한 API입니다.
Usage
# 핸들러 빌드. 아래는 simple mode의 예제 config이며, 자세한 설명은 ROIHandlerAPI.set() 함수 참고.
config = {
"mode": "simple",
"left": 0.0,
"top": 0.0,
"right": 1.0,
"bottom": 1.0,
"blind_mask": None,
}
error, roi_hander = ROIHandlerAPI.build(config)
# image에 대한 roi 계산. 리턴 결과 설명은 ROIHandlerAPI.apply() 함수 참고.
image = np.zeros((100, 100, 3), dtype=np.unit8)
error, roi_results = roi_handler.apply(image)
# roi 파라미터 변경
config["left"] = 0.1
error, _ = roi_handler.set(config)
# 변경된 파라미터로 roi 다시 계산
error, roi_results = roi_handler.apply(image)
Source code in SaigeToolkit/data/transform/roi/api.py
build
classmethod
build(config: Dict) -> ROIHandlerAPI
ROIHandlerAPI를 빌드합니다. Args: config (Dict): ROIHandlerAPI.set의 파라미터와 동일합니다.
Returns:
-
ROIHandlerAPI(ROIHandlerAPI) –빌드된 ROIHandlerAPI
Source code in SaigeToolkit/data/transform/roi/api.py
set
ROI 파라미터를 변경합니다.
Parameters:
-
config(Dict) –ROI 파라미터의 dict입니다. mode에 따라 다른 파라미터를 가집니다.
# simple mode: { "mode": "simple", # Simple ROI 모드. "left": float, # ROI의 왼쪽 경계. [0.0, 1.0) 범위의 실수. "top": float, # ROI의 위쪽 경계. [0.0, 1.0) 범위의 실수. "right": float, # ROI의 오른쪽 경계. (right, 1.0] 범위의 실수. "bottom": float, # ROI의 아래쪽 경계. (top, 1.0] 범위의 실수. "blind_mask": Optional[np.ndarray], # blind mask 이미지. None인 경우 blind 적용 안함. # np.ndarray인 경우 (dtype=uint8, shape=(H_roi, W_roi))이며 픽셀 값은 0 또는 1. # mask의 값이 1인 영역이 학습/검사 시 마스킹됩니다. # polygons에는 blind_mask가 적용되지 않습니다. } # advanced mode: { "mode": "advanced", # Advanced ROI 모드. "intensity": List[int], # 필터링할 [최소, 최대] 픽셀값 범위. 각 값은 [0, 255] 범위의 정수. "expansion": int, # 필터링된 픽셀 영역에 대한 확장/축소 정도. [-10, 10] 범위의 정수. "inversion": bool, # True인 경우 필터링된 픽셀 영역을 반전. "offset_left": float, # ROI 박스의 왼쪽 사이즈. [0.0, 2.0] 범위의 실수 이며, 1인 경우 기본 크기. "offset_right": float, # ROI 박스의 오른쪽 사이즈. [0.0, 2.0] 범위의 실수 이며, 1인 경우 기본 크기. "offset_top": float, # ROI 박스의 위쪽 사이즈. [0.0, 2.0] 범위의 실수 이며, 1인 경우 기본 크기. "offset_bottom": float, # ROI 박스의 아래쪽 사이즈. [0.0, 2.0] 범위의 실수 이며, 1인 경우 기본 크기. "blind_mask": Optional[np.ndarray], # blind mask 이미지. None인 경우 blind 적용 안함. # np.ndarray인 경우 (dtype=uint8, shape=(H_roi, W_roi))이며 픽셀 값은 0 또는 1. # mask의 값이 1인 영역이 학습/검사 시 마스킹됩니다. # polygons에는 blind_mask가 적용되지 않습니다. }
Source code in SaigeToolkit/data/transform/roi/api.py
apply
image에 대한 ROI 좌표 및 기타 결과를 계산합니다.
Parameters:
-
image(ndarray) –ROI를 적용할 입력 이미지.
Returns:
-
Dict(Dict) –ROI 계산 결과 dict 입니다. mode에 따라 다른 결과 값들을 가집니다.
Source code in SaigeToolkit/data/transform/roi/api.py
roi_calculator
ROICalculator
RelativeBoxROI
Bases: ROICalculator
이미지 크기에 비례하는 상대좌표 박스로 ROI를 계산합니다.
Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
set
Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
__call__
__call__(image: Union[Image, ndarray], get_intermediate_results: bool = False, warmup: bool = False, **data) -> Dict
Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
PixelIntensityROI
Bases: ROICalculator
픽셀값이 intensity 범위에 들어오는 픽셀만 필터링한 뒤, 필터링 된 픽셀들의 컨투어를 찾고,
가장 면적이 큰 컨투어를 감싸는 최소 박스로 ROI를 계산합니다.
Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
set
set(intensity: Union[Tuple[int, int], List[int]], expansion: int, inversion: bool, offset_left: float, offset_right: float, offset_top: float, offset_bottom: float) -> None
Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
__call__
__call__(image: Union[Image, ndarray], get_intermediate_results: bool = False, warmup: bool = False, **data) -> Dict
Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
AutoRelativeBoxROI
Bases: RelativeBoxROI
RelativeBoxROI class with automatic coordinate calculation.
Monostate pattern applied to prevent ROI coordinate mismatch between train ~ validation dataset.
Attributes:
-
left(float) –ROI coordinates.
-
top(float) –ROI coordinates.
-
right(float) –ROI coordinates.
-
bottom(float) –ROI coordinates.
-
is_ready(bol) –Whether auto ROI coordinates is set.
-
image_hw(Optional[List[int]]) –dataset image size.
-
discard_outer_polygons(bool) –Flag for discarding polygons outside of current ROI region.
-
expand_ratio–Ratio for expanding ROI region. Larger value means more padding.
Example
Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
__shared_state
class-attribute
instance-attribute
__shared_state = {'_is_ready': False, '_image_hw': None, '_left': -1.0, '_top': -1.0, '_right': -1.0, '_bottom': -1.0}
REGION_EXPAND_RATIO
class-attribute
instance-attribute
_check_auto_roi_is_ready
Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
__call__
autoupdate_roi_coordinate
Automatically update ROI coordinate using dataset information.
Returns success flag.
Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
_expand_region_xyxy
Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
_fit_region_into_img_size
Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
roi_handler
ROIHandler
ROI 기능을 수행합니다. 이미지에 대한 ROI 좌표를 계산해 크롭하고, 크롭된 이미지에 blind_mask를 적용해 마스크 영역의 픽셀 값을 0으로 치환합니다.
Source code in SaigeToolkit/data/transform/roi/roi_handler.py
roi_calculator_types
class-attribute
instance-attribute
roi_calculator_types = {'simple': RelativeBoxROI, 'advanced': PixelIntensityROI, 'auto': AutoRelativeBoxROI}
set
set(mode: str, blind_mask: Union[None, ndarray, str], image_only: bool = False, discard_outer_polygons: bool = False, det_blind_mask_threshold: float = 0.5, **kwargs)
Source code in SaigeToolkit/data/transform/roi/roi_handler.py
apply_crop
apply_crop(image: Union[Image, ndarray, List[Union[Image, ndarray]]], return_revert_params: bool = False, warmup: bool = False, **data) -> Union[Dict, Tuple[Dict, Dict]]
Source code in SaigeToolkit/data/transform/roi/roi_handler.py
apply_mask
Source code in SaigeToolkit/data/transform/roi/roi_handler.py
__call__
__call__(return_revert_params: bool = False, warmup: bool = False, **data) -> Union[Dict, Tuple[Dict, Dict]]
Source code in SaigeToolkit/data/transform/roi/roi_handler.py
_check_polygon_within_box
Source code in SaigeToolkit/data/transform/roi/roi_handler.py
transform
End-to-end 데이터 변환을 지원하는 모듈입니다.
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
inspection_size_resizer
instance-attribute
inspection_size_resizer: Optional[InspectionSizeResizer] = None
Operation
__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
_get_next_revert_operation(transform_params: Dict) -> Optional[Operation]
다음으로 할 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
revert(data: Dict, transform_params: Dict, operation: Optional[Operation] = None) -> Dict
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
_revert
classmethod
Source code in SaigeToolkit/data/transform/transform.py
_revert_resize
staticmethod
_revert_resize(data: Optional[Union[Tensor, ndarray, List[Dict]]], revert_params: Optional[Dict], data_type: str) -> Union[Tensor, ndarray, List[Dict]]
Source code in SaigeToolkit/data/transform/transform.py
_revert_roi
staticmethod
_revert_roi(data: Optional[Union[Tensor, ndarray, List[Dict]]], revert_params: Optional[Dict], data_type: str) -> Union[Tensor, ndarray, List[Dict]]
Source code in SaigeToolkit/data/transform/transform.py
is_oversized
staticmethod
InspectionSize 연산에서 resize 되었는지 여부를 판단