In one of our previous tutorial, we had shared how to find the length of an object in an image. If you miss the tutorial, please visit this link.
One of our reader was asking whether it is possible to calculate the area for a selected region, and here we will try to work on it from the basic.
Let’s say we would like to find the size of the eye of the image above, here’s the steps we need to do:
Select Points from The Image, In Anti-Clockwise Direction
First, load and show the image, followed by the function “imselect” to choose the points around the left eye of the baboon with left mouse button, and end the selection with right mouse button.
S = imread('baboon.png'); imshow(S); pts = imselect(100);
Show The Polygon On The Image
The selected points are saved in variable “pts”, we will extract it into x and y, and add the last point to be the same point with the first to form a close polygon.
x = pts(:,1); y = pts(:,2); x($+1) = x(1); y($+1) = y(1); scf();imshow(S); xpoly(x,y,'lines'); e = gce(); e.foreground = 3; e.thickness = 3;
Calculate The Area and Show On The Image
We will then use the x and y information to calculate the are in pixels and show on the image.
area = 1/2*sum(x.*y([2:length(y),1])-y.*x([2:length(x),1])); xnumb(max(x),max(y),area); e2 = gce(); e2.font_color = 3; e2.font_size = 5;
Changing The Polygon Interactively
The first selected polygon might not be perfect in shape, we could modify the polygon interactively by the steps as shown in the video below.
After modifying the polygon, we need to recalculate the area again. We will need to extract the new polygon data. Remember we have the polygon handle saved in variable “e” above? we could just use it to extract the data.
x = e.data(:,1); y = e.data(:,2); area = 1/2*sum(x.*y([2:length(y),1])-y.*x([2:length(x),1])); e2.text = string(area);
Here you go! A nicer shape with more accurate size estimation of the eye!