簡體   English   中英

如何使用 python 的枕頭使裁剪后的 gif 角透明?

[英]How can i make my cropped gif corners transparent with python's pillow?

我正在嘗試使用GaussianBlur過濾器編輯來自我的不和諧用戶的avatar圖像,將其裁剪為圓形並覆蓋圖像。 所以所有這些都可以工作,但是裁剪的 gif 有角落,我不想要它們。 它應該是透明的。 我搜索了很多解決方案,但找不到。 我沒有使用 python 的枕頭庫進行編碼的經驗,不知道如何修復它。

我當前的代碼對此進行了轉換(圖 1):

在此處輸入圖片說明

進入這個(圖2):

在此處輸入圖片說明

但應該是這樣的(適用於靜態圖像,但 GIF 應該在最后保留它們的動畫):

在此處輸入圖片說明

就像你可以看到我裁剪的 GIF 圖像有白角一樣。 如果 PICTURE 1 是 PNG,則它不包含它們。 那么如何去除這些白角呢?

這是我目前使用的代碼:

    def crop_center(pil_img, crop_width, crop_height):
        img_width, img_height = pil_img.size
        return pil_img.crop(((img_width - crop_width) // 2,
                             (img_height - crop_height) // 2,
                             (img_width + crop_width) // 2,
                             (img_height + crop_height) // 2))
    
    def crop_max_square(pil_img):
        return crop_center(pil_img, min(pil_img.size), min(pil_img.size))
    
    def mask_circle_transparent(pil_img, blur_radius, offset=0):
        offset = blur_radius * 2 + offset
        mask = Image.new("L", pil_img.size, 0)
        draw = ImageDraw.Draw(mask)
        draw.ellipse((offset, offset, pil_img.size[0] - offset, pil_img.size[1] - offset), fill=255)
        mask = mask.filter(ImageFilter.GaussianBlur(blur_radius))
    
        result = pil_img.copy()
        result.putalpha(mask)
    
        return result


    async def on_message(message):

       if ".gif" in str(message.author.avatar_url):

          frames = []

          gif = Image.open(BytesIO(await message.author.avatar_url.read()))

          for frame in ImageSequence.Iterator(gif):
              frame = frame.copy()
              frame = frame.convert("RGB")
              frame = frame.resize((256, 256))
              frame = mask_circle_transparent(frame, 4)

              background = background.resize((256, 256))

              frame.paste(background, (0, 0), background)
              frames.append(frame)

              print(str(frames))
              frames[0].save('temp_images/result.gif', save_all=True, append_images=frames[1:])

       else:

          im_square = crop_max_square(Image.open(BytesIO(await message.author.avatar_url.read())).convert("RGB"))
          im_square = im_square.resize((256, 256))
          im_thumb = mask_circle_transparent(im_square, 4)

          background = background.resize((256, 256))

          im_thumb.paste(background, (0, 0), background)
          im_thumb.show()

          im_thumb.save('temp_images/result.png')

編輯:我現在測試了很多,我認為frame = mask_circle_transparent(frame, 4)是這里的問題,在我調用該函數之前,我的框架是空白的,只是一個背景。 我不知道為什么。 顯然,角落不是白色的,它是圖像背景中的顏色或類似的顏色? 我不知道。

gif 不支持透明度。 要羽化/柔化 gif 上的邊緣,您可能必須使用帶有羽化邊緣的白色覆蓋層而不是蒙版。

使用 GIF 格式無法制作平滑的邊緣。 GIF 沒有 Alpha 通道,因此不支持部分透明(來源: 如何使用 GIF 獲得更好的透明度? )。 這意味着您在靜態圖像上獲得的結果無法在移動 GIF 上獲得。

但是,可以使用以下答案使 GIF 中的背景透明: 使用 Python Imageio 的 gif 中的透明背景 您可以在下面找到生成的 GIF 和實現此結果的代碼。 (我不得不跳過你代碼的一些部分,因為我沒有背景圖片和 Discord 連接)。

透明蜥蜴

from PIL import Image, ImageDraw, ImageFilter, ImageSequence
import numpy as np

def crop_center(pil_img, crop_width, crop_height):
    img_width, img_height = pil_img.size
    return pil_img.crop(((img_width - crop_width) // 2,
                         (img_height - crop_height) // 2,
                         (img_width + crop_width) // 2,
                         (img_height + crop_height) // 2))

def crop_max_square(pil_img):
    return crop_center(pil_img, min(pil_img.size), min(pil_img.size))

def mask_circle_transparent(pil_img, blur_radius, offset=0):
    offset = blur_radius * 2 + offset
    mask = Image.new("L", pil_img.size, 0)
    draw = ImageDraw.Draw(mask)
    draw.ellipse((offset, offset, pil_img.size[0] - offset, pil_img.size[1] - offset), fill=255)
    mask = mask.filter(ImageFilter.GaussianBlur(blur_radius))

    result = pil_img.copy()
    result.putalpha(mask)

    return result


def transparent_frame(im):
    # im = Image.open(path)
    alpha = im.getchannel('A')

    # Convert the image into P mode but only use 255 colors in the palette out of 256
    im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)

    # Set all pixel values below 128 to 255 , and the rest to 0
    mask = Image.eval(alpha, lambda a: 255 if a <=128 else 0)

    # Paste the color of index 255 and use alpha as a mask
    im.paste(255, mask)

    # The transparency index is 255
    im.info['transparency'] = 255

    return im


def on_message(message):

   # if ".gif" in str(message.author.avatar_url):

      frames = []

      gif = Image.open('a.gif')

      for frame in ImageSequence.Iterator(gif):
          frame = frame.copy()
          frame = frame.convert("RGB")
          frame = frame.resize((256, 256))
          frame = mask_circle_transparent(frame, 4)

          # I did not have the background image that you used, so i skipped this part
          # background = background.resize((256, 256))
          # frame.paste(background, (0, 0), background)
          
          # make transparent using the transparent_frame() function
          frame = transparent_frame(frame)
          frames.append(frame)

          # print(str(frames))
          frames[0].save('result.gif', save_all=True, append_images=frames[1:], optimize=False) # optimize must be false to preserve the transparent channel

   # else:

   #    im_square = crop_max_square(Image.open(BytesIO(await message.author.avatar_url.read())).convert("RGB"))
   #    im_square = im_square.resize((256, 256))
   #    im_thumb = mask_circle_transparent(im_square, 4)

   #    background = background.resize((256, 256))

   #    im_thumb.paste(background, (0, 0), background)
   #    im_thumb.show()

   #    im_thumb.save('temp_images/result.png')
   
if __name__ == "__main__":
    on_message('hi')

GIF 動畫由多個幀組成,您的圖像查看器循環播放這些幀以呈現視頻或動畫的效果。

因此,您需要讀取每一幀並將處理應用於它,然后傳遞要在最后保存的幀列表

這里用於讀取GIF動畫,並在這里寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM