{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%gui qt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Vispy Lasso\n\nDemonstrate the use of lasso selection.\n\nThe lasso selection is done on a 2D scatter but could be extended further by user.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import sys\nimport warnings\nimport numpy as np\nfrom vispy import app, scene\nfrom vispy.geometry import curves\nfrom vispy.scene import visuals\n\ntry:\n from matplotlib import path\nexcept ImportError:\n warnings.warn(\"Lasso example requires matplotlib for more accurate selection. Falling back to numpy based selection.\")\n path = None\n\nLASSO_COLOR = (1, .1, .1)\nFILTERED_COLOR = (1, 1, 1, 0.3)\nSELECTED_COLOR = (0.3, 0, 1, 1.0)\nPEN_RADIUS = 2\nMIN_MOVE_UPDATE_THRESHOLD = 5\nNUMBER_POINT = 2000000\nSCATTER_SIZE = 5\n\ncanvas = scene.SceneCanvas(keys='interactive', show=True)\nview = canvas.central_widget.add_view()\n\npointer = scene.visuals.Ellipse(center=(0., 0.), radius=(PEN_RADIUS, PEN_RADIUS,), color=None, border_width=0.2, border_color=\"white\",\n num_segments=10, parent=view.scene)\n\nlasso = scene.visuals.Line(pos=np.array([[0, 0], [0, 0]]), color = LASSO_COLOR, parent=view.scene, width = PEN_RADIUS , antialias=True)\npx, py = 0, 0\n\n# generate data\npos = 360 * np.random.normal(size=(NUMBER_POINT, 2), scale=1)\n\n# one could stop here for the data generation, the rest is just to make the\n# data look more interesting. Copied over from magnify.py\ncenters = np.random.normal(size=(NUMBER_POINT, 2), scale = 1) * 960\nindexes = np.random.normal(size=NUMBER_POINT, loc=centers.shape[0] / 2,\n scale=centers.shape[0] / 3)\nindexes = np.clip(indexes, 0, centers.shape[0] - 1).astype(int)\npos += centers[indexes]\n\n# create scatter object and fill in the data\nscatter = visuals.Markers()\npoint_color = np.full((NUMBER_POINT, 4), FILTERED_COLOR)\nselected_mask = np.full(NUMBER_POINT, False)\nscatter.set_data(pos, edge_width=0, face_color=point_color, size=SCATTER_SIZE)\n\nview.add(scatter)\n\ndef points_in_polygon(polygon, pts):\n \"\"\"Get boolean mask of points in a polygon reusing matplotlib implementation.\n \n The fallback code is based from StackOverflow answer by ``Ta946`` in this question:\n https://stackoverflow.com/questions/36399381/whats-the-fastest-way-of-checking-if-a-point-is-inside-a-polygon-in-python\n\n This is a proof of concept and depending on your use case, willingness\n to add other dependencies, and your performance needs one of the other answers\n on the above question would serve you better (ex. shapely, etc).\n \"\"\"\n # Filter vertices out of the polygon's bounding box, this serve as an early optimization whenever number of vertices\n # to filter out is huge.\n x1, x2, y1, y2 = min(polygon[:, 0]), max(polygon[:, 0]), min(polygon[:, 1]), max(polygon[:, 1])\n selection_mask = (x1 < pts[:, 0]) & (pts[:, 0] < x2) & (y1 < pts[:, 1]) & (pts[:, 1] < y2)\n pts_in_bbox = pts[selection_mask]\n\n # Select vertices inside the polygon.\n if path is not None:\n polygon = path.Path(polygon[:, :2], closed = True)\n polygon_mask = polygon.contains_points(pts_in_bbox[:, :2]) \n else:\n contour2 = np.vstack((polygon[1:], polygon[:1]))\n test_diff = contour2-polygon\n m1 = (polygon[:,1] > pts_in_bbox[:,None,1]) != (contour2[:,1] > pts_in_bbox[:,None,1])\n slope = ((pts_in_bbox[:,None,0]-polygon[:,0])*test_diff[:,1])-(test_diff[:,0]*(pts_in_bbox[:,None,1]-polygon[:,1]))\n m2 = slope == 0\n mask2 = (m1 & m2).any(-1)\n m3 = (slope < 0) != (contour2[:,1] < polygon[:,1])\n m4 = m1 & m3\n count = np.count_nonzero(m4, axis=-1)\n mask3 = ~(count%2==0)\n polygon_mask = mask2 | mask3\n\n # Return the full selection mask based on bounding box & polygon selection.\n selection_mask[np.where(selection_mask == True)] &= polygon_mask\n\n return selection_mask\n\ndef select(polygon_vertices, points):\n # Set default mask to filter everything since user selection\n # is not yet calculated.\n selected_mask = np.full((NUMBER_POINT, 4), FILTERED_COLOR)\n\n if polygon_vertices is not None:\n # Optimization: It's faster to convert lasso selection straight to visual coordinates since there's generally less vertices\n # this would speed up the processing depending on the scene.\n polygon_vertices = scatter.get_transform('canvas', 'visual').map(polygon_vertices)\n selected_mask = points_in_polygon(polygon_vertices, points)\n\n return selected_mask\n\n@canvas.connect\ndef on_mouse_press(event):\n global point_color, selected_mask\n \n if event.button == 1:\n # Reset lasso state.\n lasso.set_data(pos=np.empty((1, 2)))\n \n # Reset selected vertices to the filtered color, this would earn some time in case\n # scene contains a lot of vertices.\n point_color[selected_mask] = FILTERED_COLOR\n\n scatter.set_data(pos, edge_width=0, face_color=point_color, size=SCATTER_SIZE)\n \n@canvas.connect\ndef on_mouse_move(event):\n global pointer, px, py\n\n pp = event.pos\n\n # Optimization: to avoid too much recalculation/update we can update scene only if the mouse\n # moved a certain amount of pixel.\n if (abs(px - pp[0]) > MIN_MOVE_UPDATE_THRESHOLD or abs(py - pp[1]) > MIN_MOVE_UPDATE_THRESHOLD):\n pointer.center = pp\n if event.button == 1: \n polygon_vertices = event.trail()\n lasso.set_data(pos = np.insert(polygon_vertices, len(polygon_vertices), polygon_vertices[0], axis=0))\n px, py = pp\n\n@canvas.connect\ndef on_mouse_release(event):\n global point_color, selected_mask\n\n if event.button == 1:\n selected_mask = select(event.trail(), pos)\n\n # Set selected points with selection color\n point_color[selected_mask] = SELECTED_COLOR\n scatter.set_data(pos, edge_width=0, face_color=point_color, size=SCATTER_SIZE)\n\nif __name__ == '__main__':\n canvas.show()\n if sys.flags.interactive == 0:\n app.run()" ] } ], "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 }