# Can someone explain this code please? This was my question: Add the pixels of image1 to image2 in order to create a new image using for loops.

1 view (last 30 days)
Hind Aljallaf on 7 Dec 2022
Answered: Walter Roberson on 7 Dec 2022
Can someone please explain my code? especially this part "im12 = zeros(r,c,n,'uint8')"
[r,c,n]=size(img1)
im12 = zeros(r,c,n,'uint8')
for i = 1 : r
for j = 1 : c
im12(i,j) = img1(i,j)+img2(i,j);
end
end
imshow(im12)

Walter Roberson on 7 Dec 2022
[r,c,n] = size(img1)
assigns the number of rows in img1 to r, the number of columns in img1 to c, and n is assigned the product of all remaining dimensions.
For grayscale and indexed images, the 3rd and all higher dimensions are 1 so n would be assigned 1
For RGB images, the 3rd dimension would be 3 (three colour channels, Red, Green, Blue) so n would be assigned 3.
In some cases, PNG images can be RGBA (3rd dimension would be 4) but I do not recall at the moment whether those are returned as r x c x 4 or if the A channel will be split off by imread()
im12 = zeros(r,c,n,'uint8')
that would create an array the same size as img1 (unless somehow img1 ended up with more than 3 dimensions), but it would specifically be a uint8 array even if the png was something other than uint8.
for i = 1 : r
for j = 1 : c
im12(i,j) = img1(i,j)+img2(i,j);
end
end
There are vectorized ways to do that, such as
im12 = uint8( img1(:,:,1) + img2(:,:,1) );
Notice that if the images were RGB then the green and blue channels would be lost in created the sum. Also notice that uint8 "saturates" so if for example img1 was 185 at a location and img2 was 97 there, then 185+97=282 would "saturate" at 255 in the result.
im12 = imlincomb(0.5, img1, 0.5, img2);