Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

image rotation with opencv in android cuts off the edges of an image [duplicate]

Possible Duplicate:
Rotate cv::Mat using cv::warpAffine offsets destination image

Code below can rotate an image successfully but it cuts off corners of the image and it rotates in wrong direction!!

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);

original Image

rotated Image

PLUS rotated image's background is black but I want it to be transparent.

Am I doing anything wrong?? Thanks

EDIT SOLVED

first of all get new width/height of rotated image

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};

// create new sized box (newWidth/newHeight)

int pivotX = newWidthHeight[0]/2; 
int pivotY = newWidthHeight[1]/2;

// rotating water image

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

// now create another mat, so we can use it for mapping

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

int offsetX = (newWidthHeight[0] - scaledImage.width()) / 2;
int offsetY = (newWidthHeight[1] - scaledImage.height()) / 2;

// Centralizing watermark

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);

// your resultMat with look like this NOT CROPPED Image // BTW.. there is a huge differce between provided link and this solution

like image 741
Khawar Avatar asked Oct 12 '12 05:10

Khawar


1 Answers

I just read through the documentation: ImgProc.warpAffine

Just an extract:

void warpAffine(InputArray src, OutputArray dst, InputArray M, Size dsize, [...]);
//Parameters: dsize – Size of the destination image.

Please try the following:

Imgproc.warpAffine(cvImage, dummy, rotImage, dummy.size());

In order to play with the transparency, fiddle with the parameter at the end:

Imgproc.warpAffine(cvImage, dummy, rotImage, dummy.size(), INTER_LINEAR, BORDER_TRANSPARENT);
like image 81
Nippey Avatar answered Nov 13 '22 12:11

Nippey