I want a method to shear an image without using the built-in functions (methods) of MATLAB. How can I do this?
Form a data table of the X,Y locations of each pixel in the image. Then map these points to new points by multiplying each point by a shear matrix. I'm not familiar with Matlab, so I cannot help you further.
Let's generate a sample matrix:
image=reshape(1:25,[5 5])
image =
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
5 10 15 20 25
To shear it without using MATLAB's in-built functions, just do a remapping of pixels:
for i=1:size(image,1)-1
image(i+1,:)=image(i+1,[end-i+1:end 1:end-i]);
end
image =
1 6 11 16 21
22 2 7 12 17
18 23 3 8 13
14 19 24 4 9
10 15 20 25 5
Shearing it the other way, or shearing vertically, should be a straightforward extension of this.
I'm assuming that "without using the built-in functions" means "not using the Image Processing Toolbox".
Using just core MATLAB functions, image shearing can be done using a shear matrix and the function INTERP2. The shear matrix can be used to compute a new set of sheared coordinates for the image pixels, and INTERP2 can then be used to interpolate the image values at these new coordinates. Here's an example of applying an x-direction shear to a sample image:
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
And the following figure shows the shear applied to the image by the above code:
You can adjust the direction (x or y) and magnitude of the shear by modifying the off-diagonal terms of the shear matrix. You can also change which edge of the image (top, bottom, left, or right) is held fixed when the shear is done by first flipping the image in a given direction, performing the interpolation, then flipping the image back. You can use the functions FLIPUD and FLIPLR to change the fixed edge for x-direction and y-direction shears, respectively. Here are some examples of different shears: