简体   繁体   中英

Get frame / pattern of an image without loop MATLAB

I would like to extract certain part of an image. Let's say, only those parts that are indexed by ones, in some kind of template or frame.

GRAYPIC = reshape(randperm(169), 13, 13);
FRAME = ones(13);
FRAME(5:9, 5:9) = 0;
FRAME_OF_GRAYPIC = []; % the new pic that only shows the frame extracted

I can achieve this using a for loop:

for X = 1:13
for Y = 1:13
    vlaue = FRAME(Y, X);
    switch vlaue

        case 1
            FRAME_OF_GRAYPIC(X,Y) = GRAYPIC(X,Y)
        case 0
            FRAME_OF_GRAYPIC(X,Y) = 0
    end
end
end
imshow(mat2gray(FRAME_OF_GRAYPIC));

However, is it possible to use it with some kind of vector operation, ie:

FRAME_OF_GRAYPIC = GRAYPIC(FRAME==1);

Though, this doesn't work unfortunately.

Any suggestions?

Thanks a lot for your answers, best, Clemens

Too long for a comment...

GRAYPIC = reshape(randperm(169), 13, 13);
FRAME = zeros(13);        
FRAME(5:9, 5:9) = 0;      
FRAME_OF_GRAYPIC = zeros(size(GRAYPIC); % MUST preallocate new pic the right size
FRAME = logical(FRAME);   % ... FRAME = (FRAME == 1)
FRAME_OF_GRAYPIC(FRAME) = GRAYPIC(FRAME);

Three things to note here:

  • FRAME must be a logical array. Create it with true() / false() , or cast it using logical() , or select a value to be true using FRAME = (FRAME == true_value);
  • You must preallocate your final image to the proper dimensions, otherwise it will turn into a vector.
  • You need the image indices on both sides of the assignment:
    FRAME_OF_GRAYPIC(FRAME) = GRAYPIC(FRAME);

Output:

FRAME_OF_GRAYPIC =
    38    64   107    63    27   132   148   160    88    59   102    69    81
    14   108    76    58    49    55    51    19   158    52   100   153    39
    79   139    12   115   147   154    96   112    82    73   159   146    93
   169     2    71    25    33   149   138   150   129   117    65    97    17
    43   111    37   142     0     0     0     0     0   128    84    86    22
     9   137   127    45     0     0     0     0     0    68    28    46   163
    42    11    31    29     0     0     0     0     0   152     3    85    36
    50   110   165    18     0     0     0     0     0   144   143    44   109
   114   133     1   122     0     0     0     0     0    80   167   157   145
    24   116    60   130    53    77   156    35     6    78    90    30   140
    74   120    40    26   106   166   121    34    98    57    56    13    48
     8   155     4    16   124    75   123    23   105    66     7   141    70
    89   113    99   101    54    20    94    72    83   168    61     5    10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM