来自3D矩阵的3D补丁 [英] 3d patches from a 3d matrix

查看:84
本文介绍了来自3D矩阵的3D补丁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3d矩阵(3x3x3),我需要提取3d补丁(2x2x2)并将其转换为矢量.

I have a 3d matrix (3x3x3), and I need to extract 3d patches (2x2x2) and transform them in vectors.

在2d中,只需:

I=randi(5,3,3);

2d_patches=im2col(I,[2 2],'sliding');

那3d呢?

I=randi(5,3,3,3);

3d_patches= ???

im2col仅适用于2d.在3d中,我应该重新组合向量1728,... 这个任务有快速功能吗?

im2col just works in 2d. In 3d I should recombine the vectors 1 and 7, 2 and 8, ... Is there any fast function for this task?

推荐答案

我不认为有任何内置方法可以做到这一点.如果需要快速,那么用c编写自己的mex函数并从Matlab调用它应该相当简单.

I do not believe that there is any built-in way to do this. If you need it to be fast, it should be fairly simple to write your own mex-function in c and call it from Matlab.

这是我的(快速而又肮脏的)解决方案:

Here is my (quick and dirty) solution:

#include <mex.h>

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
  const mxArray *I = prhs[0];
  double *indata = mxGetPr(I);
  double *patchSize = mxGetPr(prhs[1]);
  const int *size = mxGetDimensions(I);
  int J = (int)patchSize[0], K = (int)patchSize[1], H = (int)patchSize[2];
  int M = size[0],           N = size[1],           P = size[2];

  int numPatches = (M - J + 1)*(N - K + 1)*(P - H + 1);
  int out_rows = J*K*H, out_cols = numPatches;
  mxArray *out = mxCreateDoubleMatrix( out_rows, out_cols, mxREAL );
  double *outdata = mxGetPr(out);

  int patch = 0;
  for( int h_offset = 0; h_offset < P-H+1; h_offset++ ){
    for( int k_offset = 0; k_offset < N-K+1; k_offset++ ){
      for( int j_offset = 0; j_offset < M-J+1; j_offset++ ){
        int row = 0;
        for( int h = 0; h < H; h++ ){
          for( int k = 0; k < K; k++ ){
            for( int j = 0; j < J; j++ ){
              outdata[patch*out_rows + row] = 
                indata[ (j_offset+j) + (k_offset+k)*M + (h_offset+h)*M*N ];
              ++row;
            }}}
      ++patch;
      }}}
  plhs[0] = out;
}

编译:

>> mex -O CFLAGS="\$CFLAGS -std=c99 -Wall" im3col.c

测试:

>> A(:,:,1) = [1,4,7;2,5,8;3,6,9]; A(:,:,2) = [10,13,16;11,14,17;12,15,18];
>> B = im3col(A, [2,2,1])

B =

     1     2     4     5    10    11    13    14
     2     3     5     6    11    12    14    15
     4     5     7     8    13    14    16    17
     5     6     8     9    14    15    17    18

>> A(:,:,1),A(:,:,2)

ans =

     1     4     7
     2     5     8
     3     6     9


ans =

    10    13    16
    11    14    17
    12    15    18

这篇关于来自3D矩阵的3D补丁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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