如何在不使用内置函数的情况下在MATLAB中剪切图像?

1 matlab image-processing

我想要一种方法来剪切图像,而不使用MATLAB的内置函数(方法).我怎样才能做到这一点?

gno*_*ice 6

我假设"不使用内置函数"意味着"不使用图像处理工具箱 ".

仅使用核心MATLAB函数,可以使用剪切矩阵和函数完成图像剪切interp2.剪切矩阵可用于计算图像像素的一组新剪切坐标,interp2然后可用于在这些新坐标处插值图像值.以下是将x方向剪切应用于样本图像的示例:

img = imread('cameraman.tif');  % Read a sample grayscale image
img = double(img);              % Convert the image to type double
[nRows, nCols] = size(img);     % Get the image size
[x, y] = meshgrid(1:nRows, 1:nCols);  % Create coordinate values for the pixels
coords = [x(:).'; y(:).'];            % Collect the coordinates into one matrix
shearMatrix = [1 0.2; 0 1];           % Create a shear matrix
newCoords = shearMatrix*coords;       % Apply the shear to the coordinates
newImage = interp2(img, ...              % Interpolate the image values
                   newCoords(1, :), ...  %   at the new x coordinates
                   newCoords(2, :), ...  %   and the new y coordinates
                   'linear', ...         %   using linear interpolation
                   0);                   %   and 0 for pixels outside the image
newImage = reshape(newImage, nRows, nCols);  % Reshape the image data
newImage = uint8(newImage);                  % Convert the image to type uint8
Run Code Online (Sandbox Code Playgroud)

下图显示了上述代码应用于图像的剪切:

在此输入图像描述

您可以通过修改剪切矩阵的非对角线项来调整剪切的方向(x或y)和大小.通过首先在给定方向上翻转图像,执行插值,然后向后翻转图像,您还可以在剪切完成时更改图像的哪个边缘(顶部,底部,左侧或右侧).您可以使用这些功能flipudfliplr分别更改x方向和y方向剪切的固定边缘.以下是不同剪刀的一些示例:

在此输入图像描述