Crop an image in half without loops or built in functions
이전 댓글 표시
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
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.
답변 (2개)
Walter Roberson
2022년 9월 5일
[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
Walter Roberson
2022년 9월 5일
and remove the top half. So, the first quarter rows from the top and first quarter columns from the left.
Suppose you have an image with 8 rows and 8 columns. You remove the first "quarter rows" from the top and left. 1/4 rows of 8 rows is 2 rows, so you remove 2 rows and 2 columns. That would give you 6 rows and 6 columns of output, which does not match the requirement that the output be floor(height/2) by floor(width/2)
It is a valid thing to do to want to crop to remove the top half and left half, giving you the bottom right quarter. It is a valid thing to do to want to remove the top and bottom 1/4 and left and right 1/4, giving you the center quarter. But you have to decide which of the two your are doing.
Poojha Palle
2022년 9월 5일
편집: Poojha Palle
2022년 9월 5일
Walter Roberson
2022년 9월 5일
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
2022년 9월 5일
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);
카테고리
도움말 센터 및 File Exchange에서 Image Arithmetic에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!