Skip to content

Commit 09d804f

Browse files
committed
Add gamma_aug
1 parent 77b3e99 commit 09d804f

2 files changed

Lines changed: 90 additions & 33 deletions

File tree

library/config_util.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ class BaseSubsetParams:
6363
secondary_separator: Optional[str] = None
6464
enable_wildcard: bool = False
6565
color_aug: bool = False
66+
gamma_aug: bool = False
67+
gamma_aug_range: Optional[Tuple[float, float]] = None
68+
gamma_aug_rate: float = 0.5
6669
flip_aug: bool = False
6770
face_crop_aug_range: Optional[Tuple[float, float]] = None
6871
random_crop: bool = False
@@ -187,6 +190,9 @@ def __validate_and_convert_scalar_or_twodim(klass, value: Union[float, Sequence]
187190
# subset schema
188191
SUBSET_ASCENDABLE_SCHEMA = {
189192
"color_aug": bool,
193+
"gamma_aug": bool,
194+
"gamma_aug_range": functools.partial(__validate_and_convert_twodim.__func__, float),
195+
"gamma_aug_rate": Any(float, int),
190196
"face_crop_aug_range": functools.partial(__validate_and_convert_twodim.__func__, float),
191197
"flip_aug": bool,
192198
"num_repeats": int,
@@ -502,6 +508,7 @@ def generate_dataset_group_by_blueprint(dataset_group_blueprint: DatasetGroupBlu
502508
# Set values for consistency
503509
subset_blueprint.params.num_repeats = 1
504510
subset_blueprint.params.color_aug = False
511+
subset_blueprint.params.gamma_aug = False
505512
subset_blueprint.params.flip_aug = False
506513
subset_blueprint.params.random_crop = False
507514
subset_blueprint.params.random_crop_padding_percent = 0.0
@@ -523,6 +530,7 @@ def generate_dataset_group_by_blueprint(dataset_group_blueprint: DatasetGroupBlu
523530
# Set values for consistency
524531
subset_blueprint_params_copy.num_repeats = 1
525532
subset_blueprint_params_copy.color_aug = False
533+
subset_blueprint_params_copy.gamma_aug = False
526534
subset_blueprint_params_copy.flip_aug = False
527535
subset_blueprint_params_copy.random_crop = False
528536
subset_blueprint_params_copy.random_crop_padding_percent = 0.0
@@ -582,6 +590,9 @@ def print_info(_datasets, dataset_type: str):
582590
caption_prefix: {subset.caption_prefix}
583591
caption_suffix: {subset.caption_suffix}
584592
color_aug: {subset.color_aug}
593+
gamma_aug: {subset.gamma_aug}
594+
gamma_aug_range: {subset.gamma_aug_range}
595+
gamma_aug_rate: {subset.gamma_aug_rate}
585596
flip_aug: {subset.flip_aug}
586597
face_crop_aug_range: {subset.face_crop_aug_range}
587598
random_crop: {subset.random_crop}

library/train_util.py

Lines changed: 79 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -410,35 +410,32 @@ class AugHelper:
410410
def __init__(self):
411411
pass
412412

413-
def color_aug(self, image: np.ndarray):
414-
# self.color_aug_method = albu.OneOf(
415-
# [
416-
# albu.HueSaturationValue(8, 0, 0, p=0.5),
417-
# albu.RandomGamma((95, 105), p=0.5),
418-
# ],
419-
# p=0.33,
420-
# )
421-
hue_shift_limit = 8
422-
423-
# remove dependency to albumentations
424-
if random.random() <= 0.33:
425-
if random.random() > 0.5:
426-
# hue shift
427-
hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
428-
hue_shift = random.uniform(-hue_shift_limit, hue_shift_limit)
429-
if hue_shift < 0:
430-
hue_shift = 180 + hue_shift
431-
hsv_img[:, :, 0] = (hsv_img[:, :, 0] + hue_shift) % 180
432-
image = cv2.cvtColor(hsv_img, cv2.COLOR_HSV2BGR)
433-
else:
434-
# random gamma
435-
gamma = random.uniform(0.95, 1.05)
436-
image = np.clip(image**gamma, 0, 255).astype(np.uint8)
413+
def get_augmentor(self, use_color_aug: bool, use_gamma_aug: bool, gamma_aug_range: Optional[Tuple[float, float]], gamma_aug_rate: float):
414+
def augmentor(image: np.ndarray, **kwargs):
415+
if use_color_aug:
416+
hue_shift_limit = 8
417+
if random.random() <= 0.33:
418+
if random.random() > 0.5:
419+
hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
420+
hue_shift = random.uniform(-hue_shift_limit, hue_shift_limit)
421+
if hue_shift < 0:
422+
hue_shift = 180 + hue_shift
423+
hsv_img[:, :, 0] = (hsv_img[:, :, 0] + hue_shift) % 180
424+
image = cv2.cvtColor(hsv_img, cv2.COLOR_HSV2BGR)
425+
else:
426+
gamma = random.uniform(0.95, 1.05)
427+
image = np.clip(image**gamma, 0, 255).astype(np.uint8)
428+
429+
if use_gamma_aug and gamma_aug_range is not None:
430+
if random.random() <= gamma_aug_rate:
431+
gamma = random.uniform(gamma_aug_range[0], gamma_aug_range[1])
432+
image = np.clip(image**gamma, 0, 255).astype(np.uint8)
437433

438-
return {"image": image}
434+
return {"image": image}
439435

440-
def get_augmentor(self, use_color_aug: bool): # -> Optional[Callable[[np.ndarray], Dict[str, np.ndarray]]]:
441-
return self.color_aug if use_color_aug else None
436+
if use_color_aug or use_gamma_aug:
437+
return augmentor
438+
return None
442439

443440

444441
class BaseSubset:
@@ -454,6 +451,9 @@ def __init__(
454451
secondary_separator: Optional[str],
455452
enable_wildcard: bool,
456453
color_aug: bool,
454+
gamma_aug: bool,
455+
gamma_aug_range: Optional[Tuple[float, float]],
456+
gamma_aug_rate: float,
457457
flip_aug: bool,
458458
face_crop_aug_range: Optional[Tuple[float, float]],
459459
random_crop: bool,
@@ -481,6 +481,9 @@ def __init__(
481481
self.secondary_separator = secondary_separator
482482
self.enable_wildcard = enable_wildcard
483483
self.color_aug = color_aug
484+
self.gamma_aug = gamma_aug
485+
self.gamma_aug_range = gamma_aug_range
486+
self.gamma_aug_rate = gamma_aug_rate
484487
self.flip_aug = flip_aug
485488
self.face_crop_aug_range = face_crop_aug_range
486489
self.random_crop = random_crop
@@ -523,6 +526,9 @@ def __init__(
523526
secondary_separator,
524527
enable_wildcard,
525528
color_aug,
529+
gamma_aug,
530+
gamma_aug_range,
531+
gamma_aug_rate,
526532
flip_aug,
527533
face_crop_aug_range,
528534
random_crop,
@@ -553,6 +559,9 @@ def __init__(
553559
secondary_separator,
554560
enable_wildcard,
555561
color_aug,
562+
gamma_aug,
563+
gamma_aug_range,
564+
gamma_aug_rate,
556565
flip_aug,
557566
face_crop_aug_range,
558567
random_crop,
@@ -599,6 +608,9 @@ def __init__(
599608
secondary_separator,
600609
enable_wildcard,
601610
color_aug,
611+
gamma_aug,
612+
gamma_aug_range,
613+
gamma_aug_rate,
602614
flip_aug,
603615
face_crop_aug_range,
604616
random_crop,
@@ -629,6 +641,9 @@ def __init__(
629641
secondary_separator,
630642
enable_wildcard,
631643
color_aug,
644+
gamma_aug,
645+
gamma_aug_range,
646+
gamma_aug_rate,
632647
flip_aug,
633648
face_crop_aug_range,
634649
random_crop,
@@ -670,6 +685,9 @@ def __init__(
670685
secondary_separator,
671686
enable_wildcard,
672687
color_aug,
688+
gamma_aug,
689+
gamma_aug_range,
690+
gamma_aug_rate,
673691
flip_aug,
674692
face_crop_aug_range,
675693
random_crop,
@@ -700,6 +718,9 @@ def __init__(
700718
secondary_separator,
701719
enable_wildcard,
702720
color_aug,
721+
gamma_aug,
722+
gamma_aug_range,
723+
gamma_aug_rate,
703724
flip_aug,
704725
face_crop_aug_range,
705726
random_crop,
@@ -1202,7 +1223,7 @@ def verify_bucket_reso_steps(self, min_steps: int):
12021223
)
12031224

12041225
def is_latent_cacheable(self):
1205-
return all([not subset.color_aug and not subset.random_crop for subset in self.subsets])
1226+
return all([not subset.color_aug and not subset.gamma_aug and not subset.random_crop for subset in self.subsets])
12061227

12071228
def is_text_encoder_output_cacheable(self, cache_supports_dropout: bool = False):
12081229
return all(
@@ -1761,7 +1782,7 @@ def __getitem__(self, index):
17611782
crop_ltrb = (0, 0, 0, 0)
17621783

17631784
# augmentation
1764-
aug = self.aug_helper.get_augmentor(subset.color_aug)
1785+
aug = self.aug_helper.get_augmentor(subset.color_aug, subset.gamma_aug, subset.gamma_aug_range, subset.gamma_aug_rate)
17651786
if aug is not None:
17661787
# augment RGB channels only
17671788
img_rgb = img[:, :, :3]
@@ -4767,6 +4788,21 @@ def add_dataset_arguments(
47674788
parser.add_argument(
47684789
"--color_aug", action="store_true", help="enable weak color augmentation / 学習時に色合いのaugmentationを有効にする"
47694790
)
4791+
parser.add_argument(
4792+
"--gamma_aug", action="store_true", help="enable gamma augmentation / 学習時にガンマのaugmentationを有効にする"
4793+
)
4794+
parser.add_argument(
4795+
"--gamma_aug_range",
4796+
type=str,
4797+
default="0.95,1.05",
4798+
help="gamma augmentation range (e.g. 0.9,1.1) / 学習時にガンマのaugmentationを有効にするときの範囲を指定する(例:0.9,1.1)",
4799+
)
4800+
parser.add_argument(
4801+
"--gamma_aug_rate",
4802+
type=float,
4803+
default=0.5,
4804+
help="gamma augmentation probability/rate (0.0 to 1.0) / ガンマのaugmentationの確率(0.0 から 1.0)",
4805+
)
47704806
parser.add_argument(
47714807
"--flip_aug", action="store_true", help="enable horizontal flip augmentation / 学習時に左右反転のaugmentationを有効にする"
47724808
)
@@ -5732,18 +5768,28 @@ def prepare_dataset_args(args: argparse.Namespace, support_metadata: bool):
57325768
len(args.resolution) == 2
57335769
), f"resolution must be 'size' or 'width,height' / resolution(解像度)は'サイズ'または'幅','高さ'で指定してください: {args.resolution}"
57345770

5735-
if args.face_crop_aug_range is not None:
5736-
args.face_crop_aug_range = tuple([float(r) for r in args.face_crop_aug_range.split(",")])
5771+
if getattr(args, "face_crop_aug_range", None) is not None:
5772+
if isinstance(args.face_crop_aug_range, str):
5773+
args.face_crop_aug_range = tuple([float(r) for r in args.face_crop_aug_range.split(",")])
57375774
assert (
57385775
len(args.face_crop_aug_range) == 2 and args.face_crop_aug_range[0] <= args.face_crop_aug_range[1]
57395776
), f"face_crop_aug_range must be two floats / face_crop_aug_rangeは'下限,上限'で指定してください: {args.face_crop_aug_range}"
57405777
else:
57415778
args.face_crop_aug_range = None
57425779

5780+
if getattr(args, "gamma_aug_range", None) is not None:
5781+
if isinstance(args.gamma_aug_range, str):
5782+
args.gamma_aug_range = tuple([float(r) for r in args.gamma_aug_range.split(",")])
5783+
assert (
5784+
len(args.gamma_aug_range) == 2 and args.gamma_aug_range[0] <= args.gamma_aug_range[1]
5785+
), f"gamma_aug_range must be two floats / gamma_aug_rangeは'下限,上限'で指定してください: {args.gamma_aug_range}"
5786+
else:
5787+
args.gamma_aug_range = None
5788+
57435789
if support_metadata:
5744-
if args.in_json is not None and (args.color_aug or args.random_crop):
5790+
if args.in_json is not None and (args.color_aug or args.random_crop or getattr(args, "gamma_aug", False)):
57455791
logger.warning(
5746-
f"latents in npz is ignored when color_aug or random_crop is True / color_augまたはrandom_cropを有効にした場合、npzファイルのlatentsは無視されます"
5792+
f"latents in npz is ignored when color_aug or gamma_aug or random_crop is True / color_augまたはgamma_augかrandom_cropを有効にした場合、npzファイルのlatentsは無視されます"
57475793
)
57485794

57495795

0 commit comments

Comments
 (0)