MATLAB Answers

Color Imaging - RGB channe[

37 views (last 30 days)
There is a image which contains 3 color channels RGB and we should crop it and overlay them one on another to get a color image. The image is :-
I have written a code for this problem :-
img = imread('image.jpg');
[r,c] = size(img);
rr=r/3;
B=imcrop(img,[1,1,c,rr]);
G=imcrop(img,[1,1*rr,c,rr]);
R=imcrop(img,[1,2*rr,c,rr]);
ColorImg(:,:,1) = R;
ColorImg(:,:,2) = G;
ColorImg(:,:,3) = B;
imshow(ColorImg)
but I am getting an error as : -
Variable B must be of size [341 400]. It is currently of size [342 400]. Check where the variable is assigned a value.
Can you help me to know what is the error?
Thank you in advance.

  0 Comments

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 2 Jul 2020
It worked for me.
though you're forgetting to add 1 so they're misaligned vertically. Also you should never use the size function like that on unknown images without asking for the number of color channels or else if it's color, your columns will be three times too big. Also, imcrop() is a weird function. By default it wants xLeft and yTop values that are half a pixel smaller than the actual row and column you want to crop on. And the width is from pixel center to pixel center, so you'd want to subtract 1 from the number of rows and columns.
Try this corrected code:
img = imread('image.jpeg');
subplot(1, 2, 1);
imshow(img);
[rows, columns, numberOfColorChannels] = size(img)
rowsForOneImage = rows/3
fprintf('Cropping B from row %d to %d.\n', 1, rowsForOneImage);
B=imcrop(img,[1, 1, columns - 1, rowsForOneImage - 1]);
fprintf('Cropping G from row %d to %d.\n', 1*rowsForOneImage + 1, 1*rowsForOneImage + rowsForOneImage);
G=imcrop(img,[1, 1*rowsForOneImage + 1, columns - 1, rowsForOneImage - 1]);
fprintf('Cropping R from row %d to %d.\n', 2*rowsForOneImage + 1, 2*rowsForOneImage + rowsForOneImage);
R=imcrop(img,[1, 2*rowsForOneImage + 1, columns - 1, rowsForOneImage - 1]);
ColorImg(:,:,1) = R;
ColorImg(:,:,2) = G;
ColorImg(:,:,3) = B;
subplot(1, 2, 2);
imshow(ColorImg)

  1 Comment

Sachin Nath P M
Sachin Nath P M on 2 Jul 2020
Great explanation. Thank You

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 2 Jul 2020
Here's another way to do it using indexing instead of imcrop():
img = imread('image.jpeg');
subplot(1, 2, 1);
imshow(img);
[rows, columns, numberOfColorChannels] = size(img)
fprintf('Rows = %d, which means %f rows per image.\n', rows, rows/3);
row1 = [1, rows/3+1, 2*rows/3+1]
row2 = row1 + rows/3 - 1
B = img(row1(1) : row2(1), :, :);
G = img(row1(2) : row2(2), :, :);
R = img(row1(3) : row2(3), :, :);
ColorImg(:,:,1) = R;
ColorImg(:,:,2) = G;
ColorImg(:,:,3) = B;
subplot(1, 2, 2);
imshow(ColorImg)

  0 Comments

Sign in to comment.


Translated by