我正在关注this tutorial为我的Android应用创建图像转换器。我已将代码转换为Java但结果并不完全符合我的预期。我想知道是否有任何方法可以修改代码,以便可以将图像转换为与教程相似。
到目前为止我的代码:
// This method is called when a button is pressed.
//Unlike the tutorial post, the 4 corner coordinates are manually marked by the user.
// Bitmap is the image taken by the user
private void thresholdPhoto(Bitmap bitmap) {
// I am using the OpenCV library so I need to convert it to a matrix
Mat matrixImage = new Mat();
Utils.bitmapToMat(bitmap, matrixImage);
// Convert to gray
Imgproc.cvtColor(matrixImage, matrixImage, Imgproc.COLOR_BGR2GRAY);
// Gaussian blur
Imgproc.GaussianBlur(matrixImage, matrixImage, new Size(5,5), 0);
// The conversion to gray and blurring is for my app later on but I don't think it should affect the warping process.
// Get the coordinates marked by the user
PointF bottomRight = new PointF(polygonView.pointer4.getX(), polygonView.pointer4.getY());
PointF bottomLeft = new PointF(polygonView.pointer3.getX(), polygonView.pointer3.getY());
PointF topRight = new PointF(polygonView.pointer2.getX(), polygonView.pointer2.getY());
PointF topLeft = new PointF(polygonView.pointer1.getX(), polygonView.pointer1.getY());
// Code following the tutorial post above
double widthA = Math.sqrt(Math.pow(bottomRight.x-bottomLeft.x, 2)+Math.pow(bottomRight.y-bottomLeft.y, 2));
double widthB = Math.sqrt(Math.pow(topRight.x-topLeft.x, 2)+Math.pow(topRight.y-topLeft.y, 2));
double maxWidth = Math.max(widthA, widthB);
double heightA = Math.sqrt(Math.pow(topRight.x-bottomRight.x, 2)+Math.pow(topRight.y-bottomRight.y, 2));
double heightB = Math.sqrt(Math.pow(topLeft.x-bottomLeft.x, 2)+Math.pow(topLeft.y-bottomLeft.y, 2));
double maxHeight = Math.max(heightA, heightB);
// To apply the final perspective transform I had to create new Matrices
Point tl = new Point(topLeft.x, topLeft.y);
Point tr = new Point(topRight.x, topLeft.y);
Point bl = new Point(bottomLeft.x, bottomLeft.y);
Point br = new Point(bottomRight.x, bottomRight.y);
MatOfPoint2f src = new MatOfPoint2f(tl, tr, br, bl);
MatOfPoint2f dst = new MatOfPoint2f(
new Point(0,0), // top left
new Point(maxWidth-1, 0), // top right
new Point(maxWidth-1, maxHeight-1), // bottom right
new Point(0, maxHeight-1) // bottom left
);
Mat perspectiveTransform = Imgproc.getPerspectiveTransform(src, dst);
Imgproc.warpPerspective(matrixImage, matrixImage, perspectiveTransform, new Size(maxWidth, maxHeight));
// Convert matrix back to bitmap to display inside imageview. This final part is just for my visualization purposes.
Bitmap bm = Bitmap.createBitmap(matrixImage.cols(), matrixImage.rows(),Bitmap.Config.ARGB_8888);
Utils.matToBitmap(matrixImage, bm);
polygonView.setVisibility(View.GONE);
scannedImage.setImageBitmap(bm);
}
使用的图像:
翘曲的结果并不是我想要的,所以我想知道是否有其他参数/设置我可以修改以使其更好。