Matrix Multiplication
Wednesday, March 9th, 2005...6:19 am
Multiplying matrices is one of those subjects that all comp sci students are taught but no one ever explains why it’s useful. And, if you ever figure out why you might want to multiply a matrix, you have to wait several years before you’re presented with an oppurtunity to do so.
Last night I needed to vertically flip an image in Java. To do this, you need to become familiar with java.awt.geom.AffineTransform. AffineTransform works by multiplying each coordinate with a given matrix. There are utility methods for scaling and rotating an image (a few examples here) but nothing for flipping (probably because it’s not that hard). The matrix for vertically flipping an image is:
1 0 00 -1 H0 0 1
Where H is the height of the image you wish to flip. Since the bottom row never changes, the values of interest are the top 6.
The matrix values are supplied to AffineTransform and the operation is actually performed on an image using java.awt.image.AffineTransformOp.
The following code performs the operation:public static BufferedImage flip(BufferedImage image){
AffineTransform transform = new AffineTransform(1, 0, 0, -1, 0, image.getHeight());
AffineTransformOp operation = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
newImage = operation.filter(image, newImage);
return newImage;
}
Example:
Leave a Reply