{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%gui qt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Custom image sampling\n\nUse custom interpolation kernels for image sampling.\n\nPress k to switch kernel.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import sys\nfrom itertools import cycle\n\nfrom vispy import scene\nfrom vispy import app\nfrom vispy.io import load_data_file, read_png\n\nfrom scipy.signal.windows import gaussian\nfrom scipy.ndimage import gaussian_filter\nimport numpy as np\n\ncanvas = scene.SceneCanvas(keys='interactive')\ncanvas.size = 800, 600\ncanvas.show()\n\n# Set up a viewbox to display the image with interactive pan/zoom\nview = canvas.central_widget.add_view()\n\n# Load the image with a slight blur (so we can later show the sharpening filter)\nimg_data = gaussian_filter(\n read_png(load_data_file('mona_lisa/mona_lisa_sm.png')),\n sigma=1,\n)\n\n# build gaussian kernel\nsmall_gaussian_window = gaussian(5, 1)\nsmall_gaussian_kernel = np.outer(small_gaussian_window, small_gaussian_window)\n# normalize\nsmall_gaussian_kernel = small_gaussian_kernel / small_gaussian_kernel.sum()\n\n# do the same but larget and with bigger sigma\nbig_gaussian_window = gaussian(20, 10)\nbig_gaussian_kernel = np.outer(big_gaussian_window, big_gaussian_window)\nbig_gaussian_kernel = big_gaussian_kernel / big_gaussian_kernel.sum()\n\n# sharpening kernel\nsharpen_kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])\n\nkernels = {\n 'null': np.ones((1, 1)),\n 'small gaussian': small_gaussian_kernel,\n 'big gaussian': big_gaussian_kernel,\n 'sharpening': sharpen_kernel,\n}\n\nk_names = cycle(kernels.keys())\n\nk = next(k_names)\n\nimage = scene.visuals.Image(\n img_data,\n interpolation='custom',\n custom_kernel=kernels[k],\n parent=view.scene,\n)\n\ncanvas.title = f'Custom sampling with {k} kernel'\n\n# Set 2D camera (the camera will scale to the contents in the scene)\nview.camera = scene.PanZoomCamera(aspect=1)\n# flip y-axis to have correct aligment\nview.camera.flip = (0, 1, 0)\nview.camera.set_range()\n\n\n# Implement key presses\n@canvas.events.key_press.connect\ndef on_key_press(event):\n if event.key == 'k':\n k = next(k_names)\n image.custom_kernel = kernels[k]\n canvas.title = f'Custom sampling with {k} kernel'\n canvas.update()\n\n\nif __name__ == '__main__' and sys.flags.interactive == 0:\n app.run()\n print(__doc__)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.19" } }, "nbformat": 4, "nbformat_minor": 0 }