Java调用OpenCV进行Hough变换直线检测

来源:互联网 发布:js request是什么 编辑:程序博客网 时间:2024/04/30 18:29

   private BitmapHoughTransFormLine(Bitmap bmp)

   {

    Mat rgbMat =new Mat();  //存储原图像的矩阵

    Mat grayMat =new Mat(); //存储灰度图像的矩阵

        Mat lineMat = new Mat();//存储检测出的直线坐标的矩阵,每个element4个通道,第12个通道为直线的1个端点,第34个通道为直线的另1个端点

       

        Utils.bitmapToMat(bmp, rgbMat);

        Imgproc.cvtColor(rgbMat,grayMat, Imgproc.COLOR_RGB2GRAY);//灰度化

        Imgproc.Canny(grayMat, grayMat,50, 200);                 //Canny边缘检测

       

        /* Hough变换标记直线

         * public static void HoughLinesP(Matimage, Mat lines, doublerho, double theta, int threshold)

         *    image - 8-bit, single-channel binary source image. The image may bemodified by the function.

         *    lines - Output vector of lines. Each line is represented by a 4-elementvector (x_1, y_1, x_2, y_2),

         *                where (x_1,y_1) and (x_2, y_2) arethe ending points of each detected line segment.

         *    rho - Distance resolution of the accumulator in pixels.

        *    theta - Angle resolution of theaccumulator in radians.

         *    threshold - Accumulator threshold parameter. Only those lines arereturned that get enough votes (>threshold).

         */

        Imgproc.HoughLinesP(grayMat,lineMat, 1, Math.PI/180,50, 50.0, 10.0);

       

        int[] a =new int[(int)lineMat.total()*lineMat.channels()];//数组a存储检测出的直线端点坐标

        lineMat.get(0,0,a);

   

        for (int i = 0; i < a.length; i += 4)

        {

           Core.line(grayMat,new Point(a[i], a[i+1]), new Point(a[i+2], a[i+3]), new Scalar(255, 0, 255),4);

        }

 

        //创建一个图像

        Bitmap newBmp = Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(), Config.RGB_565);

        //将矩阵grayMat转换为图像 

        Utils.matToBitmap(grayMat,newBmp);

       

        rgbMat = null;

        grayMat = null;

        lineMat = null;

        a = null;

       

        return newBmp;

   }

0 0
原创粉丝点击