public static ImageCV getRotatedImage(Mat source, double angle, double centerx, double centery) { if (isEqualToZero(angle)) { return ImageCV.toImageCV(source); } Mat srcImg = Objects.requireNonNull(source); Point ptCenter = new Point(centerx, centery); Mat rot = Imgproc.getRotationMatrix2D(ptCenter, -angle, 1.0); ImageCV dstImg = new ImageCV(); // determine bounding rectangle Rect bbox = new RotatedRect(ptCenter, srcImg.size(), -angle).boundingRect(); // double[] matrix = new double[rot.cols() * rot.rows()]; // // adjust transformation matrix // rot.get(0, 0, matrix); // matrix[2] += bbox.width / 2.0 - centerx; // matrix[rot.cols() + 2] += bbox.height / 2.0 - centery; // rot.put(0, 0, matrix); Imgproc.warpAffine(srcImg, dstImg, rot, bbox.size()); return dstImg; }
Imgproc.warpAffine(image, image, mapMatrix, bbox.size(), Imgproc.INTER_LINEAR);
static Mat rotateRect(Mat mat, RotatedRect rect, double degrees) { // get the affine mattrix Mat mapMatrix = Imgproc.getRotationMatrix2D(rect.center, degrees, 1.0); // adjust rect angle to coincide with the rotation. This modifies the model rect.angle -= degrees; // find the new bbox for the now rotated rect Rect bbox = rect.boundingRect(); // adjust transformation matrix double[] cx = mapMatrix.get(0, 2); double[] cy = mapMatrix.get(1, 2); cx[0] += bbox.width / 2D - rect.center.x; cy[0] += bbox.height / 2D - rect.center.y; mapMatrix.put(0, 2, cx); mapMatrix.put(1, 2, cy); // rotate and crop Imgproc.warpAffine(mat, mat, mapMatrix, bbox.size(), Imgproc.INTER_LINEAR); mapMatrix.release(); // adjust the model to the new center bbox = rect.boundingRect(); rect.center.x = bbox.width / 2.0; rect.center.y = bbox.height / 2.0; return mat; }
private static Mat rotate(Mat mat, double rotation) { if (rotation == 0D) { return mat; } // See: // http://stackoverflow.com/questions/22041699/rotate-an-image-without-cropping-in-opencv-in-c Point center = new Point(mat.width() / 2D, mat.height() / 2D); Mat mapMatrix = Imgproc.getRotationMatrix2D(center, rotation, 1.0); // determine bounding rectangle Rect bbox = new RotatedRect(center, mat.size(), rotation).boundingRect(); // adjust transformation matrix double[] cx = mapMatrix.get(0, 2); double[] cy = mapMatrix.get(1, 2); cx[0] += bbox.width / 2D - center.x; cy[0] += bbox.height / 2D - center.y; mapMatrix.put(0, 2, cx); mapMatrix.put(1, 2, cy); Mat dst = new Mat(bbox.width, bbox.height, mat.type()); Imgproc.warpAffine(mat, dst, mapMatrix, bbox.size(), Imgproc.INTER_LINEAR); mat.release(); mapMatrix.release(); return dst; }
Imgproc.warpAffine(mat, dst, mapMatrix, bbox.size(), Imgproc.INTER_LINEAR); mat.release();