{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "name": "external_colab_snippets.ipynb", "provenance": [], "collapsed_sections": [], "authorship_tag": "ABX9TyOxy808kK8BaGpbAJIS/ysk" }, "kernelspec": { "name": "python3", "display_name": "Python 3" } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "BEtkjazZ1B2d" }, "source": [ "#[selforg] External Colab boilerplate\n", "\n" ] }, { "cell_type": "code", "metadata": { "id": "XsDXlkau1Aoa" }, "source": [ "#@title Imports and Notebook Utilities\n", "import os\n", "import io\n", "import PIL.Image, PIL.ImageDraw\n", "import base64\n", "import zipfile\n", "import json\n", "import requests\n", "import numpy as np\n", "import matplotlib.pylab as pl\n", "import glob\n", "from functools import partial\n", "\n", "from IPython.display import Image, HTML, Markdown, clear_output\n", "from tqdm.notebook import trange, tqdm\n", "\n", "\n", "os.environ['FFMPEG_BINARY'] = 'ffmpeg'\n", "import moviepy.editor as mvp\n", "from moviepy.video.io.ffmpeg_writer import FFMPEG_VideoWriter\n", "\n", "\n", "def imread(url, max_size=None, mode=None):\n", " if url.startswith(('http:', 'https:')):\n", " # wikimedia requires a user agent\n", " headers = {\n", " \"User-Agent\": \"Requests in Colab/0.0 (https://colab.research.google.com/; no-reply@google.com) requests/0.0\"\n", " }\n", " r = requests.get(url, headers=headers)\n", " f = io.BytesIO(r.content)\n", " else:\n", " f = url\n", " img = PIL.Image.open(f)\n", " if max_size is not None:\n", " img.thumbnail((max_size, max_size), PIL.Image.ANTIALIAS)\n", " if mode is not None:\n", " img = img.convert(mode)\n", " img = np.float32(img)/255.0\n", " return img\n", "\n", "def np2pil(a):\n", " if a.dtype in [np.float32, np.float64]:\n", " a = np.uint8(np.clip(a, 0, 1)*255)\n", " return PIL.Image.fromarray(a)\n", "\n", "def imwrite(f, a, fmt=None):\n", " a = np.asarray(a)\n", " if isinstance(f, str):\n", " fmt = f.rsplit('.', 1)[-1].lower()\n", " if fmt == 'jpg':\n", " fmt = 'jpeg'\n", " f = open(f, 'wb')\n", " np2pil(a).save(f, fmt, quality=95)\n", "\n", "def imencode(a, fmt='jpeg'):\n", " a = np.asarray(a)\n", " if len(a.shape) == 3 and a.shape[-1] == 4:\n", " fmt = 'png'\n", " f = io.BytesIO()\n", " imwrite(f, a, fmt)\n", " return f.getvalue()\n", "\n", "def im2url(a, fmt='jpeg'):\n", " encoded = imencode(a, fmt)\n", " base64_byte_string = base64.b64encode(encoded).decode('ascii')\n", " return 'data:image/' + fmt.upper() + ';base64,' + base64_byte_string\n", "\n", "def imshow(a, fmt='jpeg', id=None):\n", " return display(Image(data=imencode(a, fmt)), display_id=id)\n", "\n", "def grab_plot(close=True):\n", " \"\"\"Return the current Matplotlib figure as an image\"\"\"\n", " fig = pl.gcf()\n", " fig.canvas.draw()\n", " img = np.array(fig.canvas.renderer._renderer)\n", " a = np.float32(img[..., 3:]/255.0)\n", " img = np.uint8(255*(1.0-a) + img[...,:3] * a) # alpha\n", " if close:\n", " pl.close()\n", " return img\n", "\n", "def tile2d(a, w=None):\n", " a = np.asarray(a)\n", " if w is None:\n", " w = int(np.ceil(np.sqrt(len(a))))\n", " th, tw = a.shape[1:3]\n", " pad = (w-len(a))%w\n", " a = np.pad(a, [(0, pad)]+[(0, 0)]*(a.ndim-1), 'constant')\n", " h = len(a)//w\n", " a = a.reshape([h, w]+list(a.shape[1:]))\n", " a = np.rollaxis(a, 2, 1).reshape([th*h, tw*w]+list(a.shape[4:]))\n", " return a\n", "\n", "def zoom(img, scale=4):\n", " img = np.repeat(img, scale, 0)\n", " img = np.repeat(img, scale, 1)\n", " return img\n", "\n", "class VideoWriter:\n", " def __init__(self, filename='_autoplay.mp4', fps=30.0, **kw):\n", " self.writer = None\n", " self.params = dict(filename=filename, fps=fps, **kw)\n", "\n", " def add(self, img):\n", " img = np.asarray(img)\n", " if self.writer is None:\n", " h, w = img.shape[:2]\n", " self.writer = FFMPEG_VideoWriter(size=(w, h), **self.params)\n", " if img.dtype in [np.float32, np.float64]:\n", " img = np.uint8(img.clip(0, 1)*255)\n", " if len(img.shape) == 2:\n", " img = np.repeat(img[..., None], 3, -1)\n", " self.writer.write_frame(img)\n", "\n", " def close(self):\n", " if self.writer:\n", " self.writer.close()\n", "\n", " def __enter__(self):\n", " return self\n", "\n", " def __exit__(self, *kw):\n", " self.close()\n", " if self.params['filename'] == '_autoplay.mp4':\n", " self.show()\n", "\n", " def show(self, **kw):\n", " self.close()\n", " fn = self.params['filename']\n", " display(mvp.ipython_display(fn, **kw))\n", "\n", "\n", "class LoopWriter(VideoWriter):\n", " def __init__(self, *a, cross_len=1.0, **kw):\n", " super().__init__(*a, **kw)\n", " self._intro = []\n", " self._outro = []\n", " self.cross_len = int(cross_len*self.params['fps'])\n", "\n", " def add(self, img):\n", " if len(self._intro) < self.cross_len:\n", " self._intro.append(img)\n", " return\n", " self._outro.append(img)\n", " if len(self._outro) > self.cross_len:\n", " super().add(self._outro.pop(0))\n", " \n", " def close(self):\n", " for t in np.linspace(0, 1, len(self._intro)):\n", " img = self._intro.pop(0)*t + self._outro.pop(0)*(1.0-t)\n", " super().add(img)\n", " super().close()" ], "execution_count": 2, "outputs": [] }, { "cell_type": "code", "source": [ "" ], "metadata": { "id": "54dpVXab6jcw" }, "execution_count": null, "outputs": [] } ] }