What is the meaning of if size(I,3)>1 I=rgb2gray(I);
8 次查看(过去 30 天)
显示 更早的评论
I dont understand why the condition if size(I,3)>1 means and why it is need to convert I=rgb2gray(I);
2 个评论
Kanwal Kaur
2016-11-17
编辑:Walter Roberson
2016-11-17
if (size(I,3) == 3)
I=rgb2gray(I);
end
here, what will be the use of 3 in (I,3), plz explain
Walter Roberson
2016-11-17
See my description below. The 3 in size() refers to the third dimension. The second 3 being compared to corresponds to the three R, G, B values.
采纳的回答
Walter Roberson
2015-8-13
grayscale images are represented as 2 dimensional matrices, Height by Width.
RGB ("truecolor") images are represented as 3 dimensional matrices, Height by Width by ColorPlane .
In MATLAB, if you take the size() of the 3rd dimension of a 2 dimensional object, the result is 1. Height by Width is the same as Height by Width by 1.
So to test whether the array represents a grayscale image or represents an RGB image, you can test whether the third dimension is size greater than 1 -- because it will be 1 for 2 dimensional arrays and it will be 3 for RGB arrays.
If the image is already grayscale there is no need to convert it again, so the rgb2gray() is being done only if the image is RGB.
rgb2gray() happens to be defined to leave 2 dimensional matrices unchanged, so you can just call rgb2gray() on the image whether it is grayscale or RGB. It is common, though, for programmers not to know about to be the case, or not to trust that it will always be the case, and so it is common for programmers to test the dimensions to see if the call needs to be made. Also size() is "nearly free", a built-in operation that has little to do internally, and it is more costly to call rgb2gray, so it is faster to do the test than to leave it up to rgb2gray()
Eventually you may see programs where the internal convention has become that 2 dimensional images are always double() but 3 dimensional images are often uint8(). In those programs, testing the dimensions would also be used to determine whether im2double() should be called along with rgb2gray()
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!