- 操作系統:ubuntu22.04
- OpenCV版本:OpenCV4.9
- IDE:Visual Studio Code
- 編程語言:C++11
算法描述
OpenCV 中用于基于可變形部件模型(DPM) 的目標檢測器,主要用于行人、人臉等目標的檢測。它是一種傳統的基于特征的目標檢測方法,不依賴深度學習,而是使用 HOG 特征 + 部件模型來進行檢測。
示例代碼
#include <iostream>
#include <opencv2/dpm.hpp>
#include <opencv2/opencv.hpp>using namespace cv;
using namespace cv::dpm;
using namespace std;int main()
{// 指定模型文件路徑(支持多個類別)vector< String > modelPaths = { "car.xml" }; // 可添加多個如 "car.xml"vector< String > classNames = { "car" }; // 類別名稱// 創建 DPM 檢測器Ptr< DPMDetector > detector = DPMDetector::create( modelPaths, classNames );if ( detector.empty() ){cerr << "Failed to create DPMDetector!" << endl;return -1;}// 讀取圖像Mat image = imread( "/media/dingxin/data/study/OpenCV/sources/images/cars.png" );if ( image.empty() ){cerr << "Failed to load image!" << endl;return -1;}imshow( "Original", image );// 執行檢測vector< DPMDetector::ObjectDetection > detections;detector->detect( image, detections );// 顯示檢測結果for ( const auto& det : detections ){if(det.score > 1.0)rectangle( image, det.rect, Scalar( 0, 255, 0 ), 2 );cout << "Detected object with score: " << det.score << endl;}imshow( "Detections", image );waitKey();return 0;
}
運行結果
模型文件獲取
你需要下載 .xml 格式的 DPM 模型文件才能運行檢測。
官方支持的模型包括:
類別 | 文件名 |
---|---|
行人 | (Pedestrian) |
轎車(Car) | car.xml |
自行車(Bicycle) | bicycle.xml |
你可以從 OpenCV 的額外測試數據倉庫獲取這些模型:
🔗 OpenCV Extra GitHub - dpm 測試數據