GIF圖換臉

from PIL import Image, ImageDraw, ImageSequence
import io

im = Image.open('E:/1.gif')
im2 = Image.open('E:/2.jpg')

# 這裏正式開始
frames = []
# Loop over each frame in the animated image
for frame in ImageSequence.Iterator(im):
    # Draw the text on the frame
    d = ImageDraw.Draw(frame)
    d.text((10, 100), 'czp')
    del d

    box = (50, 0, 250, 200)
    frame = frame.convert("RGBA")
    new = im2.convert("RGBA")
    new = new.resize((box[2] - box[0], box[3] - box[1]))
    frame.paste(new, box)

    b = io.BytesIO()
    frame.save(b, format="GIF")
    frame = Image.open(b)

    # Then append the single frame image to a list of frames
    frames.append(frame)
# Save the frames as a new image

frames[0].save('E:/out.gif', save_all=True, append_images=frames[1:])


  1. 使用ImageSequence.Iterator對Gif圖進行迭代:
           (創建一個迭代器實例,循環訪問序列中的所有幀圖像

  2. 將圖片進行RGBA處理,這樣粘貼RGBA模式圖片的時候,alpha通道不會被帖上
    (即不會有透明的效果)

  3. ImageDraw.Draw:text部分爲在圖片裏寫字

  4. box爲替換區域,處理換臉部分

  5. 用一個bytes初始化BytesIO,然後,像讀文件一樣讀取,進行Gif圖片的存儲(frames)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章