MATLAB: Not getting colored image after doing BAYER RGB to RGB conversion with self written code.

bayer2rgbImage Processing Toolbox

I am reading bayer RGB (bggr) image (.png format) with imread(test1.png'). I have written a code; that based on row and column number identifies colour of individual pixel and then generates the two missing colour components by taking mean of neighbouring pixel values. And generates 3 (RGB) matrices one for each colour component. Then I am using below piece of code to create a single image with 3 (RGB) colours per pixel.
image_rgbdem = cat(3,image_rdem(:,:,1),image_gdem(:,:,2),image_bdem(:,:,3));
imwrite(image_rgbdem,'../test_images/test1_dem.png');
This errors out saying Index exceeds matrix dimensions.
If I use below code it generates the image but its monochrome.
image_rgbdem = cat(3,image_rdem,image_gdem,image_bdem);
imwrite(image_rgbdem,'../test_images/test1_dem.png');
My question:
1] Is the approach taken to concatenate 3 matrices with cat to generate single RGB image matrix correct?
2] If yes what is missing that does not give me the colour image?
If I use MATLAB demosaic function I do get the coloured image. This is my first time with MATLAB, any help is appreciated.
Thanks

Best Answer

If image_gdem and image_bdem are monochrome images, you can't access the second and third color channel of them, respectively. They are not color images so you can't use indexes like (:,:,2) and (:,:,3). Use cat like:
image_rgbdem = cat(3, image_rdem, image_gdem, image_bdem);
Related Question