参考链接:
https://www.cnblogs.com/skyfsm/p/6882853.html
https://blog.csdn.net/i_chaoren/article/details/78313360
https://blog.csdn.net/keith_bb/article/details/56331356
void cv::warpAffine (InputArray src,
OutputArray dst,
InputArray M,
Size dsize,
int flags = INTER_LINEAR,
int borderMode = BORDER_CONSTANT,
const Scalar & borderValue = Scalar()
)
代码
public static void main(String[] args) {
System.load("F:\\opencv\\x64\\opencv_java401.dll");
Mat src = Imgcodecs.imread("D:\\my\\test.jpg");
/******************************方式一******************************/
//第一种仿射变换的调用方式:三点法
Point[] srcPoints = new Point[3]; //原图中的三点
Point[] dstPoints = new Point[3]; //目标图中的三点
//三个点对的值,上面也说了,只要知道你想要变换后图的三个点的坐标,就可以实现仿射变换
srcPoints[0] = new Point(0,0);
srcPoints[1] = new Point(src.cols()-1,0);
srcPoints[2] = new Point(0,src.rows()-1);
//映射后的三个坐标值
dstPoints[0] = new Point(src.cols() * 0.0, src.rows()* 0.33);
dstPoints[1] = new Point(src.cols() * 0.85, src.rows()* 0.25);
dstPoints[2] = new Point(src.cols() * 0.15, src.rows()* 0.70);
MatOfPoint2f mofSrc = new MatOfPoint2f(srcPoints);
MatOfPoint2f mofDst = new MatOfPoint2f(dstPoints);
//由三个点对计算变换矩阵
Mat gAffine1 = Imgproc.getAffineTransform(mofSrc, mofDst);
//仿射变换
Mat warpAffineDst1 = new Mat();
Imgproc.warpAffine(src, warpAffineDst1, gAffine1, src.size());
Imgcodecs.imwrite("D:\\my\\warpAffineDst1.jpg", warpAffineDst1);
/******************************方式二******************************/
//第二种仿射变换的调用方式:直接指定角度和比例
// 计算关于图像中心的旋转矩阵
Point center = new Point(src.cols()/2.0, src.rows()/2.0);
double angle = 35.0; // >0 逆时针, <0 顺时针
//旋转的同时也可以放缩
double scale = 0.8;
/// 根据以上参数得到旋转矩阵
Mat gAffine2 = Imgproc.getRotationMatrix2D(center, angle, scale);
//仿射变换(可以选择背景填充颜色)
Mat warpAffineDst2 = new Mat();
Imgproc.warpAffine(src, warpAffineDst2, gAffine2, src.size(), Imgproc.INTER_LINEAR, Core.BORDER_CONSTANT, new Scalar(255, 0, 0));
Imgcodecs.imwrite("D:\\my\\warpAffineDst2.jpg", warpAffineDst2);
}
原图
方式一
方式二
简单应用
public static void main(String[] args) {
System.load("F:\\opencv\\x64\\opencv_java401.dll");
Mat src = Imgcodecs.imread("D:\\my\\warpAffineDst1.jpg");
Point[] srcPoints = new Point[3];
Point[] dstPoints = new Point[3];
// 原图内容坐标
// 左上(0, 103), 左下(74, 218), 右下(499, 193), 右上(425, 78)
srcPoints[0] = new Point(0, 103);
srcPoints[1] = new Point(74, 218);
srcPoints[2] = new Point(499, 193);
dstPoints[0] = new Point(0, 0);
dstPoints[1] = new Point(0, src.height() - 1);
dstPoints[2] = new Point(src.width() - 1, src.height() - 1);
MatOfPoint2f mofSrc = new MatOfPoint2f(srcPoints);
MatOfPoint2f mofDst = new MatOfPoint2f(dstPoints);
//由三个点对计算变换矩阵
Mat gAffine1 = Imgproc.getAffineTransform(mofSrc, mofDst);
//仿射变换
Mat warpAffineDst = new Mat();
Imgproc.warpAffine(src, warpAffineDst, gAffine1, new Size(src.width(), src.height()));
Imgcodecs.imwrite("D:\\my\\warpAffineDst.jpg", warpAffineDst);
}
原图(方式一结果图)
结果图