Spaces:
Runtime error
Runtime error
| import numpy as np | |
| from PIL import Image | |
| def get_bbox_from_alpha(rgba: Image.Image): | |
| arr = np.array(rgba) | |
| alpha = arr[...,3] | |
| ys, xs = np.where(alpha>0) | |
| if ys.size == 0: | |
| return None | |
| x1, x2 = xs.min(), xs.max() | |
| y1, y2 = ys.min(), ys.max() | |
| return x1, y1, x2, y2 | |
| def paste_with_alpha(bg: np.ndarray, src: np.ndarray, offset: tuple[int,int]) -> Image.Image: | |
| res = bg.copy() | |
| x, y = offset | |
| h, w = src.shape[:2] | |
| x1, y1 = max(x,0), max(y,0) | |
| x2 = min(x+w, bg.shape[1]) | |
| y2 = min(y+h, bg.shape[0]) | |
| if x1>=x2 or y1>=y2: | |
| return Image.fromarray(res) | |
| cs = src[y1-y:y2-y, x1-x:x2-x] | |
| cd = res[y1:y2, x1:x2] | |
| mask = cs[...,3]>0 | |
| if cd.shape[2]==3: | |
| cd[mask] = cs[mask][..., :3] | |
| else: | |
| cd[mask] = cs[mask] | |
| res[y1:y2, x1:x2] = cd | |
| return Image.fromarray(res) | |