How can I rearrange the RGB planes of an image in MATLAB 7.9 (R2009b)?
Show older comments
I would like to reorder the color planes of an RGB image. Note that this has no effect on the image dimensions. This only changes the image coloring.
Accepted Answer
More Answers (1)
Why does this question exist for this specific version? Why does that answer exist? Did I miss something?
So you want to permute the channels of an image? You don't need to write a huge clumsy thing to do it -- not in R2009b or any version. Just permute the channels.
% an RGB image
A = imread('peppers.png');
% a specified channel order
chanorder = [3 2 1];
% permute the channels
B = A(:,:,chanorder);
% concatenate the results for compact display
imshow([A B])
While imshow() creates an IPT dependency in older versions, the method of permuting channels should not depend on anything. This works from R2022b to R2009b, and while I don't have anything older than R2009b, I don't know why it wouldn't work in prior versions as well. It's basic array indexing.
If you want to replicate the behavior of the function in the accepted answer:
% an RGB image
A = imread('peppers.png');
% a specified channel order
chanorder = 'bgr';
% permute the channels
B = permutechans(A,chanorder);
% concatenate the results for compact display
imshow([A B])
function outpict = permutechans(inpict,orderstr)
% strip spaces and force lowercase
orderstr = lower(orderstr(orderstr~=' '));
% if you want to require the output to be 3 channels
if numel(orderstr) < 3
error('not enough output channels specified')
end
orderstr = orderstr(1:3); % just discard any extras
% get the order from the string
[valid order] = ismember(orderstr,'rgb');
if ~all(valid)
error('expected channel designations to be one of the following: r, g, b')
end
% permute the array
outpict = inpict(:,:,order);
end
This will do the same without all the repeated code, and since it's class-agnostic, it will actually work with non-uint8 images without destroying them. Again, all of the tools used here predate R2006a.
Categories
Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
