{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "# Plot filtering on images\n",
    "\n",
    "Demo filtering for denoising of images.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 443516 characters]",
      "text/plain": [
       "<Figure size 1200x350 with 4 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Load some data\n",
    "import scipy as sp\n",
    "\n",
    "face = sp.datasets.face(gray=True)\n",
    "face = face[:512, -512:]  # crop out square on right\n",
    "\n",
    "# Apply a variety of filters\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "# 复制并转为浮点，避免原地修改原图\n",
    "noisy_face = np.copy(face).astype(float)\n",
    "\n",
    "# 随机数发生器\n",
    "rng = np.random.default_rng()\n",
    "\n",
    "# 添加高斯噪声：强度 = 原图标准差 × 0.5\n",
    "noisy_face += face.std() * 0.5 * rng.standard_normal(face.shape)\n",
    "\n",
    "# 高斯滤波：σ=3，平滑去噪\n",
    "blurred_face = sp.ndimage.gaussian_filter(noisy_face, sigma=3)\n",
    "\n",
    "# 中值滤波：5×5 窗口，去除椒盐噪声\n",
    "median_face = sp.ndimage.median_filter(noisy_face, size=5)\n",
    "\n",
    "# 维纳滤波：5×5 窗口，自适应抑制噪声同时保留边缘\n",
    "wiener_face = sp.signal.wiener(noisy_face, (5, 5))\n",
    "\n",
    "plt.figure(figsize=(12, 3.5))\n",
    "plt.subplot(141)\n",
    "plt.imshow(noisy_face, cmap=\"gray\")\n",
    "plt.axis(\"off\")\n",
    "plt.title(\"noisy\")\n",
    "\n",
    "plt.subplot(142)\n",
    "plt.imshow(blurred_face, cmap=\"gray\")\n",
    "plt.axis(\"off\")\n",
    "plt.title(\"Gaussian filter\")\n",
    "\n",
    "plt.subplot(143)\n",
    "plt.imshow(median_face, cmap=\"gray\")\n",
    "plt.axis(\"off\")\n",
    "plt.title(\"median filter\")\n",
    "\n",
    "plt.subplot(144)\n",
    "plt.imshow(wiener_face, cmap=\"gray\")\n",
    "plt.title(\"Wiener filter\")\n",
    "plt.axis(\"off\")\n",
    "\n",
    "plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
