不能用 Python,只能用 CPP。代码如下,数据在 https://github.com/opencv/opencv_extra/tree/4.x/testdata/cv/dpm 中:
#include "opencv2/dpm.hpp"
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>
#include <iostream>
using namespace cv;
using namespace cv::dpm;
using namespace std;
int main(int argc, char** argv)
{
cv::Ptr<DPMDetector> detector = DPMDetector::create(vector<string>(1, "VOC2007_Cascade/car.xml"));
Scalar color(0, 255, 255); // yellow
Mat image = imread("cars.png");
Mat frame = imread("cars.png");
vector<DPMDetector::ObjectDetection> ds;
// 这里为什么在 frame 上画矩形,是因为 DPMDetector detect 会更改原图片!!
detector->detect(image, ds);
for (unsigned int i = 0; i < ds.size(); i++)
rectangle(frame, ds[i].rect, color, 2);
imshow("DPM Cascade Detection", frame);
return 0;
}