MATLAB: Difference between two programs

forimage processing

I have two small programs which must have the same result but in executing them I have some difference and I don't understand where is the problem. The task is to write a simple stand-alone program that converts the loaded source image in the negative one.
X=imread('mosque.jpg');
imshow(X);
[n,m]=size(X);
B=zeros(n, m, 'uint8');
for i=1:n
for j=1:m
B(i,j)=255-X(i,j);
end
end
subplot(2,2,1);
imshow(X);
subplot(2,2,2);
imhist(X);
subplot(2,2,3);
imshow(B);
subplot(2,2,4);
imhist(B);
the second program without the for
X=imread('mosque.jpg');
imshow(X);
[n,m]=size(X);
B=zeros(n, m, 'uint8');
B=255.-X;
subplot(2,2,1);
imshow(X);
subplot(2,2,2);
imhist(X);
subplot(2,2,3);
imshow(B);
subplot(2,2,4);
imhist(B);

Best Answer

X=imread('mosque.jpg');
The great majority of .jpg are RGB (grayscale is possible but very rare.)
[n,m]=size(X);
size() of an RGB image when permitting only two output variables would store the number of rows in n, and three times the number of columns in m . When you use size() with fewer outputs than dimensions of the array, the result is not to throw away the extra dimensions. The product of the values returned by size() is always equal to the number of elements in the entire array.
B=zeros(n, m, 'uint8');
B is constructed as a grayscale image, not as an RGB image.
Related Question