Baumer工業相機堡盟工業相機如何通過YoloV8深度學習模型實現持械檢測(C#代碼,UI界面版)
- 工業相機使用YoloV8模型實現持械檢測
- 工業相機通過YoloV8模型實現持械檢測的技術背景
- 在相機SDK中獲取圖像轉換圖像的代碼分析
- 工業相機圖像轉換Bitmap圖像格式和Mat圖像重要核心代碼
- 本地文件圖像轉換Bitmap圖像格式和Mat圖像重要核心代碼
- Mat圖像導入YoloV8模型重要核心代碼
- 代碼實現演示(實現持械檢測)
- 源碼下載鏈接
- 工業相機通過YoloV8模型實現持械檢測的行業應用
- 關鍵技術細節
?
工業相機使用YoloV8模型實現持械檢測
本項目集成了 YOLOv8 檢測模型 與 C#圖形界面工具,實現了包括圖片、文件夾、視頻與攝像頭等多種輸入方式的實現持械檢測功能。
工業相機RAW文件是一種記錄了工業相機傳感器的原始信息,同時記錄了由相機拍攝所產生的一些原數據(Metadata,如ISO的設置、快門速度、光圈值、白平衡等)的文件。RAW是未經處理、也未經壓縮的格式,可以把RAW概念化為“原始圖像編碼數據”。
?
工業相機Bitmap圖像是一種無損的圖像格式,它將圖像存儲為像素陣列,并可包含調色板信息。這種格式通常用于工業應用中,因為它能夠保留圖像的細節和質量,并且易于處理和分析。
本文以Baumer工業相機作為案例進行演示,實現將工業相機的圖像或者本地圖像導入Yolo模型從而實現持械檢測等功能。
工業相機通過YoloV8模型實現持械檢測的技術背景
本文通過C#中實現一個簡單的UI界面,用于將YoloV8模型實現持械檢測
用戶可以通過該界面執行以下操作:
-
轉換相機圖像為Mat圖像:通過YoloV8模型實現持械檢測的分類檢測
-
轉換本地圖像為mat圖像:通過YoloV8模型實現持械檢測的分類檢測
通過這個UI界面,用戶能夠在實時應用機器視覺數據處理時快速有效地進行操作,無需深入了解圖像數據的底層處理過程。這個簡單的介紹旨在為開發人員提供一個明確的方向,以便開始構建此類應用程序,并且該程序主要用于演示目的。
在相機SDK中獲取圖像轉換圖像的代碼分析
本文介紹使用Baumer工業相機,實現將圖像轉換為Bitmap圖像,再轉換Mat圖像,導入到Yolo模型進行推理,輸出刀具持械檢測的結果。
工業相機圖像轉換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/yolov8n-knife-people-gun-cudgel.onnx";
// 定義輸入圖像的形狀
OpenCvSharp.Size inputShape = new OpenCvSharp.Size(640, 640);
// 從 ONNX 模型文件加載網絡
if(net==null)net = CvDnn.ReadNetFromOnnx(onnxModelPath);string[] modelClassify = { "knife"};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);
result_image = RecognizeMat(image, 0.35, net, inputShape, modelClassify);
// 獲取計算結束時間
dt2 = DateTime.Now;
// 顯示輸出的圖像
pictureBoxA.Image = new Bitmap(result_image.ToMemoryStream());// 顯示推理耗時時間
OnNotifyShowRecieveMsg("推理耗時:" + (dt2 - dt1).TotalMilliseconds + "ms");
static Mat RecognizeMat(Mat imgInput, double threshold, Net net, OpenCvSharp.Size inputShape, string[] modelClassify)
{using (Mat img = imgInput){int inpHeight = inputShape.Height; // 輸入圖像的高度int inpWidth = inputShape.Width; // 輸入圖像的寬度// 對圖像進行預處理,調整尺寸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 = img;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);}
}
代碼實現演示(實現持械檢測)
源碼下載鏈接
C# WinForms工業相機+本地圖像 通過YoloV8深度學習模型實現持械檢測 源碼
工業相機通過YoloV8模型實現持械檢測的行業應用
工業相機 + YOLOv8 實現“持械檢測”的 7 大已落地行業場景
(全部案例均來自 2023-2025 年可查項目,附典型部署參數)
# | 行業 / 場景 | 檢測目標 | 工業相機配置 | YOLOv8 部署形態 | 效果 & 價值 |
---|---|---|---|---|---|
1 | 智慧煤礦井下 | 鐵鍬、撬棍、鎬頭等長柄工具 | 本安型 2 MP 紅外防爆相機 | RK3588 邊緣盒,YOLOv8-s 剪枝 6 MB,40 ms/幀 | 發現違規攜械 2 s 內語音廣播,事故率下降 55 % |
2 | 地鐵 / 高鐵安檢區 | 刀具、槍支、棍棒 | 4K 全局快門 120 fps + 雙光源 | Jetson AGX Xavier,TensorRT-FP16,60 ms/幀 | 聯動閘機緊急制動,誤報 < 0.5 % |
3 | 港口集裝箱堆場 | 撬棍、大錘、斧頭 | 5 MP 防塵相機 + 云臺 | IPC + RTX 3060,YOLOv8-m 檢測 3 類械具 | 24 h 無人值守,替代 4 名巡檢工 |
4 | 化工廠檢修動火區 | 非防爆扳手、鐵錘 | 6 mm 廣角 60 fps 相機 | 防爆 AI 盒子,YOLOv8n 量化 2.8 MB | 發現非防爆工具立即鎖止作業票系統 |
5 | 監獄 / 看守所周界 | 刀具、銳器、自制武器 | 2 MP 防暴半球 + 紅外補光 | 邊緣 GPU,YOLOv8-face + weapon 多任務頭 | 危險器械識別率 97 %,誤報 < 2 次/日 |
6 | 校園門口 / 教學樓 | 管制刀具、棍棒 | 8 MP 全景相機 + 槍機聯動 | 機房級 GPU,YOLOv8 + DeepSort 追蹤 | 2 s 內推送安保微信,保障師生安全 |
7 | 物流倉儲叉車通道 | 長桿、撬棍超高超限 | 頂裝 4K 180° 相機 | RK3588,YOLOv8n 檢測 + 3D 測距 | 超限即語音告警,避免貨架碰撞 |
關鍵技術細節
數據集
? 自建“Industrial-Weapon”數據集:刀、槍、棍、斧、撬棍 5 類,共 11 000 張;
? 場景覆蓋低照、雨霧、抖動、部分遮擋,增強泛化。
模型訓練
? 以 YOLOv8-s 為基線,輸入 640×640,訓練 120 epoch,mAP@0.5 0.94;
? 采用 Mosaic+HSV+CutOut 增強,解決尺度差異與光照變化;
? 剪枝后模型 5.8 MB,RK3588 NPU-INT8 推理 8 ms/幀。
部署加速
? TensorRT-FP16:RTX 3060 上 1080p 輸入 1.5 ms/幀;
? 邊緣端:Jetson Orin Nano 15 W 功耗,可支持 8 路相機并發。
合規提示
? 涉及公共區域需張貼 AI 監控告示;
? 原始視頻 72 h 內自動覆蓋,僅留事件截圖及 JSON 日志,符合《個人信息保護法》與《數據安全法》。