video.py 4.92 KB
Newer Older
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
1 2
import numpy as np
import cv2
3
from time import clock
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
4 5
from numpy import pi, sin, cos
import common
6

Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
7
class VideoSynthBase(object):
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
8 9 10 11 12 13 14 15 16 17 18
    def __init__(self, size=None, noise=0.0, bg = None, **params):
        self.bg = None
        self.frame_size = (640, 480)
        if bg is not None:
            self.bg = cv2.imread(bg, 1)
            h, w = self.bg.shape[:2]
            self.frame_size = (w, h)
            
        if size is not None:
            w, h = map(int, size.split('x'))
            self.frame_size = (w, h)
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
19
            self.bg = cv2.resize(self.bg, self.frame_size)
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
20 21 22

        self.noise = float(noise)

Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
23
    def render(self, dst):
24 25
        pass
        
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
26 27 28
    def read(self, dst=None):
        w, h = self.frame_size

29 30 31 32
        if self.bg is None:
            buf = np.zeros((h, w, 3), np.uint8)
        else:
            buf = self.bg.copy()
33

Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
34
        self.render(buf)
35

Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
36
        if self.noise > 0.0:
37 38
            noise = np.zeros((h, w, 3), np.int8)
            cv2.randn(noise, np.zeros(3), np.ones(3)*255*self.noise)
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
39 40 41
            buf = cv2.add(buf, noise, dtype=cv2.CV_8UC3)
        return True, buf

42 43 44
    def isOpened(self):
        return True

Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
class Chess(VideoSynthBase):
    def __init__(self, **kw):
        super(Chess, self).__init__(**kw)

        w, h = self.frame_size

        self.grid_size = sx, sy = 10, 7
        white_quads = []
        black_quads = []
        for i, j in np.ndindex(sy, sx):
            q = [[j, i, 0], [j+1, i, 0], [j+1, i+1, 0], [j, i+1, 0]]
            [white_quads, black_quads][(i + j) % 2].append(q)
        self.white_quads = np.float32(white_quads)
        self.black_quads = np.float32(black_quads)

        fx = 0.9
        self.K = np.float64([[fx*w, 0, 0.5*(w-1)],
                        [0, fx*w, 0.5*(h-1)],
                        [0.0,0.0,      1.0]])

        self.dist_coef = np.float64([-0.2, 0.1, 0, 0])
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
66
        self.t = 0
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
67 68 69 70 71 72 73 74

    def draw_quads(self, img, quads, color = (0, 255, 0)):
        img_quads = cv2.projectPoints(quads.reshape(-1, 3), self.rvec, self.tvec, self.K, self.dist_coef) [0]
        img_quads.shape = quads.shape[:2] + (2,) 
        for q in img_quads:
            cv2.fillConvexPoly(img, np.int32(q*4), color, cv2.CV_AA, shift=2)

    def render(self, dst):
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
75 76
        t = self.t
        self.t += 1.0/30.0
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
        
        sx, sy = self.grid_size
        center = np.array([0.5*sx, 0.5*sy, 0.0])
        phi = pi/3 + sin(t*3)*pi/8
        c, s = cos(phi), sin(phi)
        ofs = np.array([sin(1.2*t), cos(1.8*t), 0]) * sx * 0.2
        eye_pos = center + np.array([cos(t)*c, sin(t)*c, s]) * 15.0 + ofs
        target_pos = center + ofs

        R, self.tvec = common.lookat(eye_pos, target_pos)
        self.rvec = common.mtx2rvec(R)

        self.draw_quads(dst, self.white_quads, (245, 245, 245))
        self.draw_quads(dst, self.black_quads, (10, 10, 10))


classes = dict(chess=Chess)
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
94

95 96 97 98 99 100 101 102
presets = dict(
    empty = 'synth:',
    lena = 'synth:bg=../cpp/lena.jpg:noise=0.1',
    chess = 'synth:class=chess:bg=../cpp/lena.jpg:noise=0.1:size=640x480'
)


def create_capture(source = 0, fallback = presets['chess']):
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
103 104 105
    '''
      source: <int> or '<int>' or '<filename>' or 'synth:<params>'
    '''
106
    cap = None
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
107 108 109
    try: source = int(source)
    except ValueError: pass
    else:
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
        cap = cv2.VideoCapture(source)
    if cap is None:
        source = str(source).strip()
        if source.startswith('synth'):
            ss = filter(None, source.split(':'))
            params = dict( s.split('=') for s in ss[1:] )
            try: Class = classes[params['class']]
            except: Class = VideoSynthBase
            try: cap = Class(**params)
            except: pass
    if cap is None:
        cap = cv2.VideoCapture(source)
    if not cap.isOpened():
        print 'Warning: unable to open video source: ', source
        if fallback is not None:
            return create_capture(fallback, None)
    return cap
127

Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
128 129
if __name__ == '__main__':
    import sys
130 131 132 133 134 135 136 137 138 139
    import getopt

    print 'USAGE: video.py [--shotdir <dir>] [source0] [source1] ...'
    print "source: '<int>' or '<filename>' or 'synth:<params>'"
    print

    args, sources = getopt.getopt(sys.argv[1:], '', 'shotdir=')
    args = dict(args)
    shotdir = args.get('--shotdir', '.')
    if len(sources) == 0:
140
        sources = [ 0 ]
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
141

142 143
    print 'Press SPACE to save current frame'

144
    caps = map(create_capture, sources)
145
    shot_idx = 0
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
146
    while True:
147 148 149 150 151
        imgs = []
        for i, cap in enumerate(caps):
            ret, img = cap.read()
            imgs.append(img)
            cv2.imshow('capture %d' % i, img)
Alexander Mordvintsev's avatar
Alexander Mordvintsev committed
152 153 154
        ch = cv2.waitKey(1)
        if ch == 27:
            break
155 156
        if ch == ord(' '):
            for i, img in enumerate(imgs):
157
                fn = '%s/shot_%d_%03d.bmp' % (shotdir, i, shot_idx)
158 159 160
                cv2.imwrite(fn, img)
                print fn, 'saved'
            shot_idx += 1