Zoom and Crop Image (Matrix)

前端 未结 1 593
无人及你
无人及你 2021-01-26 06:49

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

相关标签:
1条回答
  • 2021-01-26 07:19

    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:

    enter image description here

    Here's the final result:

    enter image description here

    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,:);
    

    enter image description here

    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;
    
    0 讨论(0)
提交回复
热议问题