difference between two programs
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
boutheina gherib
am 19 Okt. 2019
Beantwortet: boutheina gherib
am 20 Okt. 2019
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);
2 Kommentare
John D'Errico
am 19 Okt. 2019
Note that for these two statements:
B=zeros(n, m, 'uint8');
B=255.-X;
The first is irrelevant. There is no need to preallocate B there, because the second line just overwrites it.
Had you done this instead?
B = 'Mississippi';
B=255.-X;
The result would have been the same.
However, in the case of the for loops, since there you are populating B one element at a time, it is very important to preallocate B.
Akzeptierte Antwort
Walter Roberson
am 19 Okt. 2019
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.
2 Kommentare
Walter Roberson
am 20 Okt. 2019
>> A = randi(10,5,6,7);
>> B = size(A)
B =
5 6 7
>> [C,D] = size(A)
C =
5
D =
42
>> [E,F,G] = size(A)
E =
5
F =
6
G =
7
Notice that the [C,D] = size(A) case did not return C = 5 and D = 6. These two pieces of code are not equivalent:
[C,D] = size(A); %D will be 6*7 = 42. C*D will equal numel(A)
%versus
temp = size(A);
C = temp(1); D = temp(2); %D will be 6. C*D will equal 30 only
You can pre-allocate B as:
B = zeros(size(A), class(A));
But remember in your loops that A is not two dimensional: A is three dimensional. You have to loop over the red, green, and blue color planes.
Weitere Antworten (2)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!