opencv3_java 图像透视视角转换Perspective warpPerspective

图像透视视角转换Perspective warpPerspective


package opencv_java_demo;

import java.util.List;
import org.opencv.core.*;
import org.opencv.imgcodecs.*;
import org.opencv.imgproc.*;
import org.opencv.utils.Converters;

public class Perspective {

	public static void main(String[] args) {
		try{
			System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
			
			Mat src=Imgcodecs.imread("./images/lenna.jpg");
			//读取图像到矩阵中
			if(src.empty()){
				throw new Exception("no file");
			}
			
			int xMargin,yMargin;
			int x0=src.cols()/4;
			int x1=(src.cols()/4)*3;
			int y0=src.cols()/4;
			int y1=(src.cols()/4)*3;
			Mat dst=new Mat();
			
			List<Point> listSrcs=java.util.Arrays.asList(new Point(x0,y0),new Point(x0,y1),new Point(x1,y1),new Point(x1,y0));
			Mat srcPoints=Converters.vector_Point_to_Mat(listSrcs,CvType.CV_32F);
			
			xMargin=src.cols()/10;
			yMargin=src.rows()/10;
			List<Point> listDsts=java.util.Arrays.asList(new Point(x0+xMargin,y0+yMargin),listSrcs.get(1),listSrcs.get(2),new Point(x1-xMargin,y0+yMargin));
			Mat dstPoints=Converters.vector_Point_to_Mat(listDsts,CvType.CV_32F);
			
			Mat perspectiveMmat=Imgproc.getPerspectiveTransform(srcPoints, dstPoints);
			Imgproc.warpPerspective(src, dst, perspectiveMmat, src.size(),Imgproc.INTER_LINEAR);
			Imgcodecs.imwrite("./images/dst0.jpg",dst);
			
			xMargin=src.cols()/8;
			yMargin=src.cols()/8;
			listDsts.set(0, listSrcs.get(0));
			listDsts.set(1, listSrcs.get(1));
			listDsts.set(2, new Point(x1-xMargin,y1-yMargin));
			listDsts.set(3, new Point(x1-xMargin,y0-yMargin));
			dstPoints=Converters.vector_Point_to_Mat(listDsts,CvType.CV_32F);
			
			perspectiveMmat=Imgproc.getPerspectiveTransform(srcPoints, dstPoints);
			Imgproc.warpPerspective(src, dst, perspectiveMmat, src.size(),Imgproc.INTER_LINEAR);
			Imgcodecs.imwrite("./images/dst1.jpg", dst);
			
			xMargin=src.cols()/6;
			yMargin=src.cols()/6;
			listDsts.set(0, new Point(x0+xMargin,y0+yMargin));
			listDsts.set(1, listSrcs.get(1));
			listDsts.set(2, new Point(x1-xMargin,y1-yMargin));
			listDsts.set(3, listSrcs.get(3));
			dstPoints=Converters.vector_Point_to_Mat(listDsts,CvType.CV_32F);
			
			perspectiveMmat=Imgproc.getPerspectiveTransform(srcPoints, dstPoints);
			Imgproc.warpPerspective(src, dst, perspectiveMmat, src.size(),Imgproc.INTER_LINEAR);
			
			Imgcodecs.imwrite("./images/dst2.jpg", dst);
		}catch(Exception e){
			System.out.println("例外:" + e);
		}

	}

}







你可能感兴趣的:(java,opencv3)