Search code examples
imagematlabmatrixbinarydivide

Dividing an image into two non-rectangular non-square sub-image in matlab


Assume that I have an image like this: http://www.mathworks.com/help/releases/R2015a/examples/images/BasicImageImportProcessingAndExportExample_03.png

(It is original image in matlab pout.tif)

And help image (binary mask) like this: http://upload7.ir/uploads//df17be22203e3099ba0d86e7cb203477bc909244.jpg

(With the same size of the original image)

I wrote this simple code for dividing the original image into two images:

I=imread('pout.tif');
figure,imshow(I),title('original image')

Ih=imread('helpPic.jpg');
Ih=rgb2gray(Ih);
Ih=im2bw(Ih);
figure,
imshow(Ih),title('help image')

im1=I.*uint8(Ih);
figure,
imshow(im1),title('im1')

im2=I.*uint8(1-Ih);
figure,
imshow(im2),title('im2')

And results:

http://upload7.ir/uploads//12f09dde101cd4c98b53fcc0d400be87029ee07a.png

And know I want to implement Otsu's method to binarize this sub images(im1 and im2), How can I implement otsu's method only on part with information (non zero part of sub images) ?


Solution

  • The graythresh function in the Image Processing Toolbox implements Otsu's method. Furthermore, as Otsu's method only cares about the values of the pixels and not their position, you can rearrange the pixels of interest in a one-dimentional array before applying graythresh.

    In pratice, this gives the -compact- following code :

    level1 = graythresh(I(Ih(:)));
    level2 = graythresh(I(~Ih(:)));
    

    Best,