Crop an image in Matlab - image

I want to crop an image from a specific row onwards. Please help me how can I do this. I am a beginner in Matlab.

This page has a lot of great info on dealing with images in matlab.
When you load an image in matlab, it is loaded as a MxNx3 matrix. The third dimension stores the RGB values of each pixel. So to crop an image you simply select just the range of rows and columns you want to keep:
cropped_image = image(RowStart:RowEnd,ColStart:ColEnd,:);

See this: http://www.mathworks.com/help/techdoc/creating_plots/f9-47085.html
There is a graph editor icon in the screen where you see your graph, it should look like this:
Press it, you will get a big graph editor, now try pressing on the graph or one of the functions, in the lower right part you can set ranges, this will crop the image.

You can use imcrop function in Matlab
CropIm = imcrop(I, rectangle);
rectangle is a four-element position vector [xmin ymin width height] which indicates the size and position of the crop rectangle.
Im = imread('test.tif');
Im2 = imcrop(Im,[75 68 130 112]);
imshow(Im), figure, imshow(Im2)

Related

How to trace the surface area as well as smoothen a specific region in an image using MATLAB

I have an image with 6 colors each indicating a value. I had obtained an image as shown below.
I need to smoothen the edges and then find out the area as well as the surface area of that region. The second image shows a black line drawn in the edges which indicates that I need to smoothen the edges in such a way.
I had used segmentation to create a mask as shown in the third image, and then obtain a segmented image using the code following the image.
I have used the following code for generating till the masked image.
Source : How to segment
imshow(Out1)
str = 'Click to select initial contour location. Double-click to confirm and proceed.';
title(str,'Color','b','FontSize',12);
disp(sprintf('\nNote: Click close to object boundaries for more accurate result.'));
mask = roipoly;
figure, imshow(mask)
title('Initial MASK');
maxIterations = 3000;
bw = activecontour(Out1, mask, maxIterations, 'Chan-Vese');
% Display segmented image
figure, imshow(bw)
title('Segmented Image');
In order to use the 'activecontour' function my image needs to be a grey-scale image, which I'm not being able to convert to greyscale and back. Also to find out surface area/ area of the region is there any inbuilt function. Please help thanks.
use im2double, im2uint8, etc. to convert binary image to grayscale.
use bwarea or regionprops to find the region area.

Labeling plots with images in Matlab

Is there any way of labeling plots with images. For example, when I use the following:
plot(Y(:,1),Y(:,2),'o','LineWidth',2);
gname(names)
I can label each dot in a plot with a name. Is there any way to insert images instead of names?
It is possible, but not as convenient as gname by far. You can use the low-level version of image to insert images in your plot at arbitrary positions. Here's a simple example which puts the "Mandrill" image that comes with Matlab with its upper left corner pixel at the position (pi/2, 0):
% example plot
x = linspace(0, 2*pi, 100);
plot(x, cos(x))
% insert image
load mandrill
colormap(map)
image('CData', X, 'XData', [pi/2, pi/2 + 0.5], 'YData', [0, -0.3])
The result looks like this:
Problems with this approach:
There is no interactive point-and-click facility, you have to explicitly insert and position the image labels programmatically, or program such a point-and-click facility yourself. ginput might help doing so.
A figure window can only have one associated color map. That means if you have different images, they either all have to use the same colormap or have to be truecolor images.
Not just the position, but also the display size of the image has to be specified in the call to image, and both are by default specified with respect to the plot's coordinate system. This makes it hard to achieve the correct aspect ratio. You can switch (temporarily) to absolute units using the axes property 'Units' , but then you have to figure out the correct position in e.g. absolute millimeters or inches. Moreover, images are usually indexed with vertical coordinates increasing from top to bottom, while plots usually have vertical coordinates increasing from bottom to top. This is the reason for the negative value -0.3 in the 'YData' property above.
Alternatively, you can insert images each in their own little axes sitting on top of the plot's axes, which makes it easy to get the right orientation and aspect ratio using axis image. You'll still have the problem though to figure out the correct position for the axes.

Find the edges of image and crop it in MATLAB

I have a RGB image. I have scanned the image. So the image occupies a small portion of an A4 size sheet.
I want to find the border of the image and crop it. I could use edge detection operators like 'Sobel' etc, but they detect all the edges present in the image. All I want is the border of the image. Also many of the edge detection functions including 'bwboundaries' work only with binary or grayscale images. My image is RGB.
I tried using 'imcrop', but this is more of interactive cropping. I am keen on doing this automatically.
Uploading a test image:
Since this is an rgb image, there will be apparent color in the gray areas, but there should be none in the white ones. You can make use of this to find the image, then you can get the bounding box.
img = imread('http://i.stack.imgur.com/dEawA.jpg');
%# instead of "==" you can check for similarity within a tolerance
tt=img(:,:,1)==img(:,:,2) & img(:,:,2) == img(:,:,3);
%# invert tt so that it's 1 where there is signal
tt = ~tt;
%# clean up some of the smaller artifacts
tto = imopen(~tt,strel('square',100));
%# get the areas and bounding box of the areas above threshold
%# as an additional criterion, you could also use excentricity
%# or you could simply remove the bottom 100 rows of the scan
stats = regionprops(tto,'BoundingBox','Area');
area = cat(1,stats.Area);
[~,maxAreaIdx] = max(Area);
bb = round(stats(maxAreaIdx).BoundingBox);
%# note that regionprops switches x and y (it's a long story)
croppedImage = img(bb(2):bb(2)+bb(4),bb(1):bb(1)+bb(3),:);
There is a bit of a border left due to rotation. You can use the mask tto above to set all non-image pixels to NaN before cropping, or you can use imrotate to fix your image.
You can try to detect the corners of your image using e.g. the Harris-Detector (corner in Matlab). Set the maximum number of corners to detect to 4. Then use the positions of the corners in imcrop. If you would post an image I could give you more specific hints. Your image being RGB shouldn't be a problem, just convert it to grayscale.
You can try using bwlabel http://www.mathworks.com/help/toolbox/images/ref/bwlabel.html (along with find, as noted in the help page) to get the indices of the image and use those to crop the original.
You'll first need to convert the original image to binary using im2bw http://www.mathworks.com/help/toolbox/images/ref/im2bw.html.

Display image at desired scale across subplot axes

Is it possible to display an image in multiple subplot axes, such that the image appears at the desired scale?
subplot(3,3,[1 4 7]);
%# image scaled down to fit 1 set of axes
imshow(img);
subplot(3,3,2);
plot(relevantData);
%# And so on with 5 other plots
I want to have the image scaled to either a fixed size or to fit the axes available to it, rather than to the size of a single axes.
My use case is to show a video alongside plots derived from the video, such that the plots are progressively drawn in step with the video. Once the display is correct I can save each image and combine them into a video.
Clarification
I am asking if it is possible to produce a figure as described without specifying the position of every element in absolute terms. Though one can make arbitrary figures that way (and in fact I have done so for this project), it is very tedious.
Edit:
For changing the size of the subplot:
In help subplot they mention that you can set parameters on the selected "axes" (that's what they call a plotting area in Matlab).
Using that, you can set the 'position', as seen in help axes. This property takes takes as argument:
[left, bottom, width, height]
As pointed out by #reve_etrange, one should use absolute positioning for axes 'Position'and 'OuterPosition' parameters. they can be in normalized coordinates, though.
For changing the size of the image in the subplot:
I think there are 2 useful things for you in the help imshow output:
'InitialMagnification': setting the magnification of the image.
'Parent': determines which parent imshow will use to put the image in (never tried using imshow with subplots).

MATLAB:: Drawing a number on a image (Matrix) on MATLAB

I'm using matlab in order to perform modifications on an image.
I have loaded an image on Matlab. (the image may be in different resolutions)
Converted the image to gray scale then converted the image's matrix to double.
I have drawn grid lines on the image
(I have posted the code how to do that somewhere here on stack over flow).
My problem is that I may have upon the 1000 squares as a result from girding the image on the X axis and the Y axis.
I'd like to numbering the squares in that image.
Is there an option of drawing numbers on Matlab ?
I'd be glad to receive any information about that (except from being a clicking monkey and writing 0 till 1000 on paint haha... ).
Cheers
S
Here is a code example to put text labels on an image in the middle of grids:
x = imread('cameraman.tif');
image(x)
axis image
grid on
%# grid domains
xg = 0:50:200;
yg = 0:50:200;
%# label coordinates
[xlbl, ylbl] = meshgrid(xg+25, yg+25);
%# create cell arrays of number labels
lbl = strtrim(cellstr(num2str((1:numel(xlbl))')));
text(xlbl(:), ylbl(:), lbl(:),'color','w',...
'HorizontalAlignment','center','VerticalAlignment','middle');
Use text
text is the low-level function for creating text graphics objects. Use
text to place character strings at specified locations.
text(x,y,'string') adds the string in quotes to the location specified
by the point (x,y) x and y must be numbers of class double.

Resources