如何在MATLAB中将图像分成块? [英] How to divide an image into blocks in MATLAB?
问题描述
我有256x256的图像,我想把它分成4个128x128的块,并将它们作为A1到A4进行处理。现在我想分别调用它们并对它们进行一些操作。我知道这可以使用 blkproc
函数完成 - 但究竟是怎么做的?
I have a 256x256 image and I want to divide it into 4 blocks of 128x128 each and address them as A1 to A4. Now I want to call them separately and do some operations on them. I know this can be done using the blkproc
function -- but how exactly?
我是否打电话给 blkproc
喜欢这个?
Do I call blkproc
like this?
B=blkproc(I,[4 4],?)
我应该用什么代替?,如何解决4个块创建?
What do I put in place of the "?", and how can I address the 4 blocks created?
推荐答案
自 blockproc
(以及弃用的 blkproc
)都是函数在图像处理工具箱中,我想我会添加一个基本的MATLAB解决方案,需要没有额外的工具箱......
Since blockproc
(and the deprecated blkproc
) are both functions in the Image Processing Toolbox, I thought I'd add a basic MATLAB solution that requires no additional toolboxes...
如果你想将矩阵划分为子矩阵,一种方法是使用 mat2cell
打破矩阵并存储每个子矩阵i n单元阵列的单元格。对于您的情况,语法如下所示:
If you want to divide a matrix into submatrices, one way is to use mat2cell
to break the matrix up and store each submatrix in a cell of a cell array. For your case, the syntax would look like this:
C = mat2cell(I, [128 128], [128 128]);
C
现在是2-by- 2个单元阵列,每个单元存储一个128×128的子矩阵 I
。如果要对每个单元格执行操作,则可以使用 cellfun
。例如,如果您想获取每个子矩阵中值的平均值,您将执行以下操作:
C
is now a 2-by-2 cell array with each cell storing a 128-by-128 submatrix of I
. If you want to perform an operation on each cell, you could then use the function cellfun
. For example, if you wanted to take the mean of the values in each submatrix, you would do the following:
meanValues = cellfun(@(x) mean(x(:)), C);
第一个参数是函数句柄到匿名函数,它首先将每个子矩阵重新整形为一个列向量,然后取平均值。输出是每个子矩阵的平均值的2乘2矩阵。如果传递给 cellfun
的函数为每个单元格创建不同大小或类型的输出,那么 cellfun
将出现问题连接它们并将抛出错误:
The first argument is a function handle to an anonymous function which first reshapes each submatrix into a column vector and then takes the mean. The output is a 2-by-2 matrix of the mean values for each submatrix. If the function you pass to cellfun
creates outputs of different sizes or types for each cell, then cellfun
will have a problem concatenating them and will throw an error:
??? Error using ==> cellfun
Non-scalar in Uniform output, at index 1, output 1.
Set 'UniformOutput' to false.
如果添加 ...,'UniformOutput',false);
在您调用 cellfun
结束时,上述情况下的输出将改为2乘2 单元格数组包含在每个子矩阵上执行操作的结果。
If you add ..., 'UniformOutput', false);
to the end of your call to cellfun
, then the output in the above case will instead be a 2-by-2 cell array containing the results of performing the operation on each submatrix.
这篇关于如何在MATLAB中将图像分成块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!