本文實例講述了C#圖像處理之圖像目標質心檢測的方法。分享給大家供大家參考。具體如下:
//采用二值化圖像,圖像中黑色表示背景,白色表示目標//定義質心計算函數private int[] CentPoints(Bitmap src){ //定義存儲質心坐標的數組變量 int[] CentreP = new int[2]; int M00 = 0, M01 = 0, M10 = 0; Rectangle rect = new Rectangle(0, 0, src.Width, src.Height); System.Drawing.Imaging.BitmapData bmpData = src.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb); unsafe { int stride = bmpData.Stride; byte* p; byte* pIn = (byte*)bmpData.Scan0.ToPointer(); int R, G, B; for (int y = 0; y < src.Height; y++) { for (int x = 0; x < src.Width; x++) { p = pIn; R = p[2]; G = p[1]; B = p[0]; if (R + G + B != 0) { M00++; M01 += y; M10 += x; } pIn += 3; } pIn += stride - src.Width * 3; } CentreP[0] = (int)(M10 / M00); CentreP[1] = (int)(M01 / M00); } src.UnlockBits(bmpData); return CentreP; //返回一個數組,該數組中第一個元素是質心的X坐標, //第二個元素是質心的Y坐標}
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答