SciPy 库中maximum_filter配合generate_binary_structure获取局部极大值

SciPy 库中maximum_filter配合generate_binary_structure获取局部极大值

介绍

maximum_filter用法

maximum_filter 是 SciPy 库中的一个函数,它用于计算图像的最大值滤波。这个函数在图像处理中经常被用到,特别是在特征提取和边缘检测等任务中。

使用方法如下:

python 复制代码
import scipy.ndimage
filtered_image = scipy.ndimage.maximum_filter(input, size, footprint, output, mode, cval, origin)

参数:

  • input: 输入的 ndarray 。将应用滤波器的输入图像或数据。
  • size: 标量或元组,可选。定义滤波器窗口的大小。如果是一个标量,那么这将是每个维度的大小。如果是一个元组,那么这将指定每个维度的大小。
  • footprint: 布尔数组,可选。定义滤波器的形状,如果提供了 footprint , size 参数将被忽略。
  • output: ndarray ,可选。用于放置输出的数组。必须与输入具有相同的形状和缓冲区。
  • mode: {'reflect','constant','nearest','mirror', 'wrap'},可选。定义如何处理边界。默认值为 'reflect'。
  • cval: 标量,可选。如果 mode 是 'constant' ,这个值将用于填充。默认值为 0.0 。
  • origin: 标量或元组,可选。定义滤波器的原点。

返回值:

  • result: ndarray 。滤波后的输出。

generate_binary_structure 用法

generate_binary_structure 是 SciPy 库中的一个函数,用于生成具有给定结构元素的二进制结构。这个函数主要用于图像处理和形态学操作。

使用方法如下:

python 复制代码
import scipy.ndimage
struct = scipy.ndimage.generate_binary_structure(rank, connectivity)

参数:

  • rank: 整数,定义生成的结构元素的维数。例如,对于二维图像,排名将是2。
  • connectivity: 整数,定义像素之间的最大连接性。例如,对于二维图像,连接性为1意味着一个像素仅与其上下左右的像素连接,而连接性为2则意味着一个像素与其周围8个像素(包括对角线)都连接。

返回值:

  • output: 一个布尔数组,形状为 (2*connectivity+1,)*rank ,其中 True 表示结构元素的中心,False 表示它的背景。

例如,生成一个二维的结构元素,其连接性为1:

python 复制代码
import scipy.ndimage
struct = scipy.ndimage.generate_binary_structure(2, 1)
print(struct)

输出将是:

复制代码
[[False  True False]
 [ True  True  True]
 [False  True False]]

在这个例子中,中心像素与其上下左右的像素连接,但不与对角线像素连接。

示例代码

此代码片段摘自OpenPose项目:

python 复制代码
def find_peaks(param, img):
    """
    Given a (grayscale) image, find local maxima whose value is above a given
    threshold (param['thre1'])
    :param img: Input image (2d array) where we want to find peaks
    :return: 2d np.array containing the [x,y] coordinates of each peak found
    in the image
    """

    peaks_binary = (maximum_filter(img, footprint=generate_binary_structure(
        						   2, 1)) == img) * (img > param)
    # Note reverse ([::-1]): we return [[x y], [x y]...] instead of [[y x], [y
    # x]...]
    return np.array(np.nonzero(peaks_binary)[::-1]).T
相关推荐
IT_陈寒4 分钟前
一文搞懂React的核心概念
前端·人工智能·后端
“AI国潮设计-小江”5 分钟前
《【AIGC实战】Python+SDXL批量生成“猫咪英歌舞蛋挞”IP,附保持角色一致性的代码逻辑》
开发语言·人工智能·python·prompt·aigc
艾莉丝努力练剑13 分钟前
【AI大模型接入SDK】ChatServer HTTP接口模块实现总览
网络·c++·人工智能·网络协议·学习·http·架构
Purple Coder17 分钟前
参考论文汇总
人工智能
tq108622 分钟前
从信息到生产力
人工智能
袁俪23 分钟前
具身智能环境交互
人工智能
m4Rk_26 分钟前
【论文阅读】Agent 记忆机制(103):Dynamic Coding Memory——记忆为何让 Agent 更可靠,却可能更平庸
论文阅读·人工智能·学习·开源·github
回眸&啤酒鸭31 分钟前
【回眸】Jockey By TwelveLabs 视频智能体应用场景大纲
人工智能
小虎AI生活32 分钟前
ChatGPT 浏览器扩展升级详解:装扩展、给权限、派第一个活(附可抄话术)
人工智能·chatgpt·超级个体·一人公司·青玥ai