Rotating an image is a common task. This article reviews how to rotate a matrix using JavaCV.

These tutorials utilize GoatImage. The Image object used in the code examples comes from this library.

Related Articles:

- JavaCv Basics: IplImage
- JavaCv Basics: Contouring
- Cropping
- Splitting Objects
- JavaCV Basics: Basic Image Processing

## Rotation Matrix

The rotation matrix is used to map from one pixel position to another. The matrix, shown below, uses trigonometric functions.

Rotation is a linear transformation. A linear transformation uses a function to map from one matrix to another. In image processing, the matrix kernel is used to perform this mapping.

## Rotation in JavaCV 3

Rotation in JavaCV 3 utilizes a generated rotation matrix and the warp affine function. The function *getRotationMatrix2D* generates a two dimensional matrix using a center *Point2f*, angle, and a scale.

/** * Rotate an image by a specified angle using an affine transformation. * * @param image The image to rotate * @param angle The angle to rotate by * @return A rotated Image */ def rotateImage(image : Image,angle : Double):Image={ val srcMat = new Mat(image.image) val outMat = new Mat(srcMat.cols(),srcMat.rows(),srcMat.`type`()) val cosv = Math.cos(angle) val sinv = Math.sin(angle) val width = image.image.width val height = image.image.height val cx = width/2 val cy = height/2 //(image.image.width*cosv + image.image.height*sinv, image.image.width*sinv + image.image.height*cosv); val rotMat : Mat = getRotationMatrix2D(new Point2f(cx.toInt,cy.toInt),angle,1) warpAffine(srcMat,outMat,rotMat,srcMat.size()) new Image(new IplImage(outMat),image.name,image.itype) }

## The Angle

The angle in OpenCV and thus JavaCV is centered at -45 degrees due to the use of vertical contouring. If an image is less than -45 degrees, adding 90 degrees will correct this offset.

val angle = if(minAreaRect.angle < -45.0) minAreaRect.angle + 90 else minAreaRect.angle

## Conclusion

In this tutorial we reviewed the function in GoatImage for rotating images using OpenCv. The functions *getRotationMatrix2D* and *warpAffine* were introduced. Basic kernel processing was introduced as well.