MATLAB: Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.

imageimage processingMATLAB and Simulink Student Suite

I am trying to crop an image in 3 based on rows and then superimpose them on top of each other.
The number of rows are 1023 and number of columns are 1200. Accordingly, I am able to crop the images in 3 parts of size 341x400x3.
While concatenating, I am getting the mentioned error.
%Read the image
img = imread('G:\Computer Vision Basics\image.jpg');
%Get the size (rows and columns) of the image
[r,c] = size(img);
rr = r/3;
%Split the image into three equal parts and store them in B, G, R channels
B=imcrop(img,[0,1,c,(rr - 1)]);
G=imcrop(img,[1,1*rr,c,(rr - 1)]);
R=imcrop(img,[1,2*rr,c,(rr - 1)]);
%concatenate R,G,B channels and assign the RGB image to ColorImg variable
ColorImg(:,:,1) = R;
ColorImg(:,:,2) = G;
ColorImg(:,:,3) = B;
imshow(ColorImg)
I am getting the following error. Any help would be really useful as I am new to MATLAB.
Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.
Error in Week2 (line 15)
ColorImg(:,:,1) = R;
Thank you

Best Answer

  1. jpg images are almost always RGB images (even when they look gray), so your imcrop() are probably returning RGB images, but you are trying to store the rgb image into a single bit plane
  2. Your images might not have the number of rows exactly divisible by 3. That leads to one of the three cropped images having a different size
  3. Unless you know for sure than an image is grayscale or pseudocolor, do not use [r,c] = size(img); and instead use r=size(img,1); c = size(img,2); or use [r,c,p] = size(img) (after which p will be the number of color planes: 1 for grayscale, 3 for RGB).