先簡單介紹下什么是OpenCVsharp,內容取自百度百科
OpenCvSharp是一個OpenCV的.Net wrapper,應用最新的OpenCV庫開發,使用習慣比EmguCV更接近原始的OpenCV,有詳細的使用樣例供參考。該庫采用LGPL發行,對商業應用友好。使用OpenCvSharp,可用C#,VB.NET等語言實現多種流行的圖像處理(image processing)與計算機視覺(computer vision)算法。
下面進入正題:
代碼實現目的: 通過獲取像素值然后進行判斷,最終對像素值進行更改。
先介紹個比較低速效率不高的方法
1 private void SearchAviColorYIQ(IplImage img) 2 { 3 using (IplImage src = img.Clone()) 4 using (IplImage dst = new IplImage(src.Size, BitDepth.U8, 3)) 5 using (IplImage r = new IplImage(src.Size, BitDepth.U8, 1)) 6 using (IplImage g = new IplImage(src.Size, BitDepth.U8, 1)) 7 using (IplImage b = new IplImage(src.Size, BitDepth.U8, 1)) 8 { 9 src.CvtColor(dst, ColorConversion.BgrToRgb); 10 dst.Split(r, g, b, null); //將圖像分割成單獨的R,G,B圖形
11
12 int dr, dg, db;//RGB
13 double y, i, q; 14 int h, w; 15 for (h = 0; h < dst.Height; ++h) //用for循環進行遍歷
16 {//270
17 for (w = 0; w < dst.Width; ++w) 18 {//360
19 dr = (int)r[h, w].Val0; 20 dg = (int)g[h, w].Val0; 21 db = (int)b[h, w].Val0; 22 //將RGB模式轉換為YIQ模型,並只識別黃色
23 y = (0.299 * dr) + (0.587 * dg) + (0.114 * db); 24 i = (0.596 * dr) + ((-0.274) * dg) + ((-0.322) * db); 25 q = (0.211 * dr) + ((-0.523) * dg) + (0.312 * db); 26
27 if ((i >= 1) && (q < -4.0)) 28 { 29 dst[h, w] = CvColor.White; 30 } 31 else
32 { 33 dst[h, w] = CvColor.Black; 34 } 35 } 36 } 37 pictureBoxIpl2.ImageIpl = dst; 38 } 39 }
下面是用指針實現快速高效訪問圖片像素值
1 private void SearchBlockforYIQ(IplImage img) 2 { 3 using (IplImage src = img.Clone()) 4 using (IplImage dst = new IplImage(src.Size, BitDepth.U8, 3)) 5 { 6 src.CvtColor(dst, ColorConversion.BgrToRgb);//將bgr轉為rgb
7
8 int h, w; 9 int index; 10 double y, i, q; 11
12 unsafe
13 { 14 byte* ptr = (byte*)dst.ImageData; 15 byte r, g, b; 16 for (h = 0; h < dst.Height; ++h) 17 {//270
18 for (w = 0; w < dst.Width; ++w) 19 {//360
20 index = (dst.WidthStep * h) + (w * 3); 21 r = ptr[index]; 22 g = ptr[index + 1]; 23 b = ptr[index + 2]; 24
25 y = (0.299 * r) + (0.587 * g) + (0.114 * b); 26 i = (0.596 * r) + ((-0.274) * g) + ((-0.322) * b); 27 q = (0.211 * r) + ((-0.523) * g) + (0.312 * b); 28
29 if ((i >= 1) && (q < -4.0))//檢測黃色
30 {//變更為白色(白色的rgb值都是255)
31 ptr[index] = 255; 32 ptr[index + 1] = 255; 33 ptr[index + 2] = 255; 34 } 35 else
36 {//變更為黑色(黑色的RGB值都是0)
37 ptr[index] = 0; 38 ptr[index + 1] = 0; 39 ptr[index + 2] = 0; 40 } 41 } 42 } 43 } 44 pictureBoxIpl2.ImageIpl = dst; 45 } 46 }
以上是全部代碼,20~23行部分是核心部分。僅供參考!
PS: unsafe的使用方法
不知道的同學直接使用上述代碼的話,在unsafe部分可能會提示出錯,這時我們就要根據下面步驟來設置:
1. 右擊項目選擇屬性
2. 在生成的選項卡下將“允許不安全代碼”前面的勾勾上。
這樣設置后就可以正常使用unsafe了。