How can I display a grayscale raster in color in Matlab? - matlab

I have a .tif file of a landmass that denotes elevation. I want to display this raster with a color ramp as opposed to a grayscale ramp. How would I do this in Matlab?
I looked at the information associated with the tiff using:
[Z, R] = geotiffread('Landmass.tif')
which denotes the heading 'ColourType' as 'grayscale'. I tried to change this to 'winter' (one of matlabs in-built color schemes) but it made no difference.
At the moment I am using the following commands to display the tiff:
[Z, R] = geotiffread('Landmass.tif');
e=uint8(Z);
mapshow(e,R);
All the higher areas are white and everything else is black...even around the landmass (which I think I may have to cut/mask the landmass out to get rid of).
All the black colour is making it too difficult for me to display other shapefiles on top of the tiff, so I want to change the color scheme from grayscale to something lighter.
How do I do this?

The reason colormap winter is not working is because the output of mapshow(e,R); is RGB image format.
Even when the displayed image is gray, it is actually RGB, when r=g=b for each pixel.
I took Matlab mapshow example, converted boston image to Grayscale, and used mapshow.
For using colormap winter, I got image using getimage, convert it to Grayscale using rgb2gray, and then colormap winter worked when showing the image.
Check the following example:
[boston, R] = geotiffread('boston.tif');
boston = rgb2gray(boston); %Convert to Grayscale for testing.
figure
mapshow(boston, R);
axis image off
%Get image data, note: size of I is 2881x4481x3 (I is not in Grayscale format).
I = getimage(gca);
%Convert I from RGB (R=G=B) formtat to Grayscale foramt, note: size of J is
%2881x4481 (J is Grayscale format).
%%%%%%%Avoid image being rotated%%%%%%%%%%%%%
%Close old image and open new figure
close Figure 1
Figure
J = rgb2gray(I);
imshow(J);
colormap winter %Now it's working...
Boston with winter colormap:

Related

How to create an inverse gray scale?

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.
Is there a way to do an inverse gray scale where the black background takes the lighter shades?
Or, another preferable option is to represent the blue as white and the black as black.
I am using img = rgb2gray(img); in MATLAB for now.
From mathworks site:
IM2 = imcomplement(IM)
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:
Approach 1: Convert the blue channel to a binary image (B&W)
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.
Approach 2: Convert the blue channel to grayscale image
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 in I 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.

how to to make a car park shows different colors for each dots using matlab?

I convert my car park image to binary image and clear the unwanted white dots/region to get this image:
This is my codes:
sceneImage = imread('nocars10green.jpg');
figure;
imshow(sceneImage);
hsvscene = rgb2hsv (sceneImage);
figure;
imshow (hsvscene);
grayscene = rgb2gray (hsvscene);
figure;
imshow (grayscene);
bwScene = im2bw (grayscene);
figure;
imshow (bwScene);
str = strel('disk',4)
bw = imerode(bwScene,str)
figure;
imshow (bw);
How do I convert the binary image after erode so that I can show different colors for different dots?
I read in this journal.
Al-Kharusi, Hilal, and Ibrahim Al-Bahadly. "Intelligent parking management system based on image processing." World Journal of Engineering and Technology 2014 (2014).
it is mentioned:
if (newmatrix(y,x) > 0) % an object is there, if (e(newmatrix(y,x)) = 0) this object has not been seen
(newmatrix(y,x)) = x; make the value and index 3 equal to the current X coordinate.
and this is their output image:
But I don't understand how it works. Can anyone explain to me how it work and how to write the commands to convert my binary image to get the same as their output image in order to get different colors of each dots?
or if there is any other way to convert it?
The term you have to search the web for is connected component labeling or just labeling.
Given the provided image with 10 white dots on black background you can do the following:
Find the blobs:
https://en.wikipedia.org/wiki/Connected-component_labeling
https://de.mathworks.com/help/images/ref/bwlabel.html
Then color them. For example by using label2rgb:
You can display the output matrix as a pseudocolor indexed image. Each
object appears in a different color, so the objects are easier to
distinguish than in the original image. For more information, see
label2rgb.

Identifying White Cars in an Image using Matlab

I am currently writing a program on Matlab for Image Processing. I am using an image (below) to attempt to count the number of white cars in the image. I have used filtering commands, strel(disk, 2), and have managed to detect the two white cars in the image but due to the way the binary image (below) displays a car it counts one car as two.
Are there any solutions to overcome this problem or are there any particular methods I should be using as an alternative to the code below?
a = imread('Cars2.jpg'); %Read the image Car1.jpg
subplot(3,3,1), imshow (a); %Display RGB image Car1.jpg
b = rgb2gray(a); %Turn Car1 from RGB to greyscale
subplot(3,3,2), imshow (b); %Display greyscale image Car1.jpg
c = graythresh (a); %Automatically set appropriate threshold for foreground & background (Otsu's Method)
d = im2bw (b,0.8); %Convert from greyscale to binary image
subplot (3,3,3), imshow(d); %Display binary image Car1.jpg
subplot(3,3,4), imhist (b,256); %Display histogram for greyscale values (image, samples)
SE = strel ('disk',2); %Set Disk radius for filtering unnecessary pixels
e = imopen (d,SE); %Erode then Dilate image with Disk radius
subplot (3,3,5), imshow(e); %Display openned/filtered image Car1.jpg
B = bwboundaries(e);
imshow(e)
text(10,10,strcat('\color{red}Objects Found:',num2str(length(B))))
hold on
EDIT: As i have under 10 reputation I can't post the image displayed from the code but the theory is pretty generic so I hope you understand what I'm getting across. The images are similar to http://www.mathworks.co.uk/help/images/examples/detecting-cars-in-a-video-of-traffic.html
Instead of using bwboundaries I would use regionprops(e). You can then use some additional logic by looking at the area of the object and the shape of the bounding box to infer if the object is one or two cars.
If you are only interested in detecting white cars, your overall algorithm could be improved by converting the image into HSV colour space and thresholding on the saturation and value channels instead of using im2bw. If you have a video sequence I would segment using vision.ForegroundDetector or another Gaussian mixture model segmentation technique.

Matlab: imgradient returns quantized images

In Matlab, I want to display the gradient magnitude and direction of a grayscale image. Here is the code I am trying:
image = imread('gray_image.bmp');
[gmag, gdir] = imgradient(image);
figure, imshow(image);
figure, imshow(gmag);
figure, imshow(gdir);
However, gmag and gdir seem to be quantized to just two values: black and white. Every pixel in gmag and gdir is either black, or white. My image itself has a range of gradient magnitudes and directions. Why are these not showing up in the gmag and gdir images? Yes, I would expect gmag to have pure black for pixels with zero gradient, and pure white for pixels with maximum gradient, but I would also expect a range of gray values for gradients between those. Similarly, I would expect a range of gray values in gdir representing the range of angles.
For example, here is the grayscale image:
Here is gmag:
And here is gdir:
Why are gmag and gdir only displaying black or white, with no intermediate gray values?
Two issues
'gmag' and 'gdir' calculated with IMGRADIENT have double datatype.
Thus, if you want to display them as such, MATLAB would treat them as
intensity images and would expect them to be in the range [0 1].
Thus, we need to normalize ‘gmag’ and ‘gdir’, which is shown in the
code later on.
If you wish to save these images, MATLAB expects UINT8 datatype and
the values must lie in the range [0 255].Thus, before saving you need
to multiply it by 255 and then convert to UINT8.
Code
image = imread('gray_image.bmp');
[gmag, gdir] = imgradient(image);
%%// Normalize gmag and gdir
gmag = (gmag-min(gmag(:)))./(max(gmag(:))-min(gmag(:)));
gdir = (gdir-min(gdir(:)))./(max(gdir(:))-min(gdir(:)));
%%// Display images
figure, imshow(image);
figure, imshow(gmag);
figure, imshow(gdir);
%%// Save gradient images
imwrite(uint8(255.*gmag),'Lena_gmag.bmp');
imwrite(uint8(255.*gdir),'Lena_gdir.bmp');
Ouput images
GMAG -
GDIR -
As a test, one can notice the bar-like structure right behind Lena in the GDIR image now, which wasn't visible before.

Colorbar is not showing the colors I want

I have a similar question than the one in this post.
I have a grayscale image and I plot points on it. Fro plotting the points I use colormap('jet') but as I want the image to be grayscale, after plotting the points I reset the colormap, colormap('gray').
But I want to show a colorbar! And the colorbar is plotted in grayscale, not 'jet'.
How can I do that?
EDIT:
I want a Colorbar showing the color of the points!
You should convert your image to RGB by putting the same data into R-, G-, and B-channels (this will be grayscale RGB image). Colormap in MatLab is not applied to RGB images, only to indexed ones. Then plot your points over the image with colormap you like.
As discussed here, there's a few ways:
If you have the image processing toolbox, use subimage to create an independent image with a separate colormap. Then plot the image, your points, and join them into one using linkaxes.
Use freezeColors from the file exchange (or multiple colormaps, which I haven't ever tested personally). This is a very easy way to create a larger colormap, and automatically selecting the right portion of the colormap for display of images and colorbars.
As answered by anandr, convert your greyscale image to RGB; Matlab doesn't use colormaps on RGB images, which leaves you freedom to plot your points and show their colorbar independent of the image.
Example code for (3):
I = imread('cameraman.tif');
imshow(cat(3,I,I,I))
hold on
x = #() round(size(I,1) * rand(50,1));
y = #() round(size(I,2) * rand(50,1));
plot(x(), y(), 'r.')
plot(x(), y(), 'g.')
plot(x(), y(), 'b.')
colormap('jet')
colorbar
result: