# Code explanation (bw)

3 views (last 30 days)
nurul atikah mohd sharif on 15 Nov 2021
Commented: yanqi liu on 16 Nov 2021
Any one know what is the meaning of this coding?
imageOutR(bw2(:)~=0) = Ro(bw2(:)~=0);
imageOutG(bw2(:)~=0) = Go(bw2(:)~=0);
imageOutB(bw2(:)~=0) = Bo(bw2(:)~=0);
Dccc = cat(3,imageOutR,imageOutG,imageOutB);
how to explain this code?
imageOutR(bw2(:)~=0) = Ro(bw2(:)~=0);

Image Analyst on 15 Nov 2021
It's someone (not a super skilled MATLAB programmer evidently) trying to take part of R, G, and B images that are defined by a mask (logical, binary image), bw2, and put them into different R, G, and B images, which they then concatenate into an RGB image called Dcc. It could be written simpler as:
imageOutR(bw2) = Ro(bw2); % Paste Red image inside bw2 onto imageOutR
imageOutG(bw2) = Go(bw2); % Paste Green image inside bw2 onto imageOutG
imageOutB(bw2) = Bo(bw2); % Paste Blue image inside bw2 onto imageOutB
% Concatenate individual color channels into a 3-D true color RGB image.
Dccc = cat(3,imageOutR,imageOutG,imageOutB);

Awais Saeed on 15 Nov 2021
The (:) reshapes a matrix into a column vector.
imageOutR = [zeros(1,3); 2 5 13; 0 1 2; 1 3 5] % 4x4 matrix for instance
imageOutR = 4×3
0 0 0 2 5 13 0 1 2 1 3 5
bw2 = randi([0 1],1,10)
bw2 = 1×10
1 1 1 1 0 1 0 1 1 0
% get indices of bw2 where non-zero elements resides
% get elements of imageOutR at those indices
imageOutR(bw2(:)~=0)
ans = 7×1
0 2 0 1 5 3 0
Ro = magic(4)
Ro = 4×4
16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1
% replace elements of imageOutR with corresponding Ro's elements at those indices
imageOutR(bw2(:)~=0) = Ro(bw2(:)~=0)
imageOutR = 4×3
16 0 3 5 11 13 9 1 2 4 14 5
cat() is for concatenation of arrays

yanqi liu on 15 Nov 2021
sir，may be check it by some demo
clc; clear all; close all;
% 3 channel
Ro=RGB(:,:,1);Go=RGB(:,:,2);Bo=RGB(:,:,3);
bw2 = im2bw(RGB);
% get mask data in image
imageOutR = zeros(size(Ro));imageOutG = zeros(size(Ro));imageOutB = zeros(size(Ro));
imageOutR(bw2(:)~=0) = Ro(bw2(:)~=0);
imageOutG(bw2(:)~=0) = Go(bw2(:)~=0);
imageOutB(bw2(:)~=0) = Bo(bw2(:)~=0);
Dccc = uint8(cat(3,imageOutR,imageOutG,imageOutB));
figure;
montage({RGB,bw2,Dccc}, 'Size', [1 3], 'BackgroundColor', 'r', 'BorderSize', [3 3])
##### 2 CommentsShowHide 1 older comment
yanqi liu on 16 Nov 2021
yes，sir，use logical matrix can use directly

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by