Search code examples
matlabarea

MATLAB calculate area of shape on plot


I Create a plot using imagesc. The X/Y axis are longitude and latitude respectively. The Z values are the intensity of the images for the image shown below. What I'd like to be able to do is calculate the area in each of the polygons shown. Can anybody recommend a straightforward (or any) method in accomplishing this?

EDIT

Forgot to include image.

enter image description here


Solution

  • Below is a toy example. It hinges on the assumption that the Z values are different inside the objects from outside (here: not 0). Also here I assume a straight divider at column 4, but the same principle (applying a mask) can be applied with other boundaries. This also assumes that the values are equidistant along x and y axes, but the question does not state the opposite. If that is not the case, a little more work using bsxfun is needed.

    A = [0     2     0     0     0     2     0
         3     5     3     0     1     4     0
         1     4     0     0     3     2     3
         2     3     0     0     0     4     2
         0     2     6     0     1     6     1
         0     3     0     0     2     3     0
         0     0     0     0     0     0     0];
    
    area_per_pix = 0.5; % or whatever
    
    % plot it 
    cm = parula(10);
    cm(1, :) = [1 1 1];
    figure(1);
    clf
    imagesc(A);
    colormap(cm);
    
    % divider
    dv_idx = 4;
    
    left_object = A(:, 1:(dv_idx-1));
    left_mask = left_object > 0; % threshold object
    num_pix_left = sum(left_mask(:));
    
    % right object, different method
    right_mask = repmat((1:size(A, 2)) > dv_idx, size(A, 1), 1);
    right_mask = (A > 0) & right_mask;
    num_pix_right = sum(right_mask(:));
    
    fprintf('The left object is %.2f units large, the right one %.2f units.\n', ...
        num_pix_left * area_per_pix, num_pix_right * area_per_pix);