如何在不使用MATLAB循环的情况下比较矩阵元素与其邻居? [英] How to compare a matrix element with its neighbours without using a loop in MATLAB?

查看:276
本文介绍了如何在不使用MATLAB循环的情况下比较矩阵元素与其邻居?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MATLAB中有一个矩阵。我想检查每个元素的4个连接的邻居(左,右,上,下)。如果当前元素小于任何邻居,那么我们将其设置为零,否则它将保持其值。它可以很容易地用循环完成,但它非常昂贵,因为我有数千个这样的矩阵。

I have a matrix in MATLAB. I want to check the 4-connected neighbours (left, right, top, bottom) for every element. If the current element is less than any of the neighbours then we set it to zero otherwise it will keep its value. It can easily be done with loop, but it is very expensive as I have thousands of these matrices.

你可能会在边缘检测后将其识别为非最大值抑制。

You might recognize it as nonmaxima suppression after edge detection.

推荐答案

一种方法是使用函数图像处理工具箱的images / ref / nlfilter.htmlrel =noreferrer> NLFILTER ,将给定函数应用于矩阵的每个M-by-N块:

One way to do this is with the function NLFILTER from the Image Processing Toolbox, which applies a given function to each M-by-N block of a matrix:

>> A = magic(6)  %# A sample matrix

A =

    35     1     6    26    19    24
     3    32     7    21    23    25
    31     9     2    22    27    20
     8    28    33    17    10    15
    30     5    34    12    14    16
     4    36    29    13    18    11

>> B = nlfilter(A,[3 3],@(b) b(5)*all(b(5) >= b([2 4 6 8])))

B =

    35     0     0    26     0     0
     0    32     0     0     0    25
    31     0     0     0    27     0
     0     0     0     0     0     0
    30     0    34     0     0    16
     0    36     0     0    18     0

以上代码定义匿名函数,它使用线性索引以获取3乘3子矩阵的中心元素 b(5)并将其与其4个连接的邻居 b([2 4 6 8])进行比较。中心元素中的值乘以函数 ALL ,当中心元素大于其所有最近邻居时为1,否则为0。

The above code defines an anonymous function which uses linear indexing to get the center element of a 3-by-3 submatrix b(5) and compare it to its 4-connected neighbors b([2 4 6 8]). The value in the center element is multiplied by the logical result returned by the function ALL, which is 1 when the center element is larger than all of its nearest neighbors and 0 otherwise.

这篇关于如何在不使用MATLAB循环的情况下比较矩阵元素与其邻居?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆