天天看點

EmguCv圖像的矩(計算輪廓中心)

//圖像的矩,計算圖形的中心
        private void btn_moments_Click(object sender, EventArgs e)
        {
            if (ib_original.Image != null)
            {
                Mat src = new Image<Bgr, byte>(ib_original.Image.Bitmap).Mat;
                Mat dst = new Mat();

                CvInvoke.Canny(src, dst, 120, 180);

                VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();

                CvInvoke.FindContours(dst, contours, null, Emgu.CV.CvEnum.RetrType.External,
                    Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxNone);

                //篩選出面積不為0的輪廓并畫出
                VectorOfVectorOfPoint use_contours = new VectorOfVectorOfPoint();

                for (int i = 0; i < contours.Size; i++)
                {
                    //擷取獨立的連通輪廓
                    VectorOfPoint contour = contours[i];

                    //計算連通輪廓的面積
                    double area = CvInvoke.ContourArea(contour);
                    //進行面積篩選
                    if (area > 0)
                    {
                        //添加篩選後的連通輪廓
                        use_contours.Push(contour);
                    }
                }
                CvInvoke.DrawContours(src, use_contours, -1, new MCvScalar(0, 0, 255));

                //計算輪廓中心并畫出
                int ksize = use_contours.Size;

                double[] m00 = new double[ksize];
                double[] m01 = new double[ksize];
                double[] m10 = new double[ksize];
                Point[] gravity = new Point[ksize];//用于存儲輪廓中心點坐标
                MCvMoments[] moments = new MCvMoments[ksize];

                for (int i = 0; i < ksize; i++)
                {
                    VectorOfPoint contour = use_contours[i];
                    //計算目前輪廓的矩
                    moments[i] = CvInvoke.Moments(contour, false);

                    m00[i] = moments[i].M00;
                    m01[i] = moments[i].M01;
                    m10[i] = moments[i].M10;
                    int x = Convert.ToInt32(m10[i] / m00[i]);//計算目前輪廓中心點坐标
                    int y = Convert.ToInt32(m01[i] / m00[i]);
                    gravity[i] = new Point(x, y);
                }

                //畫出中心點位置
                foreach (Point cent in gravity)
                {
                    CvInvoke.Circle(src, cent, 2, new MCvScalar(0, 0, 255), 2);
                }

                ib_result.Image = src;
            }
        }
           
EmguCv圖像的矩(計算輪廓中心)