Crop an image in half without loops or built in functions
15 views (last 30 days)
Show older comments
I'm supposed to crop a given image and remove the top half. So, the first quarter rows from the top and first quarter columns from the left. The resulting image should have the size floor(height/2) by floor(width/2). NO LOOPS or built-in functions are allowed.
I went about it the following way:
function halved_image = half_the_image(img)
[height width] = size(img)
halved_image = img(floor(height/4):height, floor(width/4):width);
end
What's happening is that the resulting image seems to clone itself? It also loses all of its color.
1 Comment
Steven Lord
on 5 Sep 2022
Your code fails to satisfy your stated requirements.
which size
which /
which floor
which :
All four of those commands are built-in functions used in your code.
Answers (2)
Walter Roberson
on 5 Sep 2022
[height width] = size(img)
sz1,...,szN — Dimension lengths listed separately
Dimension lengths listed separately, returned as nonnegative integer scalars separated by commas.
- When dim is not specified and fewer than ndims(A) output arguments are listed, then all remaining dimension lengths are collapsed into the last argument in the list. For example, if A is a 3-D array with size [3 4 5], then [sz1,sz2] = size(A) returns sz1 = 3 and sz2 = 20.
You are using RGB images, which are 3 dimensional, but your size() is only expecting two outputs.
halved_image = img(floor(height/4):height, floor(width/4):width)
and you are only indexing two dimensions in taking the half-image.
3 Comments
Walter Roberson
on 5 Sep 2022
Suppose the image has 11 rows. Then floor(height/2) would be floor(11/2) which would be 5. You would then be indexing 5:11 which is 6 rows not 5.
You need ceil() not floor() in this context.
Image Analyst
on 5 Sep 2022
It's because you did this:
[height width] = size(img)
Never do that, especially when you don't know if img will be color or gray scale.. Why not? See Steve's blog:
Do this:
[rows, columns, numberOfColorChannels] = size(img);
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!