# For loop each RGB image channel

7 views (last 30 days)
nurul atikah mohd sharif on 8 Nov 2021
Answered: Image Analyst on 8 Nov 2021
I want to make this manual saperated RGB channel code into for loop, each channel will undergo the same calculation. Can anybody help me how to convert it into for loop code?
here the image:
%% black & white
bw = imbinarize (t,0.4);
bw = ~bw;
%% remove noise
bw2 = bwareaopen (bw,100);
%%separate 3 layer RGB
R = t(:,:,1);
G = t(:,:,2);
B = t(:,:,3);
R(bw2(:)==0) = 255;
G(bw2(:)==0) = 255;
B(bw2(:)==0) = 255;
c = cat(3,R,G,B);
%calculate range R
rmax = max(R(bw2(:)~=0))
rmin = min(R(bw2(:)~=0))
gmax = max(G(bw2(:)~=0))
gmin = min(G(bw2(:)~=0))
bmax = max(B(bw2(:)~=0))
bmin = min(B(bw2(:)~=0))

DGM on 8 Nov 2021
There are probably more succinct ways, but this is one way. Instead of creating a pile of variables, just put things in an array
c = t;
c(repmat(~bw2,[1 1 3])) = 255;
% calculate min and max for R,G,B masked regions
for cc = 1:3
thischan = t(:,:,cc);
end
93 67 131 255 251 255
DGM on 8 Nov 2021
There were a number of issues. Here's a first pass. You'll have to fill in where there's missing variables
dg = 10; % dg not defined
segmented_images2 = cell(1,5);
for j = 1:5 % only provided 5 images instead of 6?
%
bw = imbinarize (segmented_images2{j},0.4); % need to use an image instead of the index
bw =~bw;
bw2 =bwareaopen (bw,100);
%c = j;
%c(repmat(~bw2,[1 1 3])) = 255;
% calculate min and max for R,G,B masked regions
for cc = 1:3
thischan = segmented_images2{j}(:,:,cc); % need to use an image instead of the index
%calculate range R
Cmin = min(thischan(bw2(:,:,cc))); % imbinarize generates mask with 3 chans instead of 1
Cmax = max(thischan(bw2(:,:,cc)));
% degree of alpha, beta, gamma
alpha_degree= dg; %input('Enter alpha in degrees: ');
beta_degree= dg; %input('Enter beta in degrees: ');
gamma_degree= dg; %input('Enter gamma in degrees: ');
alpha=(alpha_degree*pi)/180;
beta=(beta_degree*pi)/180;
gamma=(gamma_degree*pi)/180;
% range definitions
x_r1 = 0:Cmin;
x_r2 = Cmin:Cmax;
x_r3 = Cmax:255;
a1 = tan(alpha);
a2 = tan(beta);
a3 = tan(gamma);
% contrast stretching in regions
im1 = floor(a1*cc);
im2 = floor(a1*Cmin + (a2*minus(cc,Cmin)));
im3 = floor(a2*Cmax+minus(a1,a2)*Cmin + (a3*minus(cc,Cmax)));
end
% concatance of output image
CSsegment_image2{j} = cast(im1+im2+im3,'uint8'); %#ok<SAGROW> % variable name
CSsegment_image2{j}(bw2(:)~=0) = Ro(bw2(:)~=0); %#ok<*SAGROW> % Ro is undefined
subplot(2,2,j);
imshow(CSsegment_image2{j});
end

Image Analyst on 8 Nov 2021
Not sure what analysis you want to do (you didn't say what the "calculations" were) but I just thought I'd point you to a similar example by the Mathworks: