-
-
Save gsasikiran/c80c7e28fa2aa4f9df645859d806cb18 to your computer and use it in GitHub Desktop.
Creates a composite image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import glob | |
import os | |
import random | |
def create_composite_image(_fg_image , _bg_image): | |
""" | |
Creates composite images from a given set of foreground and background images | |
:param _fg_image: path to foreground images folder | |
:param _bg_image: path to background images folder | |
:return: | |
""" | |
flag = 0 | |
for plate in glob.glob(_bg_image): | |
composite_folder_name = os.path.splitext(plate)[0] + "_composite" | |
print(composite_folder_name) | |
if not os.path.exists(composite_folder_name): | |
os.makedirs(composite_folder_name) | |
for food in glob.glob(_fg_image): | |
plate_base_image = cv2.imread(plate, cv2.IMREAD_UNCHANGED) | |
plate_base_image = cv2.resize(plate_base_image, (1000, 1000)) | |
h_1, w_1 = plate_base_image.shape[:2] | |
random_size = random.randint(1, 250) | |
food_image = cv2.imread(food, cv2.IMREAD_UNCHANGED) | |
food_image = cv2.resize(food_image, (300 + random_size, 300 + random_size)) | |
h1, w1 = food_image.shape[:2] | |
b, g, r, a = cv2.split(food_image) | |
x = int((w_1 / 2) - (w1 / 2)) | |
y = int((h_1 / 2) - (h1 / 2)) | |
print(food_image.shape, plate_base_image.shape) | |
cropped_bg_image = plate_base_image[y:y + h1, x:x + w1] | |
inv_a = cv2.bitwise_not(a) | |
image1_out = cv2.bitwise_and(cropped_bg_image, cropped_bg_image, mask=inv_a) | |
image2_out = cv2.bitwise_and(food_image, food_image, mask=a) | |
image_cropped = cv2.bitwise_or(image1_out, image2_out) | |
plate_base_image[y:y + h1, x:x + w1] = image_cropped | |
cv2.imwrite(composite_folder_name + "/" + str(flag) + "_" + os.path.basename(food), plate_base_image) | |
print(composite_folder_name + "/" + str(flag) + "_" + os.path.basename(food)) | |
flag += 1 | |
def jpg2png(_jpg_folder_path): | |
for file in glob.glob(_jpg_folder_path): | |
img = cv2.imread(file) | |
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGBA) | |
cv2.imwrite(os.path.basename(file)+".png" , img) | |
if __name__ == "__main__": | |
BG_FOLDER_PATH = "/home/anirudh/HBRS/HomeLab/Dataset/dataset_green_segmentation/bg_png/*.png" | |
FG_FOLDERS_PATH = "/home/anirudh/HBRS/HomeLab/Dataset/dataset_green_segmentation/fg/*.png" | |
create_composite_image(FG_FOLDERS_PATH,BG_FOLDER_PATH) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment