visualize.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. from fastai.core import *
  2. from fastai.vision import *
  3. from matplotlib.axes import Axes
  4. from matplotlib.figure import Figure
  5. from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
  6. from .filters import IFilter, MasterFilter, ColorizerFilter
  7. from .generators import gen_inference_deep, gen_inference_wide
  8. from IPython.display import display
  9. from tensorboardX import SummaryWriter
  10. from scipy import misc
  11. from PIL import Image
  12. import ffmpeg
  13. import youtube_dl
  14. class ModelImageVisualizer():
  15. def __init__(self, filter:IFilter, results_dir:str=None):
  16. self.filter = filter
  17. self.results_dir=None if results_dir is None else Path(results_dir)
  18. def _open_pil_image(self, path:Path)->Image:
  19. return PIL.Image.open(path).convert('RGB')
  20. def plot_transformed_image(self, path:str, figsize:(int,int)=(20,20), render_factor:int=None)->Image:
  21. path = Path(path)
  22. result = self.get_transformed_image(path, render_factor)
  23. orig = self._open_pil_image(path)
  24. fig,axes = plt.subplots(1, 2, figsize=figsize)
  25. self._plot_image(orig, axes=axes[0], figsize=figsize)
  26. self._plot_image(result, axes=axes[1], figsize=figsize)
  27. if self.results_dir is not None:
  28. self._save_result_image(path, result)
  29. def _save_result_image(self, source_path:Path, image:Image):
  30. result_path = self.results_dir/source_path.name
  31. image.save(result_path)
  32. def get_transformed_image(self, path:Path, render_factor:int=None)->Image:
  33. orig_image = self._open_pil_image(path)
  34. filtered_image = self.filter.filter(orig_image, orig_image, render_factor=render_factor)
  35. return filtered_image
  36. def _plot_image(self, image:Image, axes:Axes=None, figsize=(20,20)):
  37. if axes is None:
  38. _,axes = plt.subplots(figsize=figsize)
  39. axes.imshow(np.asarray(image)/255)
  40. axes.axis('off')
  41. def _get_num_rows_columns(self, num_images:int, max_columns:int)->(int,int):
  42. columns = min(num_images, max_columns)
  43. rows = num_images//columns
  44. rows = rows if rows * columns == num_images else rows + 1
  45. return rows, columns
  46. class VideoColorizer():
  47. def __init__(self, vis:ModelImageVisualizer):
  48. self.vis=vis
  49. workfolder = Path('./video')
  50. self.source_folder = workfolder/"source"
  51. self.bwframes_root = workfolder/"bwframes"
  52. self.audio_root = workfolder/"audio"
  53. self.colorframes_root = workfolder/"colorframes"
  54. self.result_folder = workfolder/"result"
  55. def _purge_images(self, dir):
  56. for f in os.listdir(dir):
  57. if re.search('.*?\.jpg', f):
  58. os.remove(os.path.join(dir, f))
  59. def _get_fps(self, source_path: Path)->float:
  60. probe = ffmpeg.probe(str(source_path))
  61. stream_data = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
  62. avg_frame_rate = stream_data['avg_frame_rate']
  63. fps_num=avg_frame_rate.split("/")[0]
  64. fps_den = avg_frame_rate.rsplit("/")[1]
  65. return round(float(fps_num)/float(fps_den))
  66. def _download_video_from_url(self, source_url, source_path:Path):
  67. if source_path.exists(): source_path.unlink()
  68. ydl_opts = {
  69. 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4',
  70. 'outtmpl': str(source_path)
  71. }
  72. with youtube_dl.YoutubeDL(ydl_opts) as ydl:
  73. ydl.download([source_url])
  74. def _extract_raw_frames(self, source_path:Path):
  75. bwframes_folder = self.bwframes_root/(source_path.stem)
  76. bwframe_path_template = str(bwframes_folder/'%5d.jpg')
  77. bwframes_folder.mkdir(parents=True, exist_ok=True)
  78. self._purge_images(bwframes_folder)
  79. ffmpeg.input(str(source_path)).output(str(bwframe_path_template), format='image2', vcodec='mjpeg', qscale=0).run(capture_stdout=True)
  80. def _colorize_raw_frames(self, source_path:Path):
  81. colorframes_folder = self.colorframes_root/(source_path.stem)
  82. colorframes_folder.mkdir(parents=True, exist_ok=True)
  83. self._purge_images(colorframes_folder)
  84. bwframes_folder = self.bwframes_root/(source_path.stem)
  85. for img in progress_bar(os.listdir(str(bwframes_folder))):
  86. img_path = bwframes_folder/img
  87. if os.path.isfile(str(img_path)):
  88. color_image = self.vis.get_transformed_image(str(img_path))
  89. color_image.save(str(colorframes_folder/img))
  90. def _build_video(self, source_path:Path):
  91. result_path = self.result_folder/source_path.name
  92. colorframes_folder = self.colorframes_root/(source_path.stem)
  93. colorframes_path_template = str(colorframes_folder/'%5d.jpg')
  94. result_path.parent.mkdir(parents=True, exist_ok=True)
  95. if result_path.exists(): result_path.unlink()
  96. fps = self._get_fps(source_path)
  97. ffmpeg.input(str(colorframes_path_template), format='image2', vcodec='mjpeg', framerate=str(fps)) \
  98. .output(str(result_path), crf=17, vcodec='libx264') \
  99. .run(capture_stdout=True)
  100. print('Video created here: ' + str(result_path))
  101. def colorize_from_url(self, source_url, file_name:str):
  102. source_path = self.source_folder/file_name
  103. self._download_video_from_url(source_url, source_path)
  104. self._colorize_from_path(source_path)
  105. def colorize_from_file_name(self, file_name:str):
  106. source_path = self.source_folder/file_name
  107. self._colorize_from_path(source_path)
  108. def _colorize_from_path(self, source_path:Path):
  109. self._extract_raw_frames(source_path)
  110. self._colorize_raw_frames(source_path)
  111. self._build_video(source_path)
  112. def get_video_colorizer2(root_folder:Path=Path('./'), weights_name:str='ColorizeVideos_gen2',
  113. results_dir = 'result_images', render_factor:int=36)->VideoColorizer:
  114. learn = gen_inference_wide(root_folder=root_folder, weights_name=weights_name, arch=models.resnet101)
  115. filtr = MasterFilter([ColorizerFilter(learn=learn)], render_factor=render_factor)
  116. vis = ModelImageVisualizer(filtr, results_dir=results_dir)
  117. return VideoColorizer(vis)
  118. def get_video_colorizer(root_folder:Path=Path('./'), weights_name:str='ColorizeVideos_gen',
  119. results_dir = 'result_images', render_factor:int=21, nf_factor:float=1.25)->VideoColorizer:
  120. learn = gen_inference_deep(root_folder=root_folder, weights_name=weights_name, nf_factor=nf_factor)
  121. filtr = MasterFilter([ColorizerFilter(learn=learn)], render_factor=render_factor)
  122. vis = ModelImageVisualizer(filtr, results_dir=results_dir)
  123. return VideoColorizer(vis)
  124. def get_image_colorizer(root_folder:Path=Path('./'), weights_name:str='ColorizeImages_gen',
  125. results_dir = 'result_images', render_factor:int=21, arch=models.resnet34)->ModelImageVisualizer:
  126. learn = gen_inference_wide(root_folder=root_folder, weights_name=weights_name, arch=arch)
  127. filtr = MasterFilter([ColorizerFilter(learn=learn)], render_factor=render_factor)
  128. vis = ModelImageVisualizer(filtr, results_dir=results_dir)
  129. return vis