例子使用的版本为3.4.0,安装配置网上资料比较多。
代码为本地测试时候的版本,所以会有点乱。
import org.opencv.core.*; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import org.opencv.utils.Converters; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author liuxf * @date 2018/10/22 14:28 * @param * @return */ public class OpenCVJavaTest2 { static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); } public static void main(String[] args) { String imgUrl = "F:\\1.jpg"; Mat src = Imgcodecs.imread(imgUrl ,1); Mat src_gray = new Mat(); test1(src,src_gray); } public static void test1(Mat src ,Mat src_gray){ List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); List<MatOfPoint> markContours = new ArrayList<MatOfPoint>(); System.loadLibrary(Core.NATIVE_LIBRARY_NAME); /**图片太小就放大**/ if (src.width()*src.height()<90000){ Imgproc.resize(src,src,new Size(800,600)); } Mat src_all=src.clone(); //彩色图转灰度图 Imgproc.cvtColor(src ,src_gray ,Imgproc.COLOR_RGB2GRAY); //对图像进行平滑处理 Imgproc.GaussianBlur(src_gray, src_gray, new Size(3,3), 0); /**Imgcodecs.imwrite("F:\\output\\EH.jpg", src_gray);**/ Imgproc.Canny(src_gray,src_gray,112,255); /**Imgcodecs.imwrite("F:\\output\\1-2.jpg", src_gray);**/ Mat hierarchy = new Mat(); Imgproc.findContours(src_gray ,contours ,hierarchy ,Imgproc.RETR_TREE ,Imgproc.CHAIN_APPROX_NONE); for ( int i = 0; i< contours.size(); i++ ) { MatOfPoint2f newMtx = new MatOfPoint2f( contours.get(i).toArray() ); RotatedRect rotRect = Imgproc.minAreaRect( newMtx ); double w = rotRect.size.width; double h = rotRect.size.height; double rate = Math.max(w, h)/Math.min(w, h) ; /*** * 长短轴比小于1.3,总面积大于60 */ if (rate < 1.3 && w < src_gray.cols()/4 && h<src_gray.rows()/4 && Imgproc.contourArea(contours.get(i))>60) { /*** * 计算层数,二维码角框有五层轮廓(有说六层),这里不计自己这一层,有4个以上子轮廓则标记这一点 */ dou