I have an image with dark blue spots on a black background. I want to convert this to inverse gray scale. By inverse, I mean, I want the black ground to be white.
When I convert it to gray scale, it makes everything look black and it makes it very hard to differentiate.
I am using img = rgb2gray(img);
in MATLAB for now.
- Is there a way to do an inverse gray scale where the black background takes the lighter shades?
Based on your image description I created an image sample.png
:
img1 = imread('sample.png'); % Read rgb image from graphics file.
imshow(img1); % Display image.
Then, I used the imcomplement
function to obtain the complement of the original image (as suggested in this answer).
img2 = imcomplement(img1); % Complement image.
imshow(img2); % Display image.
This is the result:
- Or, another preferable option is to represent the blue as white and the black as black.
In this case, the simplest option is to work with the blue channel. Now, depending on your needs, there are two approaches you can use:
This comment suggests using the logical operation img(:,:,3) > 0
, which will return a binary array of the blue channel, where every non-zero valued pixel will be mapped to 1
(white), and the rest of pixels will have a value of 0
(black).
While this approach is simple and valid, binary images have the big disadvantage of loosing intensity information. This can alter the perceptual properties of your image. Have a look at the code:
img3 = img1(:, :, 3) > 0; % Convert blue channel to binary image.
imshow(img3); % Display image.
This is the result:
Notice that the round shaped spots in the original image have become octagon shaped in the binary image, due to the loss of intensity information.
A better approach is to use a grayscale image, because the intensity information is preserved.
The imshow
function offers the imshow(I,[low high])
overload, which adjusts the color axis scaling of the grayscale image through the DisplayRange parameter.
One very cool feature of this overload, is that we can let imshow
do the work for us.
From the documentation:
If you specify an empty matrix
([])
,imshow
uses[min(I(:)) max(I(:))]
. In other words, use the minimum value inI
as black, and the maximum value as white.
Have a look at the code:
img4 = img1(:, :, 3); % Extract blue channel.
imshow(img4, []); % Display image.
This is the result:
Notice that the round shape of the spots is preserved exactly as in the original image.