How can I find and replace a pattern inside a matrix

1 次查看(过去 30 天)
I have a binary matrix with large zones of white "1". I need to crop the white zones by one pixel. For example
A =[
0 0 0 0 0 ;
0 1 1 1 0 ;
0 1 1 1 0 ;
0 1 1 1 0 ;
0 1 1 1 0 ;
0 0 0 0 0 ;
]
then after
B = crop1white(A)
B =[
0 0 0 0 0 ;
0 0 0 0 0 ;
0 0 1 0 0 ;
0 0 1 0 0 ;
0 0 0 0 0 ;
0 0 0 0 0 ;
]
I was thinking in doing something like find(01) and then at the index changing the value. However I have the feeling this is not the best way to proceed.

采纳的回答

Thorsten
Thorsten 2015-5-21
The is the morphological operation 'erode' on black-and-white images. If you have the image processing toolbox, you can use
B = bwmorph(A, 'erode')

更多回答(1 个)

Joseph Cheng
Joseph Cheng 2015-5-21
Well in the case that you do not have the image processing toolbox
A =[
0 0 0 0 0 ;
0 0 1 1 0 ;
0 1 1 1 0 ;
0 1 1 0 0 ;
0 0 1 1 0 ;
0 0 0 0 0 ;
];
B = ones(3,3)/9;
B=conv2(A,B,'same');
B(B<.75)=0;
B(B>=.75)=1
so by using the convolution we can determine the edges or portions of the center. Then by adjusting the threshold in the last two lines you can figure out how many 1's need to be in the rolling 3x3 window before the center value changes to a 1 or 0.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by