Baumer工業相機堡盟工業相機如何通過YoloV8的深度學習模型實現PCB的缺陷檢測(C#代碼,UI界面版)
- 工業相機使用YoloV8模型實現PCB的缺陷檢測
- 工業相機實現YoloV8模型實現PCB的缺陷檢測的技術背景
- 在相機SDK中獲取圖像轉換圖像的代碼分析
- 工業相機圖像轉換Bitmap圖像格式和Mat圖像重要核心代碼
- 本地文件圖像轉換Bitmap圖像格式和Mat圖像重要核心代碼
- Mat圖像導入YoloV8模型重要核心代碼
- 代碼實現演示(PCB的缺陷檢測)
- 源碼下載鏈接
- 工業相機通過YoloV8模型實現PCB的缺陷檢測的行業應用
?
工業相機使用YoloV8模型實現PCB的缺陷檢測
本項目集成了 YOLOv8 缺陷檢測模型 與 C#圖形界面工具,實現了包括圖片、文件夾、視頻與攝像頭等多種輸入方式的缺陷檢測功能。
工業相機RAW文件是一種記錄了工業相機傳感器的原始信息,同時記錄了由相機拍攝所產生的一些原數據(Metadata,如ISO的設置、快門速度、光圈值、白平衡等)的文件。RAW是未經處理、也未經壓縮的格式,可以把RAW概念化為“原始圖像編碼數據”。
?
工業相機Bitmap圖像是一種無損的圖像格式,它將圖像存儲為像素陣列,并可包含調色板信息。這種格式通常用于工業應用中,因為它能夠保留圖像的細節和質量,并且易于處理和分析。
本文以Baumer工業相機作為案例進行演示,實現將工業相機的圖像或者本地圖像導入Yolo模型從而實現PCB缺陷檢測等功能。
工業相機實現YoloV8模型實現PCB的缺陷檢測的技術背景
本文通過C#中實現一個簡單的UI界面,用于將YoloV8模型實現PCB的缺陷檢測
用戶可以通過該界面執行以下操作:
-
轉換相機圖像為Mat圖像:通過YoloV8模型實現PCB的缺陷檢測
-
轉換本地圖像為mat圖像:通過YoloV8模型實現PCB的缺陷檢測
通過這個UI界面,用戶能夠在實時應用機器視覺數據處理時快速有效地進行操作,無需深入了解圖像數據的底層處理過程。這個簡單的介紹旨在為開發人員提供一個明確的方向,以便開始構建此類應用程序,并且該程序主要用于演示目的。
在相機SDK中獲取圖像轉換圖像的代碼分析
本文介紹使用Baumer工業相機,實現將圖像轉換為Bitmap圖像,再轉換Mat圖像,導入到Yolo模型進行推理,輸出PCB的缺陷檢測的結果。
工業相機圖像轉換Bitmap圖像格式和Mat圖像重要核心代碼
//將相機內部圖像內存數據轉為bitmap數據
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap((int)mBufferFilled.Width, (int)mBufferFilled.Height,(int)mBufferFilled.Width,System.Drawing.Imaging.PixelFormat.Format8bppIndexed, (IntPtr)((ulong)mBufferFilled.MemPtr + mBufferFilled.ImageOffset));#region//Mono圖像數據轉換。彩色圖像數據轉換于此不同
System.Drawing.Imaging.ColorPalette palette = bitmap.Palette;
int nColors = 256;
for (int ix = 0; ix < nColors; ix++)
{uint Alpha = 0xFF;uint Intensity = (uint)(ix * 0xFF / (nColors - 1));palette.Entries[ix] = System.Drawing.Color.FromArgb((int)Alpha, (int)Intensity,(int)Intensity, (int)Intensity);
}
bitmap.Palette = palette;
#endregionstring strtime = DateTime.Now.ToString("yyyyMMddhhmmssfff");
string saveimagepath = pImgFileDir + "\\" + strtime + ".brw";//使用Bitmap格式保存
bitmap.Save(saveimagepath, System.Drawing.Imaging.ImageFormat.Bmp); //用bitmap轉換為mat
OpenCvSharp.Mat Matgray1 = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);
本地文件圖像轉換Bitmap圖像格式和Mat圖像重要核心代碼
C#環境下代碼如下所示:
if (imagePaths.Count() == 0)
{LoadImagePaths("test_img");
}string currentImagePath = imagePaths[currentImageIndex];// 顯示到pictureBoxA
pictureBoxA.Image.Dispose(); // 釋放上一張圖片資源,避免內存泄漏
pictureBoxA.Image = new Bitmap(currentImagePath);
image_path = currentImagePath;currentImageIndex = (currentImageIndex + 1) % imagePaths.Count;OnNotifyShowRecieveMsg("檢測中,請稍等……");
//textBox1.Text = "檢測中,請稍等……";
//pictureBox2.Image = null;
Application.DoEvents();image = new Mat(image_path);float ratio = Math.Min(1.0f * inpHeight / image.Rows, 1.0f * inpWidth / image.Cols);
int neww = (int)(image.Cols * ratio);
int newh = (int)(image.Rows * ratio);Mat dstimg = new Mat();
Cv2.Resize(image, dstimg, new OpenCvSharp.Size(neww, newh));Cv2.CopyMakeBorder(dstimg, dstimg, 0, inpHeight - newh, 0, inpWidth - neww, BorderTypes.Constant);
Mat圖像導入YoloV8模型重要核心代碼
C#環境下代碼如下所示:
// 定義 ONNX 模型的路徑
string onnxModelPath = "model/best.onnx";
// 定義輸入圖像的形狀
OpenCvSharp.Size inputShape = new OpenCvSharp.Size(640, 640);
// 從 ONNX 模型文件加載網絡
if(net==null)net = CvDnn.ReadNetFromOnnx(onnxModelPath);string[] modelClassify = { "missing_hole" };if (imagePaths.Count() == 0)
{LoadImagePaths("test_img");
}string currentImagePath = imagePaths[currentImageIndex];// 顯示到pictureBoxA
pictureBoxA.Image.Dispose(); // 釋放上一張圖片資源,避免內存泄漏
pictureBoxA.Image = new Bitmap(currentImagePath);
image_path = currentImagePath;if (pictureBoxA.Image == null)
{return;
}
currentImageIndex = (currentImageIndex + 1) % imagePaths.Count;OnNotifyShowRecieveMsg("檢測中,請稍等……");Application.DoEvents();image = new Mat(image_path);dt1 = DateTime.Now;
// 調用識別圖像的函數,并傳入圖像路徑、閾值、網絡、輸入形狀和分類類別列表
result_image = Recognize(image, 0.35, net, inputShape, modelClassify);
// 獲取計算結束時間
dt2 = DateTime.Now;
// 顯示輸出的圖像
pictureBoxA.Image = new Bitmap(result_image.ToMemoryStream());// 顯示推理耗時時間
OnNotifyShowRecieveMsg("推理耗時:" + (dt2 - dt1).TotalMilliseconds + "ms");
static Mat Recognize(Mat imgPath, double threshold, Net net, OpenCvSharp.Size inputShape, string[] modelClassify)
{using (Mat img = imgPath){int inpHeight = 640; // 輸入圖像的高度int inpWidth = 640; // 輸入圖像的寬度// 對圖像進行預處理,調整尺寸Mat image = img;float ratio = Math.Min(1.0f * inpHeight / image.Rows, 1.0f * inpWidth / image.Cols);int neww = (int)(image.Cols * ratio);int newh = (int)(image.Rows * ratio);//// 將圖像調整為模型需要的大小//Mat dstimg = new Mat();//Cv2.Resize(image, dstimg, new OpenCvSharp.Size(neww, newh));//Cv2.CopyMakeBorder(dstimg, dstimg, 0, inpHeight - newh, 0, inpWidth - neww, BorderTypes.Constant);//Mat BN_image = CvDnn.BlobFromImage(dstimg); // 將調整后的圖像轉換為Blob格式//// 配置圖片輸入數據 // 將 blob 設置為網絡的輸入//net.SetInput(BN_image);//// 從圖像生成用于網絡輸入的 blob//Mat blob = CvDnn.BlobFromImage(img, 1 / 255.0, inputShape, new Scalar(0, 0, 0), false);////Mat blob = CvDnn.BlobFromImage(img, 1.0 / 255.0, inputShape, new Scalar(0, 0, 0), true, false);// 將 blob 設置為網絡的輸入//net.SetInput(blob);//// 從圖像生成用于網絡輸入的 blobMat img0 = imgPath;Mat blob0 = CvDnn.BlobFromImage(img0, 1 / 255.0, new OpenCvSharp.Size(inputShape.Width, inputShape.Height), swapRB: true, crop: false);net.SetInput(blob0);// 執行前向傳播獲取輸出Mat output = net.Forward();// 此處可能需要根據 C# 中 OpenCV 的特性來處理轉置操作output = ReshapeAndTranspose(output);// 獲取圖像的行數(高度)int height = img.Height;// 獲取圖像的列數(寬度)int width = img.Width;// 計算寬度的縮放因子double xFactor = (double)width / inputShape.Width;// 計算高度的縮放因子double yFactor = (double)height / inputShape.Height;// 初始化分類類別、得分和檢測框的列表List<string> classifys = new List<string>();List<float> scores = new List<float>();List<Rect> boxes = new List<Rect>();List<Double> maxVales = new List<Double>();List<OpenCvSharp.Point> maxloces = new List<OpenCvSharp.Point>();// 遍歷輸出的行for (int i = 0; i < output.Rows; i++){// 獲取當前行的檢測框數據using (Mat box = output.Row(i)){// 在框數據的特定范圍中找到最小值、最大值及其位置OpenCvSharp.Point minloc, maxloc;double minVal, maxVal;// Mat classes_scores = box.ColRange(4, 5);//GetArray(i, 5, classes_scores);// double curmates0 = box.At<float>(0);double curmates1 = box.At<float>(4);int collength = box.Cols;int rowlength = box.Rows;Mat curmates = box.ColRange(4, box.Cols);//Cv2.MinMaxLoc(box.ColRange(4, box.Cols), out minVal, out maxVal, out minloc, out maxloc);Cv2.MinMaxLoc(box.ColRange(4, box.Cols), out minVal, out maxVal, out minloc, out maxloc);int classId = maxloc.Y;if (classId == 0){// 獲取對應類別的得分 float score = (float)maxVal;// 如果得分大于閾值if (score > threshold){// 將得分添加到得分列表scores.Add(score);// 將類別添加到類別列表classifys.Add(modelClassify[classId]);// 獲取框的原始坐標float x = box.At<float>(0, 0);float y = box.At<float>(0, 1);float w = box.At<float>(0, 2);float h = box.At<float>(0, 3);// 計算調整后的坐標int xInt = (int)((x - 0.5 * w) * xFactor);int yInt = (int)((y - 0.5 * h) * yFactor);int wInt = (int)(w * xFactor);int hInt = (int)(h * yFactor);// 將調整后的框坐標添加到框列表boxes.Add(new Rect(xInt, yInt, wInt, hInt));}}}}// 執行非極大值抑制操作int[] indices;CvDnn.NMSBoxes(boxes, scores, 0.25f, 0.45f, out indices);// 遍歷非極大值抑制操作后的索引foreach (int i in indices){// 獲取對應的類別、得分和框string classify = classifys[i];float score = scores[i];Rect box = boxes[i];// 獲取框的坐標和尺寸// 在圖像上繪制矩形框Cv2.Rectangle(img, box, new Scalar(0, 255, 0), 3);// 生成類別和得分的標簽文本string label = $"{classify}: {score:F2}";// 在圖像上添加標簽文本Cv2.PutText(img, label, new OpenCvSharp.Point(box.X, box.Y - 10), HersheyFonts.HersheySimplex, 0.5, new Scalar(0, 255, 0), 2);}// 將圖像復制輸出返回Mat result_image0 = img.Clone();return result_image0;// 將處理后的圖像保存為文件// Cv2.ImWrite("result.jpg", img);}
}
代碼實現演示(PCB的缺陷檢測)
源碼下載鏈接
C# WinForms工業相機+本地圖像 通過YoloV8模型實現PCB的缺陷檢測
工業相機通過YoloV8模型實現PCB的缺陷檢測的行業應用
# | 細分行業 / 場景 | 主要缺陷類型 | 典型部署形態 & 價值 |
---|---|---|---|
1 | SMT 貼片產線后道 AOI | 焊橋、少錫、偏移、立碑 | 高速彩色工業相機(25 kHz)+ 雙側條形光源;YOLOv8-s 剪枝后跑在 NVIDIA Jetson Xavier,節拍 120 ms/板,直通率提升 30 % |
2 | HDI 鉆孔后 AOI | 缺失孔、孔偏、多孔 | 12 μm 線陣相機 + 遠心鏡頭;YOLOv8n 專訓“缺失孔”類,漏檢率 < 0.1 %,替代 2 臺人工顯微鏡 |
3 | FPC 軟板終檢 | 鼠咬、開路、短路、銅渣 | 可彎曲背光 + 4K 面陣相機;模型同時跑缺陷檢測與分類,缺陷坐標直接輸出給激光修板機,減少 40 % 報廢 |
4 | 汽車板(厚銅) | 銅厚不均、偽銅、毛刺 | 高動態范圍 HDR 工業相機 + 偏振片;YOLOv8 多尺度特征融合抑制反光,解決傳統閾值法 15 % 誤判問題 |
5 | IC 載板(BGA) | 微短路、焊盤凹陷 | 8K 彩色 TDI 線掃相機;TensorRT-YOLOv8-FP16 推理 50 ms/Frame,對接 MES 實時鎖批 |
6 | 軍工高可靠板 | 裂紋、劃傷、異物 | 真空吸附平臺 + 多角度環形光;檢測數據留存 10 年,滿足 GJB 要求 |
7 | LED 鋁基板 | 白油殘缺、線路缺口 | 白光 + UV 雙通道相機;YOLOv8 多任務頭同時檢測缺陷與字符,實現一機兩用 |
8 | 維修返修站 | 返修板二次缺陷確認 | 手持式 2000 萬像素工業相機 + 筆記本;離線模型權重僅 6 MB,現場一鍵升級 |