File size: 7,308 Bytes
9c206a9 ea07c6e 9c206a9 4810ae5 ea07c6e 9c206a9 4810ae5 9c206a9 4810ae5 9c206a9 4810ae5 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 9c206a9 4810ae5 9c206a9 ea07c6e 4810ae5 ea07c6e 4810ae5 ea07c6e 4810ae5 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 9c206a9 6b540a3 ea07c6e 6b540a3 ea07c6e 6b540a3 ea07c6e 6b540a3 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 6b540a3 ea07c6e 9c206a9 4810ae5 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 9c206a9 ea07c6e 9c206a9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 |
import os
import cv2
import argparse
import random
import string
import albumentations as A
def augment_final_image(image):
transform = A.Compose(
[
A.MotionBlur(blur_limit=(3, 11), p=0.05),
A.GaussNoise(var_limit=(1, 10), p=0.2),
A.ColorJitter(
brightness=(0.6, 1.0),
contrast=(0.6, 1.0),
saturation=(0.3, 1),
hue=(0.0, 0.1),
p=0.5,
),
A.RandomFog(
fog_coef_lower=0.05,
fog_coef_upper=0.2,
alpha_coef=0.08,
always_apply=False,
p=0.2,
),
A.RandomShadow(
shadow_roi=(0, 0.5, 1, 1),
num_shadows_limit=(1, 2),
num_shadows_lower=None,
num_shadows_upper=None,
shadow_dimension=5,
always_apply=False,
p=0.2,
),
A.RandomToneCurve(scale=0.1, always_apply=False, p=0.5),
]
)
return transform(image=image)["image"]
def augment_background(image):
transform = A.Compose(
[
A.RandomBrightnessContrast(brightness_limit=(-0.4, 0.0), p=0.2),
A.RandomShadow(
shadow_roi=(0, 0.7, 1, 1),
num_shadows_limit=(1, 5),
num_shadows_lower=None,
num_shadows_upper=None,
shadow_dimension=5,
always_apply=False,
p=1.0,
),
]
)
return transform(image=image)["image"]
def remove_alpha_threshold(image, alpha_threshold=160):
# This function removes artifacts created by LayerDiffusion
mask = image[:, :, 3] < alpha_threshold
image[mask] = [0, 0, 0, 0]
return image
def create_ground_truth_mask(image):
return image[:, :, 3]
def create_random_filename_from_filepath(path):
letters = string.ascii_lowercase
random_string = "".join(random.choice(letters) for i in range(13))
return random_string + "_" + os.path.basename(path)
def scale_image(image, factor=1.5):
width = int(image.shape[1] * factor)
height = int(image.shape[0] * factor)
return cv2.resize(image, (width, height), interpolation=cv2.INTER_LINEAR)
def augment_and_match_size(image, target_width, target_height):
color = [0, 0, 0, 0]
image = cv2.copyMakeBorder(
image, 200, 200, 200, 200, cv2.BORDER_CONSTANT, value=color
)
transform = A.Compose(
[
A.LongestMaxSize(max_size=max(target_width, target_height), p=1.0),
A.RandomScale(scale_limit=(-0.7, 0.5)),
A.HorizontalFlip(p=0.5),
A.ShiftScaleRotate(
shift_limit_x=(-0.3, 0.3),
shift_limit_y=(0.0, 0.5),
scale_limit=(0, 0),
rotate_limit=(-5, 5),
border_mode=cv2.BORDER_CONSTANT,
p=0.5,
),
]
)
image = transform(image=image)["image"]
# Ensure the image matches the target dimensions
current_height, current_width = image.shape[:2]
# Crop if the image is larger than the target size
if current_height > target_height or current_width > target_width:
# Calculating the top-left point to crop the image
start_x = max(0, (current_width - target_width) // 2)
start_y = max(0, (current_height - target_height) // 2)
image = image[
start_y : start_y + target_height, start_x : start_x + target_width
]
# Pad if the image is smaller than the target size
if current_height < target_height or current_width < target_width:
delta_w = max(0, target_width - current_width)
delta_h = max(0, target_height - current_height)
top, bottom = delta_h // 2, delta_h - (delta_h // 2)
left, right = delta_w // 2, delta_w - (delta_w // 2)
image = cv2.copyMakeBorder(
image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color
)
return image
def merge_images(background, foreground, position=(0, 0)):
x, y = position
fh, fw = foreground.shape[:2]
if x + fw > background.shape[1]:
fw = background.shape[1] - x
foreground = foreground[:, :fw]
if y + fh > background.shape[0]:
fh = background.shape[0] - y
foreground = foreground[:fh, :]
# Region of Interest (ROI) in the background where the foreground will be placed
roi = background[y : y + fh, x : x + fw]
# Split the foreground image into its color and alpha channels
foreground_color = foreground[:, :, :3]
alpha = foreground[:, :, 3] / 255.0
# Blend the images based on the alpha channel
for c in range(0, 3):
roi[:, :, c] = (1.0 - alpha) * roi[:, :, c] + alpha * foreground_color[:, :, c]
# Place the modified ROI back into the original image
background[y : y + fh, x : x + fw] = roi
return background
def create_training_data(
background_path, segmentation_path, image_path, ground_truth_path
):
background = cv2.imread(background_path, cv2.IMREAD_COLOR)
segmentation = cv2.imread(segmentation_path, cv2.IMREAD_UNCHANGED)
if segmentation.shape[2] < 4:
raise Exception(f"Image does not have an alpha channel: {segmentation_path}")
background = augment_background(background)
segmentation = remove_alpha_threshold(segmentation)
file_name = create_random_filename_from_filepath(segmentation_path)
image_path = os.path.join(image_path, file_name)
ground_truth_path = os.path.join(ground_truth_path, file_name)
bg_height, bg_width = background.shape[:2]
segmentation = augment_and_match_size(
segmentation, target_height=bg_height, target_width=bg_width
)
ground_truth = create_ground_truth_mask(segmentation)
result = merge_images(background, segmentation)
result = augment_final_image(result)
assert ground_truth.shape[0] == result.shape[0]
assert ground_truth.shape[1] == result.shape[1]
cv2.imwrite(ground_truth_path, ground_truth)
cv2.imwrite(image_path, result)
def main():
parser = argparse.ArgumentParser(
description="Merge two images with one image having transparency."
)
parser.add_argument(
"-b", "--background", required=True, help="Path to the background image"
)
parser.add_argument(
"-s", "--segmentation", required=True, help="Path to the segmentation image"
)
parser.add_argument(
"-im",
"--image-path",
type=str,
default="im",
help="Path where the merged image will be saved",
)
parser.add_argument(
"-gt",
"--groundtruth-path",
type=str,
default="gt",
help="Ground truth folder",
)
args = parser.parse_args()
if not os.path.exists(args.image_path):
os.makedirs(args.image_path)
if not os.path.exists(args.groundtruth_path):
os.makedirs(args.groundtruth_path)
create_training_data(
background_path=args.background,
segmentation_path=args.segmentation,
image_path=args.image_path,
ground_truth_path=args.groundtruth_path,
)
if __name__ == "__main__":
main()
|