在android中使用opencv进行图像旋转会切断图像的边缘

Kha*_*war 8 android opencv image rotation

可能重复:
使用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);
Run Code Online (Sandbox Code Playgroud)

原始图像

旋转图像

PLUS旋转图像的背景是黑色的,但我希望它是透明的.

我做错了什么?谢谢

编辑已解决

首先获得旋转图像的新宽度/高度

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};
Run Code Online (Sandbox Code Playgroud)

//创建新大小的框(newWidth/newHeight)

int pivotX = newWidthHeight[0]/2; 
int pivotY = newWidthHeight[1]/2;
Run Code Online (Sandbox Code Playgroud)

//旋转水像

org.opencv.core.Point center = new org.opencv.core.Point(pivotX, pivotY);
Size targetSize = new Size(newWidthHeight[0], newWidthHeight[1]);
Run Code Online (Sandbox Code Playgroud)

//现在创建另一个垫子,所以我们可以用它来进行贴图

Mat targetMat = new Mat(targetSize, scaledImage.type());

int offsetX = (newWidthHeight[0] - scaledImage.width()) / 2;
int offsetY = (newWidthHeight[1] - scaledImage.height()) / 2;
Run Code Online (Sandbox Code Playgroud)

//集中水印

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);
Run Code Online (Sandbox Code Playgroud)

//你的resultMat看起来像这样没有图像 // BTW ..提供的链接和这个解决方案之间存在巨大的差异

Nip*_*pey 2

我刚刚阅读了文档:ImgProc.warpAffine

\n\n

只是摘录:

\n\n
void warpAffine(InputArray src, OutputArray dst, InputArray M, Size dsize, [...]);\n//Parameters: dsize \xe2\x80\x93 Size of the destination image.\n
Run Code Online (Sandbox Code Playgroud)\n\n

请尝试以下操作:

\n\n
Imgproc.warpAffine(cvImage, dummy, rotImage, dummy.size());\n
Run Code Online (Sandbox Code Playgroud)\n\n

为了调整透明度,请修改最后的参数:

\n\n
Imgproc.warpAffine(cvImage, dummy, rotImage, dummy.size(), INTER_LINEAR, BORDER_TRANSPARENT);\n
Run Code Online (Sandbox Code Playgroud)\n