Pythonでカードをめくるアニメーションを作る【GIF】

  • 回転している画像を作成する
from PIL import Image
import numpy as np
import cv2

img = cv2.imread('sss10.jpg')
pts0 = np.float32([[256,256],[256,0],[0,0],[0,256]])
pts1 = np.float32([[192,236],[192,20],[64,0],[64,256]])
pts2 = np.float32(([160,216],[160,40],[96,0],[96,256]))
pts3 = np.float32([[160,256],[160,0],[96,40],[96,216]])
pts4 = np.float32(([192,256],[192,0],[64,20],[64,236]))

M1 = cv2.getPerspectiveTransform(pts0,pts1)
M2 = cv2.getPerspectiveTransform(pts0,pts2)
M8 = cv2.getPerspectiveTransform(pts0,pts3)
M9 = cv2.getPerspectiveTransform(pts0,pts4)

dst1 = cv2.warpPerspective(img,M1,(256,256),borderValue=(255,255,255))
dst2 = cv2.warpPerspective(img,M2,(256,256),borderValue=(255,255,255))
dst8 = cv2.warpPerspective(img,M8,(256,256),borderValue=(255,255,255))
dst9 = cv2.warpPerspective(img,M9,(256,256),borderValue=(255,255,255))

img = Image.new('RGB', (256, 256), (0, 0, 0))
img.save('sss5.jpg')
img = np.array(img)

M3 = cv2.getPerspectiveTransform(pts0,pts3)
M4 = cv2.getPerspectiveTransform(pts0,pts4)
M6 = cv2.getPerspectiveTransform(pts0,pts1)
M7 = cv2.getPerspectiveTransform(pts0,pts2)

dst3 = cv2.warpPerspective(img,M3,(256,256),borderValue=(255,255,255))
dst4 = cv2.warpPerspective(img,M4,(256,256),borderValue=(255,255,255))
dst6 = cv2.warpPerspective(img,M6,(256,256),borderValue=(255,255,255))
dst7 = cv2.warpPerspective(img,M7,(256,256),borderValue=(255,255,255))

cv2.imwrite('sss1.jpg', dst1)
cv2.imwrite('sss2.jpg', dst2)
cv2.imwrite('sss3.jpg', dst3)
cv2.imwrite('sss4.jpg', dst4)
cv2.imwrite('sss6.jpg', dst6)
cv2.imwrite('sss7.jpg', dst7)
cv2.imwrite('sss8.jpg', dst8)
cv2.imwrite('sss9.jpg', dst9)
  • GIFとして保存
from PIL import Image

images = []

for i in range(10):
    images.append(Image.open('sss%d.jpg'%i))

images[0].save('out.gif', save_all=True, append_images=images[1:], duration=250)
  • 結果

f:id:touch-sp:20181119172236g:plain

  • 追記

Visual Studio(C#)のユーザーフォームアプリケーションにおいてpictureBox上にGIFを表示させると無限に動く。
それを回避するためには単純に画像を順番に表示すればよい。

        bool ura1 = true;

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (ura1)
            {
                for (int i = 6; i < 11; i++)
                {
                    pictureBox1.Image = Image.FromFile("sss" + i.ToString() + ".jpg");
                    pictureBox1.Refresh();
                    Thread.Sleep(100);
                }
                ura1 = false;
            }
            else
            {
                for (int i = 1; i < 6; i++)
                {
                    pictureBox1.Image = Image.FromFile("sss" + i.ToString() + ".jpg");
                    pictureBox1.Refresh();
                    Thread.Sleep(100);
                }
                ura1 = true;
            }