summaryrefslogtreecommitdiff
path: root/live-mogrify.py
blob: 8e71958fc6d1c3182dfc98d1cdd47e24668728e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../live-cortex/rpc/'))
from options.test_options import TestOptions
from options.dataset_options import DatasetOptions
from data import CreateRecursiveDataLoader
from models import create_model
# from util.visualizer import Visualizer
from util.util import mkdirs, crop_image
from util import html
from shutil import move, copyfile
from PIL import Image, ImageOps
from skimage.transform import resize
from scipy.misc import imresize
from shutil import copyfile, rmtree
import numpy as np
import cv2
from datetime import datetime
import re
import sys
import math
import subprocess
from time import sleep

from rpc import CortexRPC

def clamp(n,a,b):
  return max(a, min(n, b))

def lerp(n,a,b):
  return (b-a)*n+a

def load_opt():
  opt = TestOptions().parse()
  data_opt = DatasetOptions().parse(opt.unknown)
  opt.nThreads = 1   # test code only supports nThreads = 1
  opt.batchSize = 1  # test code only supports batchSize = 1
  opt.serial_batches = True  # no shuffle
  opt.no_flip = True  # no flip

  data_opt.tag = get_tag(opt, data_opt)
  opt.render_dir = opt.results_dir + opt.name + "/" + data_opt.tag + "/"
  return opt, data_opt

def get_tag(opt, data_opt):
  if data_opt.tag == '':
    d = datetime.now()
    tag = data_opt.tag = "{}_{}_{}".format(
      opt.name,
      'live',
      d.strftime('%Y%m%d%H%M')
    )
  else:
    tag = data_opt.tag
  return tag

def load_first_frame(opt, data_opt):
  start_img_path = os.path.join(opt.render_dir, "frame_00000.png")
  if data_opt.just_copy:
    copyfile(opt.start_img, start_img_path)
  else:
    print("preload {}".format(opt.start_img))
    A_img = Image.open(opt.start_img).convert('RGB')
    A_im = np.asarray(A_img)
    A = process_image(opt, data_opt, A_im)
    cv2.imwrite(start_img_path, A)

  numz = re.findall(r'\d+', os.path.basename(opt.start_img))
  print(numz)
  if len(numz) > 0:
    A_offset = int(numz[0])
    print(A_offset)
    if A_offset:
      print(">> starting offset: {}".format(A_offset))
      A_dir = opt.start_img.replace(numz[0], "{:05d}")
      print(A_dir)
    else:
      print("Sequence not found")
  return A_offset, A_im, A_dir

def process_image(opt, data_opt, im):
  img = im[:, :, ::-1].copy()
  processed = False

  if data_opt.clahe is True:
    processed = True
    lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
    l, a, b = cv2.split(lab)
    clahe = cv2.createCLAHE(clipLimit=data_opt.clip_limit, tileGridSize=(8,8))
    l = clahe.apply(l)
    limg = cv2.merge((l,a,b))
    img = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
  if data_opt.posterize is True:
    processed = True
    img = cv2.pyrMeanShiftFiltering(img, data_opt.spatial_window, data_opt.color_window)
  if data_opt.grayscale is True:
    processed = True
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  if data_opt.blur is True:
    processed = True
    img = cv2.GaussianBlur(img, (data_opt.blur_radius, data_opt.blur_radius), data_opt.blur_sigma)
  if data_opt.canny is True:
    processed = True
    img = cv2.Canny(img, data_opt.canny_lo, data_opt.canny_hi)
    img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

  if processed is False or data_opt.process_frac == 0:
    return img

  src_img = im[:, :, ::-1].copy()
  frac_a = data_opt.process_frac
  frac_b = 1.0 - frac_a
  array_a = np.multiply(src_img.astype('float64'), frac_a)
  array_b = np.multiply(img.astype('float64'), frac_b)
  img = np.add(array_a, array_b).astype('uint8')
  return img

def listen():
  opt, data_opt = load_opt()
  def set_data_opt(key, value):
    data_opt[key] = value
  def get_opts():
    return vars(data_opt)
  def activate():
    process_live_input(opt, data_opt)
  rpc_client = CortexRPC(get_opts, set_data_opt, activate)

def process_live_input(opt, data_opt):
  A_offset, A_im, A_dir = load_first_frame(opt, data_opt)
  print("load first frame")

  data_loader = CreateRecursiveDataLoader(opt)
  print("made data loader")
  dataset = data_loader.load_data()
  print("load data")
  model = create_model(opt)

  print("generating...")
  last_im = None
  for i, data in enumerate(data_loader):
    print("{}...".format(i))
    if i >= opt.how_many:
      break
    model.set_input(data)
    model.test()
    visuals = model.get_current_visuals()
    img_path = model.get_image_paths()

    if (i % 100) == 0:
      print('%04d: process image...' % (i))

    im = visuals['fake_B']
    last_path = opt.render_dir + "frame_{:05d}.png".format(i)
    tmp_path = opt.render_dir + "frame_{:05d}_tmp.png".format(i+1)
    next_path = opt.render_dir + "frame_{:05d}.png".format(i+1)
    current_path = opt.render_dir + "ren_{:05d}.png".format(i+1)
    if A_dir is not None:
      sequence_path = A_dir.format(A_offset+i+1)

    if opt.send_image == 'b':
      image_pil = Image.fromarray(im, mode='RGB')
      rpc_client.send_pil_image("frame_{:05d}.png".format(i+1), image_pil)

    if opt.store_a is not True:
      os.remove(last_path)
    if opt.store_b is True:
      image_pil = Image.fromarray(im, mode='RGB')
      image_pil.save(tmp_path)
      os.rename(tmp_path, current_path)

    if data_opt.recursive and last_im is not None:
      if data_opt.sequence and A_dir is not None:
        A_img = Image.open(sequence_path).convert('RGB')
        A_im = np.asarray(A_img)
        t = lerp(math.sin(i / data_opt.transition_period * math.pi * 2.0 ) / 2.0 + 0.5, data_opt.transition_min, data_opt.transition_max)
        frac_a = data_opt.recursive_frac * (1.0 - t)
        frac_b = data_opt.sequence_frac * (1.0 - t)
        frac_c = 1.0 - frac_a - frac_b
        array_a = np.multiply(last_im.astype('float64'), frac_a)
        array_b = np.multiply(A_im.astype('float64'), frac_b)
        array_c = np.multiply(im.astype('float64'), frac_c)
        array_ab = np.add(array_a, array_b)
        array_abc = np.add(array_ab, array_c)
        next_im = array_abc.astype('uint8')

      else:
        frac_a = data_opt.recursive_frac
        frac_b = 1.0 - frac_a
        array_a = np.multiply(last_im.astype('float64'), frac_a)
        array_b = np.multiply(im.astype('float64'), frac_b)
        next_im = np.add(array_a, array_b).astype('uint8')

      if data_opt.recurse_roll != 0:
        last_im = np.roll(im, data_opt.recurse_roll, axis=data_opt.recurse_roll_axis)
      else:
        last_im = next_im.copy().astype('uint8')

    else:
      last_im = im.copy().astype('uint8')
      next_im = im

    # image_pil = Image.fromarray(next_im, mode='RGB')
    # im = np.asarray(image_pil).astype('uint8')
    #print(im.shape, im.dtype)

    next_img = process_image(opt, data_opt, next_im)

    if opt.send_image == 'sequence':
      rpc_client.send_pil_image("frame_{:05d}.png".format(i+1), A_img)
    if opt.send_image == 'recursive':
      pil_im = Image.fromarray(next_im)
      rpc_client.send_pil_image("frame_{:05d}.png".format(i+1), pil_im)
    if opt.send_image == 'a':
      rgb_im = cv2.cvtColor(next_img, cv2.COLOR_BGR2RGB)
      pil_im = Image.fromarray(rgb_im)
      rpc_client.send_pil_image("frame_{:05d}.png".format(i+1), pil_im)

    cv2.imwrite(tmp_path, next_img)
    os.rename(tmp_path, next_path)

if __name__ == '__main__':
  listen()