Image scaling

Question:

Write a function that takes a gray image and a target size as input, and generates the scaled imageas output. Please use bi-linear for interpolation. The function prototype is “scale(input img,size) → output img”, where “input img” and “output img” are two-dimensional matricesstoring images, and “size” is a tuple of (width, height) defining the spatial resolution of output.You can modify the prototype if necessary.For the report, please load your input image and use your “scale” function to:

1. Down-scale to 192 × 128 (width: 192, height: 128), 96 × 64, 48 × 32, 24 × 16 and 12 × 8,then manually paste your results on the report. 

2. Down-scale to 300 × 200, then paste your result. 

3. Up-scale to 450 × 300, then paste your result. 

4. Scale to 500 × 200, then paste your result.

5. Detailedly discuss how you implement the scaling operation, i.e., the “scale” function, in lessthan 2 pages. Please focus on the algorithm part. If you have found interesting phenomenonsin your scaling results, analyses and discussions on them are strongly welcomed and maybring you bonuses. But please don’t widely copy/paste your codes in the report, since yourcodes are also submitted. 

Answer:

function [output] = scale1(I, Width, Height)
img = imread(I);
[row,col] = size(img);
%确定缩放比例
ratioH = Height/row;
ratioW = Width/col;
output = zeros(Height,Width);
%拓宽矩阵,赋值,处理边界
temp = zeros(row+2,col+2);
%拷贝原矩阵
for x = 1:row
    for y = 1:col
        temp(x+1,y+1) = img(x,y);
    end
end
%边界处理
for y = 1:col
    temp(1,y+1) = img(1,y);
    temp(row+2,y+1) = img(row,y);
end
for x = 1:row
    temp(x+1,1) = img(x,1);
    temp(x+1,col+2) = img(x,col);
end
temp(1,1) = img(1,1);
temp(1,col+2) = img(1,col);
temp(row+2,1) = img(row,1);
temp(row+2,col+2) = img(row,col);
%双线性内插值算法
for j = 1:Width
    for i = 1:Height
        jj = (j-1)/ratioW;
        ii = (i-1)/ratioH;
        pj = floor(jj);
        pi = floor(ii);
        u = ii - pi;
        v = jj - pj;
        pi = pi + 1;
        pj = pj + 1;
        output(i,j) = (1-u)*(1-v)*temp(pi,pj) +(1-u)*v*temp(pi,pj+1)...
                    + u*(1-v)*temp(pi+1,pj) +u*v*temp(pi+1,pj+1);
    end
end
output = uint8(output);
figure
imshow(output)
end

algorithm illustrate:

对图片的缩放是通过双线性差值法实现的。具体算法如下:对于一个目的像素,设置坐标通过反向变换得到的浮点坐标为(i+u,j+v) (其中 i、j 均为浮点坐标的整数部分,u、v 为浮点坐标的小数部分,是取值[0,1)区间的浮点数),则这个像素得值 f(i+u,j+v) 可由原图像中坐标为 (i,j)、(i+1,j)、(i,j+1)、(i+1,j+1)所对应的周围四个像素的值决定,即:f(i+u,j+v) = (1-u)(1-v)f(i,j) + (1-u)vf(i,j+1) + u(1-v)f(i+1,j) + uvf(i+1,j+1)其中 f(i,j)表示源图像(i,j)处的的像素值。通过对目标图像的每个像素点进行如上运算估值即可。对于边界像素点,我是通过拓宽了原图像对应矩阵来避免越界。



猜你喜欢

转载自blog.csdn.net/qq_34200964/article/details/79517715