Clear Filters
Clear Filters

how crop an image automatically without any coordinate?

32 views (last 30 days)
Hello everyone. My original image width 841pixels x height 482 pixels. So, the problem here's, I want to crop the image automatically with 512x512 pixels in the center of the lesion like the picture above. but my original image does not enough pixels to crop. Should I enlarge the original image first? What I meant is that, the pixels from the original image is enlarge from the original one. So, my objective have 2, first : if the orignal image does not enough pixels crop, I want Matlab to enlarge the pixels of the original image at first, then crop automatically into 512x512 pixels. Here, I attacth the image that I want to crop using square box. As you can see below picture, the square box detects the lesion ground truth below and crop it automatically. and also the original image I attached below.
Hope that you can help me out. Thank you.

Accepted Answer

Image Analyst
Image Analyst on 12 May 2024
You can use padarray to add enough rows so that your box can be 512x512. Or you can crop what you have within the existing image and then use imresize to force the cropped image to be 512x512.
Dayangku Nur Faizah Pengiran Mohamad
Dayangku Nur Faizah Pengiran Mohamad on 17 May 2024 at 15:39
Edited: Dayangku Nur Faizah Pengiran Mohamad on 17 May 2024 at 15:40
Lets say I want to resize with unchanged aspect ratio but using padding. This is my code:-
size = 256;
function new_image = letterbox_image(image, size)
% resize image with unchanged aspect ratio using padding
[iw, ih] = size(image);
[w, h] = deal(size);
scale = min(w/iw, h/ih);
nw = round(iw*scale);
nh = round(ih*scale);
image = imresize(image, [nw, nh], 'bicubic');
new_image = uint8(ones(h, w, 3)*256);
new_image((h-nh)//2+1:(h-nh)//2+nh, (w-nw)//2+1:(w-nw)//2+nw, :) = image;
but then, I got the error here:-
File: resize4.m Line: 14 Column: 22
Invalid use of operator.
Image Analyst
Image Analyst on 17 May 2024 at 16:11
Wow, so much wrong with that code! For one thing, don't use size as the name of your variable since it's the name of a very important built-in function. In fact you later try to use it as the built-in function to get the size of your image but since you overrode the function with your variable, it will use the variable "size" instead of the function size(). Not only that but if you were using the size function, you're using it incorrectly. JPG images are often RGB even if they appear gray scale. So you'd need to do
[rows, columns, numberOfColorChannels] = size(yourImage);
which brings up to yet another problem. "image" is also the name of a built in function so you should not use it for the name of your variable. Call in inputImage instead of image.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!