下面的代码可以成功地旋转图像,但它会切掉图像的角落并且旋转方向错误!这是一个可能重复的问题,请参考: 使用cv::warpAffine旋转cv::Mat时如何偏移目标图像
Mat cvImage = Highgui.imread("mnt/sdcard/canvasgrid.png");
int degrees = 20;
Point center = new Point(cvImage.cols()/2, cvImage.rows()/2);
Mat rotImage = Imgproc.getRotationMatrix2D(center, degrees, 1.0);
Mat dummy = cvWaterImage;
Imgproc.warpAffine(cvImage, dummy, rotImage, cvImage.size());
rotatedImage = dummy;
Highgui.imwrite("mnt/sdcard/imageRotate.png",rotatedImage);
另外,旋转后的背景是黑色的,但我希望它是透明的。
我做错了什么吗? 谢谢
编辑已经解决
首先获得旋转图片的新宽度/高度
double radians = Math.toRadians(rotationAngle);
double sin = Math.abs(Math.sin(radians));
double cos = Math.abs(Math.cos(radians));
int newWidth = (int) (scaledImage.width() * cos + scaledImage.height() * sin);
int newHeight = (int) (scaledImage.width() * sin + scaledImage.height() * cos);
int[] newWidthHeight = {newWidth, newHeight};
// 创建新的尺寸框(newWidth/newHeight)
int pivotX = newWidthHeight[0]/2;
int pivotY = newWidthHeight[1]/2;
// 旋转的水印图片
org.opencv.core.Point center = new org.opencv.core.Point(pivotX, pivotY);
Size targetSize = new Size(newWidthHeight[0], newWidthHeight[1]);
//现在创建另一个矩阵,以便我们可以用它进行映射
Mat targetMat = new Mat(targetSize, scaledImage.type());
int offsetX = (newWidthHeight[0] - scaledImage.width()) / 2;
int offsetY = (newWidthHeight[1] - scaledImage.height()) / 2;
// 居中水印
Mat waterSubmat = targetMat.submat(offsetY, offsetY + scaledImage.height(), offsetX, offsetX + scaledImage.width());
scaledImage.copyTo(waterSubmat);
Mat rotImage = Imgproc.getRotationMatrix2D(center, waterMarkAngle, 1.0);
Mat resultMat = new Mat(); // CUBIC
Imgproc.warpAffine(targetMat, resultMat, rotImage, targetSize, Imgproc.INTER_LINEAR, Imgproc.BORDER_CONSTANT, colorScalar);
//你的结果矩阵应该像这样 未裁剪的图像 //顺便说一下,提供的链接和这个解决方案之间有很大的区别