Datasets:
Download Test/Composition_code.py from Thinnaphat/transparent-460: direct link, hf CLI and curl.
- Browser
- Download file 2.67 kB
-
https://huggingface.co/datasets/Thinnaphat/transparent-460/resolve/main/Test/Composition_code.py
- Command line
-
hf download hf://datasets/Thinnaphat/transparent-460/Test/Composition_code.py
-
curl -L -o Composition_code.py https://huggingface.co/datasets/Thinnaphat/transparent-460/resolve/main/Test/Composition_code.py
2.67 kB
| ############################################################## | |
| #Set your paths here | |
| #path to provided foreground images | |
| fg_path = "fg" | |
| #path to provided alpha mattes | |
| a_path = "alpha" | |
| #Path to background images | |
| bg_path = "bg" | |
| #Path to folder where you want the composited images to go | |
| out_path = "composited_images" | |
| fg_files = [line.rstrip('\n') for line in open('./transparent-460-test-fg-names.txt')] | |
| bg_files = [line.rstrip('\n') for line in open('./transparent-460-test-bg-names.txt')] | |
| ############################################################## | |
| from PIL import Image | |
| import os | |
| import math | |
| import time | |
| def composite4(fg, bg, a, w, h): | |
| bbox = fg.getbbox() | |
| bg = bg.crop((0,0,w,h)) | |
| fg_list = fg.load() | |
| bg_list = bg.load() | |
| a_list = a.load() | |
| for y in range(h): | |
| for x in range (w): | |
| alpha = a_list[x,y][0] / 255 | |
| t = fg_list[x,y][0] | |
| t2 = bg_list[x,y][0] | |
| if alpha >= 1: | |
| r = int(fg_list[x,y][0]) | |
| g = int(fg_list[x,y][1]) | |
| b = int(fg_list[x,y][2]) | |
| bg_list[x,y] = (r, g, b, 255) | |
| elif alpha > 0: | |
| r = int(alpha * fg_list[x,y][0] + (1-alpha) * bg_list[x,y][0]) | |
| g = int(alpha * fg_list[x,y][1] + (1-alpha) * bg_list[x,y][1]) | |
| b = int(alpha * fg_list[x,y][2] + (1-alpha) * bg_list[x,y][2]) | |
| bg_list[x,y] = (r, g, b, 255) | |
| return bg | |
| num_bgs = 20 | |
| bg_iter = iter(bg_files) | |
| num = 0 | |
| for im_name in fg_files: | |
| im = Image.open(os.path.join(fg_path, im_name)) | |
| a = Image.open(os.path.join(a_path, im_name.split(".")[0]+".png")) | |
| bbox = im.size | |
| w = bbox[0] | |
| h = bbox[1] | |
| if im.mode != 'RGB' and im.mode != 'RGBA': | |
| im = im.convert('RGB') | |
| bcount = 0 | |
| for i in range(num_bgs): | |
| bg_name = next(bg_iter) | |
| bg = Image.open(os.path.join(bg_path, bg_name)) | |
| if bg.mode != 'RGB': | |
| bg = bg.convert('RGB') | |
| bg_bbox = bg.size | |
| bw = bg_bbox[0] | |
| bh = bg_bbox[1] | |
| wratio = w / bw | |
| hratio = h / bh | |
| ratio = wratio if wratio > hratio else hratio | |
| if ratio > 1: | |
| bg = bg.resize((math.ceil(bw*ratio),math.ceil(bh*ratio)), Image.BICUBIC) | |
| out = composite4(im, bg, a, w, h) | |
| out.save(out_path + im_name[:len(im_name)-4] + '_' + str(bcount) + '.png', "PNG") | |
| print(out_path + im_name[:len(im_name)-4] + '_' + str(bcount) + '.png') | |
| bcount += 1 | |
| print("Finished") | |