Changing Blackground of Image to gray?
3 views (last 30 days)
Show older comments
Hi Guys, I have an jpg / bmp image (3 D) with a black background. Can anybody tell me how can I modify this image to convert black background to gray. I only want to modify the background without changing the picture in between.
0 Comments
Accepted Answer
Walter Roberson
on 12 Jun 2012
if isreal(YourImage)
greycol = 0.5;
else
greycol = intmax(class(YourImage)) / 2;
end
[rows, cols, panes] = size(YourImage);
blacks = find( ~sum(YourImage,3) );
YourImage( [blacks, blacks + rows*cols, blacks + 2*rows*cols]) = greycol;
2 Comments
Walter Roberson
on 12 Jun 2012
Black is represented by 0. When the sum() of the third dimension (R, G, B plane) is non-0, then the implication is that at least one of the R, G, or B individually must have been non-zero. The logical negation of that (~) is the case where the R, G, and B were all 0 -- that is, that the pixel was black.
The rest of the code has to do with extending the 2D result (the locations where the pixels were black) up into the 3rd dimension so as to set the R, G, and B pixels there to the greycolor (1/2 or 127 as appropriate depending on the data type.)
Instead of sum(YourImage,3) you could use any(YourImage,3)
Detecting white is not as nice because white can be represented by 1 (double precision) or 255 (uint8) or 65535 (uint16). None the less, it isn't too bad:
if isread(YourImage)
whitecol = 1;
else
whitecol = intmax(class(YourImage));
end
greycol = whitecol / 2;
[rows, cols, panes] = size(YourImage);
whites = find( all(YourImage == whitecol, 3) );
YourImage( [whites, whites + rows*cols, whites + 2*rows*cols]) = greycol;
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!