Skip to content

Commit

Permalink
retain alpha in pil_resize backport kohya-ss#1619
Browse files Browse the repository at this point in the history
  • Loading branch information
kohya-ss committed Sep 23, 2024
1 parent 0b7927e commit 29177d2
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 @@ -83,13 +83,20 @@ def setup_logging(args=None, log_level=None, reset=False):


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 29177d2

Please sign in to comment.