MATLAB: Matching original coloured images to their black and white version to remove the black parts and keep the white parts for multiple images.

Image Processing Toolboximage segmentationmasking

For example, this would be the original input image
And this would be the black and white output image that I would like to match it to.
Once that is done, id like to segment the image where it gets rid of the black and only keeps the white. At the end, it should output only the bit of the original image that matched to the white for further analysis of the cells without the background(black parts). Id also like to output these images into their own file that i can access on my desktop to look at.

Best Answer

Not exactly sure what you want, and not sure if what you think you want is really what you need. If you have the mask, then regionprops() automatically ignores the black pixels while making measurements. So matching, segmenting, and extracting (as you asked for) are NOT needed.
You cannot get rid of black pixels because an image has to remain rectangular. However, if you want to extract only the white pixels into a list (a 1-D vector) you can pass the mask in to the gray scale image as an index:
selectedPixelValues = grayImage(mask); % Vector of only gray levels within mask
If you want a masked image where the white parts show up in their original gray scale and the background is black, you can create a masked image like this:
% Mask the image using bsxfun() function to multiply the mask by each channel individually. Works for gray scale as well as RGB Color images.
maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, 'like', rgbImage));
If you want to crop off some of the black, to make a smaller image, you could, but it's not really necessary.
[r, c] = find(mask);
croppedImage = grayImage(min(r):max(r), min(c):max(c), :);