Zoom and Crop Image (Matrix)

2019-03-06 08:27发布

问题:

I have 2 questions that pertains to zooming and cropping of an image.

1) Zooming into an image that would make the image twice as large in both height and width and that each pixel in the matrix is replicated to become 4 pixels. Was wondering if this can be accomplished without using any loops or interpolations and the function imresize.

2) Cropping a matrix by selecting a certain area of the image and then cropping it to a certain length and height. Again, I'm wondering how this can be accomplished without using any loops or interpolations and the function imresize. Maybe by removing a certain column and row from the matrix?

Any help on how to create a function for these would be greatly appreciated. :)

回答1:

Let's answer each question one at a time.

Question #1

Your problem statement says that you want to zoom in, yet what you're describing is a simple resizing. I'm going to do both.

For the first point, what you are seeking is pixel duplication. The easiest thing to do would be to declare an output image that is twice the size of the input image, then write code that will duplicate each input pixel to the output where it gets copied to the right, bottom and bottom right. For example, using onion.png from the MATLAB system path, you would do:

im = imread('onion.png');
rows = size(im,1);
cols = size(im,2);
out = zeros(2*rows, 2*cols, size(im,3), class(im));
out(1:2:end,1:2:end,:) = im; %// Left
out(2:2:end,1:2:end,:) = im; %// Bottom
out(1:2:end,2:2:end,:) = im; %// Right
out(2:2:end,2:2:end,:) = im; %// Bottom-Right

Note that the way we are indexing into the array, we are skipping over one pixel, and the starting position changes depending on where you want to copy the pixels.

Here's the original image:

Here's the final result:

BTW, usually when you increase the size of an image, you are upsampling, you usually low-pass filter the result to perform anti-aliasing.

Now if you want to zoom in to a portion, all you have to do is choose a portion that you want from the upsampled image and crop it. This leads to your next question.

Question #2

This can simply be done by indexing. Given a row and column location of the top-left corner of where you want to extract, as well as the width and height of what you want to crop, you simply do this. r and c are row and columns of the top-left corner and w and h are the width and height of the cropped result:

out = im(r:r+h-1, c:c+w-1,:);

Let's say (r,c) = (50,50) and (w,h) = (50,50). For our onion.png image, we get:

r = 50; c = 50;
h = 50; w = 50;
out = im(r:r+h-1, c:c+w-1,:);

If you wanted to place the cropped image in another position in the original image, you would simply repeat the procedure above, but the output will be assigned to locations in the original image. Given r2 and c2 to be the top-left corner of where you want to save the image to in the original image, do:

im(r2:r2+h-1, c2:c2+w-1, :) = out;