Skip to content

Instantly share code, notes, and snippets.

@ZJUGuoShuai
Last active December 6, 2023 08:52
Show Gist options
  • Select an option

  • Save ZJUGuoShuai/f725721546947a178dd7e9af11dbb835 to your computer and use it in GitHub Desktop.

Select an option

Save ZJUGuoShuai/f725721546947a178dd7e9af11dbb835 to your computer and use it in GitHub Desktop.
演示如何使用 OpenCV 图像修复功能填补缺失值
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import cv2\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"def reconstruct_matrix(matrix, mask):\n",
" # Convert the matrix to an image format\n",
" image = np.float32(matrix)\n",
"\n",
" # Convert the mask to an image format\n",
" mask = np.uint8(mask)\n",
"\n",
" # Perform inpainting using the Navier-Stokes based method\n",
" filled_image = cv2.inpaint(image, mask, 3, cv2.INPAINT_TELEA)\n",
"\n",
" # Convert the filled image back to a matrix format\n",
" filled_matrix = np.array(filled_image, dtype=np.float64)\n",
"\n",
" return filled_matrix"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[1. 2. 6.97709751]\n",
" [3. 5.74754715 7. ]\n",
" [6.73858976 8. 9. ]]\n"
]
}
],
"source": [
"# 原始图像:斜对角线初值为 0,需要被复原\n",
"matrix = np.array([[1, 2.0, 0],\n",
" [3.0, 0, 7.0],\n",
" [0, 8.0, 9.0]])\n",
"\n",
"# 斜对角线是需要复原的\n",
"mask = np.array([[0, 0, 1],\n",
" [0, 1, 0],\n",
" [1, 0, 0]])\n",
"\n",
"filled_matrix = reconstruct_matrix(matrix, mask)\n",
"print(filled_matrix)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "numpy",
"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.11.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
@ZJUGuoShuai

ZJUGuoShuai commented Dec 6, 2023

Copy link
Copy Markdown
Author

主要使用了 cv.inpaint() 这个函数。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment