how to generate correct logical mask of the size of shape file?

i am using following code to generate logical mask
function croppedimg = cropimage(data, R, shapefile)
% Load the shapefile and retrieve its info
S = shaperead(shapefile);
% Shapefile projections
info = shapeinfo(shapefile);
crs = info.CoordinateReferenceSystem;
[S.lon,S.lat] = projinv(crs,S.X,S.Y);
% read and reproject image file
p = R.ProjectedCRS;
[x,y] = worldGrid(R);
[lon,lat] = projinv(p,x,y);
% Create a logical mask
% Approach 1: Using 'inpolygon' function
xq = lon(:);
yq = lat(:);
in = inpolygon(xq,yq,S.lon,S.lat);
logical_mask = reshape(in,size(lon));
% Debugging: Display the logical mask summary
disp(['Total number of pixels inside polygon: ', num2str(numel(logical_mask))]);
disp(['Total number of pixels inside image: ', num2str(numel(data))]);
However it is showing the
Total number of pixels inside polygon: 16982229
Total number of pixels inside image: 16982229
please suggest me how to create correct logical mask of the size of shape file.
kuldeep

Antworten (1)

DGM
DGM am 25 Sep. 2024
Bearbeitet: DGM am 25 Sep. 2024
I don't have everything to run your example, but the last lines are a problem at the least.a
Use numel() to return the total number of elements regardless of their value.
Use nnz() if you want the number of true elements in a logical array.
A = magic(5);
mask = A>15
mask = 5x5 logical array
1 1 0 0 0 1 0 0 0 1 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0
numel(mask)
ans = 25
nnz(mask)
ans = 10

5 Kommentare

Thanks a lot for your kind help. I have modified the lines as follows
% Debugging: Display the logical mask summary
disp(['Sum of pixels inside polygon: ', num2str(nnz(logical_mask))]);
disp(['Total number of pixels inside image: ', num2str(numel(logical_mask))]);
ans it is displaying as
Sum of pixels inside polygon: 0
Total number of pixels inside image: 16982229
and the size of cropped image is [0 0]
I request you to please suggest me how to get correct correct size of cropped image.
kuldeep
i am attaching the figure of image and logical mask and request you to please have a look on it.
Can you share the data files, it will be easy for us to look into it.
If you're trying to crop out blobs from a logical mask, then you can use the 'Image' property from regionprops(), or you can use the 'BoundingBox' property and pass it to imcrop() instead.
That said, there's obviously something wrong because none of your query points are in the polygon. Without the inputs to this code, it's not apparent why that is.
Thanks for your help. I am attaching the shape file and data file.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Startup and Shutdown finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2024a

Gefragt:

am 25 Sep. 2024

Kommentiert:

am 26 Sep. 2024

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by