一个SciPy图像处理案例的全过程

本文利用SciPy进行图像处理,并记录图像处理的全过程,处理过程包含高斯模糊、腐蚀等操作。

代码

import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage

# 设置图像的大小为 128x128,即 128x128 的逻辑像素
l = 128
# 生成的随机点的数量为 36。
n_pts = 36
# 记录图像处理过程中的图像
images_in_process = []

def generate_synthetic_data():
    """Synthetic binary data"""
    # 创建一个随机数生成器 rs,并设置种子为 0,以确保生成的随机数是可重复的。
    rs = np.random.RandomState(0)
    # 生成一个从 0 到 l 的二维网格坐标。
    x, y = np.ogrid[0:l, 0:l]
    images_in_process.append(x.copy())
    images_in_process.append(y.copy())
    # x和y计算时会产生广播机制,因此mask_outer的大小是(l,l)
    # 创建一个圆形掩码,定义在图像中心的圆形区域内的点为 True,其他点为 False。
    mask_outer = (x - l / 2.0) ** 2 + (y - l / 2.0) ** 2 < (l / 2.0) ** 2
    images_in_process.append(mask_outer.copy())
    # 初始化一个大小为 (l, l) 的全零矩阵,用于存储随机点。
    mask = np.zeros((l, l))
    # 生成 n_pts 个随机点,坐标范围在 [0, l) 之间。
    points = l * rs.rand(2, n_pts)
    # 将上一步生产的随机点在 mask 中对应的位置设置为 1。
    mask[(points[0]).astype(int), (points[1]).astype(int)] = 1
    images_in_process.append(mask.copy())
    # 对 mask 应用高斯模糊,使得随机点的边缘变得平滑。
    mask = ndimage.gaussian_filter(mask, sigma=l / n_pts)
    images_in_process.append(mask.copy())
    # 生成一个新的掩码 res,其中只有在 mask 大于其平均值且在 mask_outer 圆形区域内的点为 True。
    res = np.logical_and(mask > mask.mean(), mask_outer)
    images_in_process.append(res.copy())
    # 对 res 应用腐蚀操作,使白色前景区域变小。
    res_erosion = ndimage.binary_erosion(res)
    images_in_process.append(res.copy())
    # 异或操作会检测出白色前景区域边缘
    return np.logical_xor(res, res_erosion)

data = generate_synthetic_data()
# 绘制图像
for i in range(len(images_in_process)):
    plt.figure(figsize=(10, 5))
    plt.imshow(images_in_process[i], cmap=plt.cm.gray, interpolation="nearest")
    plt.axis("off")
    plt.title("original image")
    plt.savefig(f"original_image_{i}.png")

plt.figure(figsize=(10, 5))
plt.imshow(data, cmap=plt.cm.gray, interpolation="nearest")
plt.axis("off")
plt.title("original image")
plt.savefig(f"original_image_{len(images_in_process)}.png")

结果
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥猪猪爸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值