せっかくグリーンスクリーン動画を見つけたので。
2017-12-15 追記: 以下参照:
ダウンロードという行為そのものが youtube の利用規約に反することを知りませんでした。(なお、ダウンロードするだけで著作権法違反となる、という話ではない。)以下一応読めるようにはしておくけれど、出来れば読まないで。
以下2つ:
これを PyAV と Pillow を使って「合成」してみる:
1 #
2 import sys
3 import argparse
4 import logging
5
6 import numpy as np
7 import av
8 from PIL import Image
9
10 if __name__ == '__main__':
11 logging.basicConfig(stream=sys.stderr, level=logging.INFO)
12 parser = argparse.ArgumentParser()
13 parser.add_argument("background")
14 parser.add_argument("greenback")
15 parser.add_argument("outfile")
16 args = parser.parse_args()
17
18 icontbg = av.open(args.background)
19 icontgb = av.open(args.greenback)
20 ivstrbg = next(s for s in icontbg.streams if s.type == b'video')
21 ivstrgb = next(s for s in icontgb.streams if s.type == b'video')
22 ocont = av.open(args.outfile, "w")
23 ovstr = ocont.add_stream(codec_name="h264", rate=ivstrbg.rate)
24 ovstr.width = ivstrbg.width
25 ovstr.height = ivstrbg.height
26 for packets in zip(icontbg.demux(ivstrbg), icontgb.demux(ivstrgb)):
27 for iframes in zip(packets[0].decode(), packets[1].decode()):
28 logging.info(iframes)
29 imgbg = iframes[0].to_image()
30 imggb = iframes[1].to_image().resize(imgbg.size)
31 keyclr = imggb.getpixel((0, 0))
32
33 r = np.array(imggb.getdata(0))
34 g = np.array(imggb.getdata(1))
35 b = np.array(imggb.getdata(2))
36 a = np.zeros(r.shape)
37 a[np.logical_and(r == keyclr[0], g == keyclr[1], b == keyclr[2])] = 255
38 alpha = Image.new("L", imggb.size)
39 alpha.putdata(a.flatten())
40 mask = imggb.copy()
41 mask.putalpha(alpha)
42
43 dimg = Image.composite(imgbg, imggb, mask)
44
45 ofr = av.VideoFrame.from_image(dimg)
46 for p in ovstr.encode(ofr):
47 ocont.mux(p)
48 ocont.close()
カラーキーって言うんだっけか、これの「一致判定」にあと一工夫必要だね。