Skip to content

Instantly share code, notes, and snippets.

@giswqs
Created February 7, 2025 16:05
Show Gist options
  • Save giswqs/ace1dbfac56025fb3007e681b773b35e to your computer and use it in GitHub Desktop.
Save giswqs/ace1dbfac56025fb3007e681b773b35e to your computer and use it in GitHub Desktop.
change pixel values on mouse clicks
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# %pip install ipympl\n",
"\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from ipywidgets import interact, Output\n",
"from IPython.display import display\n",
"\n",
"%matplotlib widget\n",
"\n",
"def f(i, j, img):\n",
" print(f\"Clicked on pixel: ({i}, {j})\")\n",
" img[i, j] = [1, 0, 0] # Set pixel to red. Modify as needed.\n",
" return img\n",
"\n",
"img = np.random.rand(20, 20, 3) # 100x100 RGB image. Modify as needed.\n",
"\n",
"fig, ax = plt.subplots()\n",
"ax.imshow(img)\n",
"\n",
"output = Output()\n",
"\n",
"def onclick(event):\n",
" if event.inaxes == ax:\n",
" i, j = int(round(event.ydata)), int(round(event.xdata))\n",
" with output:\n",
" global img\n",
" img = f(i, j, img) \n",
" ax.imshow(img) \n",
" fig.canvas.draw() \n",
"\n",
"cid = fig.canvas.mpl_connect('button_press_event', onclick)\n",
"\n",
"plt.show()\n",
"\n",
"display(output)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "geo",
"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.12.7"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment