Skip to content

Commit

Permalink
Merge pull request kohya-ss#1619 from emcmanus/patch-1
Browse files Browse the repository at this point in the history
Retain alpha in `pil_resize` for `--alpha_mask`
  • Loading branch information
kohya-ss authored Sep 20, 2024
2 parents 583d4a4 + de4bb65 commit 95ff9db
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions library/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,13 +305,20 @@ def _convert_float8(byte_tensor, dtype_str, shape):
raise ValueError(f"Unsupported float8 type: {dtype_str} (upgrade PyTorch to support float8 types)")

def pil_resize(image, size, interpolation=Image.LANCZOS):
pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
has_alpha = image.shape[2] == 4 if len(image.shape) == 3 else False

if has_alpha:
pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGRA2RGBA))
else:
pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

# use Pillow resize
resized_pil = pil_image.resize(size, interpolation)

# return cv2 image
resized_cv2 = cv2.cvtColor(np.array(resized_pil), cv2.COLOR_RGB2BGR)
# Convert back to cv2 format
if has_alpha:
resized_cv2 = cv2.cvtColor(np.array(resized_pil), cv2.COLOR_RGBA2BGRA)
else:
resized_cv2 = cv2.cvtColor(np.array(resized_pil), cv2.COLOR_RGB2BGR)

return resized_cv2

Expand Down

0 comments on commit 95ff9db

Please sign in to comment.