I have been searching the internet for a while now. The problem is that the solution to my problem in mostly available in either python or C++. I have tried to replicate the code but no luck.
I have detected a card (Rectangle) and I am able to crop it if the rectangle is straight but if the rectangle is rotated at an angle I get a image that cuts the card.
Image showing what I want to achieve...
My working code for straight Image.
Bitmap abc = null;
Point topleft, topright, bottomleft, bottomright;
float xRatio = (float) original.getWidth() / sourceImageView.getWidth();
float yRatio = (float) original.getHeight() / sourceImageView.getHeight();
float x1 = (points.get(0).x) * xRatio;
float x2 = (points.get(1).x) * xRatio;
float x3 = (points.get(2).x) * xRatio;
float x4 = (points.get(3).x) * xRatio;
float y1 = (points.get(0).y) * yRatio;
float y2 = (points.get(1).y) * yRatio;
float y3 = (points.get(2).y) * yRatio;
float y4 = (points.get(3).y) * yRatio;
Point p1 = new Point(x1, y1);
Point p2 = new Point(x2, y2);
Point p3 = new Point(x3, y3);
Point p4 = new Point(x4, y4);
List<Point> newpoints = new ArrayList<Point>();
newpoints.add(p1);
newpoints.add(p2);
newpoints.add(p3);
newpoints.add(p4);
Collections.sort(newpoints, new Comparator<Point>() {
public int compare(Point o1, Point o2) {
return Double.compare(o1.x, o2.x);
}
});
if (newpoints.get(0).y > newpoints.get(1).y) {
bottomleft = newpoints.get(0);
topleft = newpoints.get(1);
} else {
bottomleft = newpoints.get(1);
topleft = newpoints.get(0);
}
if (newpoints.get(2).y > newpoints.get(3).y) {
bottomright = newpoints.get(2);
topright = newpoints.get(3);
} else {
bottomright = newpoints.get(3);
topright = newpoints.get(2);
}
final Mat newimage = new Mat();
Bitmap bmp32 = original.copy(Bitmap.Config.ARGB_8888, true);
org.opencv.android.Utils.bitmapToMat(bmp32, newimage);
final float dd = getAngle(bottomleft, bottomright);
Mat finalMat = new Mat(newimage, new org.opencv.core.Rect(topleft, bottomright));
abc = RotateBitmap(createBitmapfromMat(finalMat), (-dd));
Current code when rectangle is straight :
Current code when rectangle is rotated: