Skip to content

Commit d84d6d6

Browse files
yolox in c++ (#177)
* yolox in c++ * review 1 * review 202306 * disable counter
1 parent 3f8cb2f commit d84d6d6

File tree

3 files changed

+363
-0
lines changed

3 files changed

+363
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
cmake_minimum_required(VERSION 3.24)
2+
set(project_name "opencv_zoo_object_detection_yolox")
3+
4+
PROJECT (${project_name})
5+
6+
set(OPENCV_VERSION "4.7.0")
7+
set(OPENCV_INSTALLATION_PATH "" CACHE PATH "Where to look for OpenCV installation")
8+
find_package(OpenCV ${OPENCV_VERSION} REQUIRED HINTS ${OPENCV_INSTALLATION_PATH})
9+
# Find OpenCV, you may need to set OpenCV_DIR variable
10+
# to the absolute path to the directory containing OpenCVConfig.cmake file
11+
# via the command line or GUI
12+
13+
file(GLOB SourceFile
14+
"demo.cpp")
15+
# If the package has been found, several variables will
16+
# be set, you can find the full list with descriptions
17+
# in the OpenCVConfig.cmake file.
18+
# Print some message showing some of them
19+
message(STATUS "OpenCV library status:")
20+
message(STATUS " config: ${OpenCV_DIR}")
21+
message(STATUS " version: ${OpenCV_VERSION}")
22+
message(STATUS " libraries: ${OpenCV_LIBS}")
23+
message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}")
24+
25+
# Declare the executable target built from your sources
26+
add_executable(${project_name} ${SourceFile})
27+
28+
# Link your application with OpenCV libraries
29+
target_link_libraries(${project_name} PRIVATE ${OpenCV_LIBS})

models/object_detection_yolox/README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ Note:
1313

1414
## Demo
1515

16+
### Python
17+
1618
Run the following command to try the demo:
1719
```shell
1820
# detect on camera input
@@ -24,6 +26,23 @@ Note:
2426
- image result saved as "result.jpg"
2527
- this model requires `opencv-python>=4.8.0`
2628

29+
### C++
30+
31+
Install latest OpenCV and CMake >= 3.24.0 to get started with:
32+
33+
```shell
34+
# A typical and default installation path of OpenCV is /usr/local
35+
cmake -B build -D OPENCV_INSTALLATION_PATH=/path/to/opencv/installation .
36+
cmake --build build
37+
38+
# detect on camera input
39+
./build/opencv_zoo_object_detection_yolox
40+
# detect on an image
41+
./build/opencv_zoo_object_detection_yolox -m=/path/to/model -i=/path/to/image -v
42+
# get help messages
43+
./build/opencv_zoo_object_detection_yolox -h
44+
```
45+
2746

2847
## Results
2948

Lines changed: 315 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,315 @@
1+
#include <vector>
2+
#include <string>
3+
#include <utility>
4+
5+
#include <opencv2/opencv.hpp>
6+
7+
using namespace std;
8+
using namespace cv;
9+
using namespace dnn;
10+
11+
vector< pair<dnn::Backend, dnn::Target> > backendTargetPairs = {
12+
std::make_pair<dnn::Backend, dnn::Target>(dnn::DNN_BACKEND_OPENCV, dnn::DNN_TARGET_CPU),
13+
std::make_pair<dnn::Backend, dnn::Target>(dnn::DNN_BACKEND_CUDA, dnn::DNN_TARGET_CUDA),
14+
std::make_pair<dnn::Backend, dnn::Target>(dnn::DNN_BACKEND_CUDA, dnn::DNN_TARGET_CUDA_FP16),
15+
std::make_pair<dnn::Backend, dnn::Target>(dnn::DNN_BACKEND_TIMVX, dnn::DNN_TARGET_NPU),
16+
std::make_pair<dnn::Backend, dnn::Target>(dnn::DNN_BACKEND_CANN, dnn::DNN_TARGET_NPU) };
17+
18+
vector<string> labelYolox = {
19+
"person", "bicycle", "car", "motorcycle", "airplane", "bus",
20+
"train", "truck", "boat", "traffic light", "fire hydrant",
21+
"stop sign", "parking meter", "bench", "bird", "cat", "dog",
22+
"horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe",
23+
"backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
24+
"skis", "snowboard", "sports ball", "kite", "baseball bat",
25+
"baseball glove", "skateboard", "surfboard", "tennis racket",
26+
"bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl",
27+
"banana", "apple", "sandwich", "orange", "broccoli", "carrot",
28+
"hot dog", "pizza", "donut", "cake", "chair", "couch",
29+
"potted plant", "bed", "dining table", "toilet", "tv", "laptop",
30+
"mouse", "remote", "keyboard", "cell phone", "microwave",
31+
"oven", "toaster", "sink", "refrigerator", "book", "clock",
32+
"vase", "scissors", "teddy bear", "hair drier", "toothbrush" };
33+
34+
class YoloX {
35+
private:
36+
Net net;
37+
string modelPath;
38+
Size inputSize;
39+
float confThreshold;
40+
float nmsThreshold;
41+
float objThreshold;
42+
dnn::Backend backendId;
43+
dnn::Target targetId;
44+
int num_classes;
45+
vector<int> strides;
46+
Mat expandedStrides;
47+
Mat grids;
48+
49+
public:
50+
YoloX(string modPath, float confThresh = 0.35, float nmsThresh = 0.5, float objThresh = 0.5, dnn::Backend bId = DNN_BACKEND_DEFAULT, dnn::Target tId = DNN_TARGET_CPU) :
51+
modelPath(modPath), confThreshold(confThresh),
52+
nmsThreshold(nmsThresh), objThreshold(objThresh),
53+
backendId(bId), targetId(tId)
54+
{
55+
this->num_classes = int(labelYolox.size());
56+
this->net = readNet(modelPath);
57+
this->inputSize = Size(640, 640);
58+
this->strides = vector<int>{ 8, 16, 32 };
59+
this->net.setPreferableBackend(this->backendId);
60+
this->net.setPreferableTarget(this->targetId);
61+
this->generateAnchors();
62+
}
63+
64+
void setBackendAndTarget(dnn::Backend bId, dnn::Target tId)
65+
{
66+
this->backendId = bId;
67+
this->targetId = tId;
68+
this->net.setPreferableBackend(this->backendId);
69+
this->net.setPreferableTarget(this->targetId);
70+
}
71+
72+
Mat preprocess(Mat img)
73+
{
74+
Mat blob;
75+
Image2BlobParams paramYolox;
76+
paramYolox.datalayout = DNN_LAYOUT_NCHW;
77+
paramYolox.ddepth = CV_32F;
78+
paramYolox.mean = Scalar::all(0);
79+
paramYolox.scalefactor = Scalar::all(1);
80+
paramYolox.size = Size(img.cols, img.rows);
81+
paramYolox.swapRB = true;
82+
83+
blob = blobFromImageWithParams(img, paramYolox);
84+
return blob;
85+
}
86+
87+
Mat infer(Mat srcimg)
88+
{
89+
Mat inputBlob = this->preprocess(srcimg);
90+
91+
this->net.setInput(inputBlob);
92+
vector<Mat> outs;
93+
this->net.forward(outs, this->net.getUnconnectedOutLayersNames());
94+
95+
Mat predictions = this->postprocess(outs[0]);
96+
return predictions;
97+
}
98+
99+
Mat postprocess(Mat outputs)
100+
{
101+
Mat dets = outputs.reshape(0,outputs.size[1]);
102+
Mat col01;
103+
add(dets.colRange(0, 2), this->grids, col01);
104+
Mat col23;
105+
exp(dets.colRange(2, 4), col23);
106+
vector<Mat> col = { col01, col23 };
107+
Mat boxes;
108+
hconcat(col, boxes);
109+
float* ptr = this->expandedStrides.ptr<float>(0);
110+
for (int r = 0; r < boxes.rows; r++, ptr++)
111+
{
112+
boxes.rowRange(r, r + 1) = *ptr * boxes.rowRange(r, r + 1);
113+
}
114+
// get boxes
115+
Mat boxes_xyxy(boxes.rows, boxes.cols, CV_32FC1, Scalar(1));
116+
Mat scores = dets.colRange(5, dets.cols).clone();
117+
vector<float> maxScores(dets.rows);
118+
vector<int> maxScoreIdx(dets.rows);
119+
vector<Rect2d> boxesXYXY(dets.rows);
120+
121+
for (int r = 0; r < boxes_xyxy.rows; r++, ptr++)
122+
{
123+
boxes_xyxy.at<float>(r, 0) = boxes.at<float>(r, 0) - boxes.at<float>(r, 2) / 2.f;
124+
boxes_xyxy.at<float>(r, 1) = boxes.at<float>(r, 1) - boxes.at<float>(r, 3) / 2.f;
125+
boxes_xyxy.at<float>(r, 2) = boxes.at<float>(r, 0) + boxes.at<float>(r, 2) / 2.f;
126+
boxes_xyxy.at<float>(r, 3) = boxes.at<float>(r, 1) + boxes.at<float>(r, 3) / 2.f;
127+
// get scores and class indices
128+
scores.rowRange(r, r + 1) = scores.rowRange(r, r + 1) * dets.at<float>(r, 4);
129+
double minVal, maxVal;
130+
Point maxIdx;
131+
minMaxLoc(scores.rowRange(r, r+1), &minVal, &maxVal, nullptr, &maxIdx);
132+
maxScoreIdx[r] = maxIdx.x;
133+
maxScores[r] = float(maxVal);
134+
boxesXYXY[r].x = boxes_xyxy.at<float>(r, 0);
135+
boxesXYXY[r].y = boxes_xyxy.at<float>(r, 1);
136+
boxesXYXY[r].width = boxes_xyxy.at<float>(r, 2);
137+
boxesXYXY[r].height = boxes_xyxy.at<float>(r, 3);
138+
}
139+
140+
vector< int > keep;
141+
NMSBoxesBatched(boxesXYXY, maxScores, maxScoreIdx, this->confThreshold, this->nmsThreshold, keep);
142+
Mat candidates(int(keep.size()), 6, CV_32FC1);
143+
int row = 0;
144+
for (auto idx : keep)
145+
{
146+
boxes_xyxy.rowRange(idx, idx + 1).copyTo(candidates(Rect(0, row, 4, 1)));
147+
candidates.at<float>(row, 4) = maxScores[idx];
148+
candidates.at<float>(row, 5) = float(maxScoreIdx[idx]);
149+
row++;
150+
}
151+
if (keep.size() == 0)
152+
return Mat();
153+
return candidates;
154+
155+
}
156+
157+
158+
void generateAnchors()
159+
{
160+
vector< tuple<int, int, int> > nb;
161+
int total = 0;
162+
163+
for (auto v : this->strides)
164+
{
165+
int w = this->inputSize.width / v;
166+
int h = this->inputSize.height / v;
167+
nb.push_back(tuple<int, int, int>(w * h, w, v));
168+
total += w * h;
169+
}
170+
this->grids = Mat(total, 2, CV_32FC1);
171+
this->expandedStrides = Mat(total, 1, CV_32FC1);
172+
float* ptrGrids = this->grids.ptr<float>(0);
173+
float* ptrStrides = this->expandedStrides.ptr<float>(0);
174+
int pos = 0;
175+
for (auto le : nb)
176+
{
177+
int r = get<1>(le);
178+
for (int i = 0; i < get<0>(le); i++, pos++)
179+
{
180+
*ptrGrids++ = float(i % r);
181+
*ptrGrids++ = float(i / r);
182+
*ptrStrides++ = float((get<2>(le)));
183+
}
184+
}
185+
}
186+
};
187+
188+
std::string keys =
189+
"{ help h | | Print help message. }"
190+
"{ model m | object_detection_yolox_2022nov.onnx | Usage: Path to the model, defaults to object_detection_yolox_2022nov.onnx }"
191+
"{ input i | | Path to input image or video file. Skip this argument to capture frames from a camera.}"
192+
"{ confidence | 0.5 | Class confidence }"
193+
"{ obj | 0.5 | Enter object threshold }"
194+
"{ nms | 0.5 | Enter nms IOU threshold }"
195+
"{ save s | true | Specify to save results. This flag is invalid when using camera. }"
196+
"{ vis v | 1 | Specify to open a window for result visualization. This flag is invalid when using camera. }"
197+
"{ backend bt | 0 | Choose one of computation backends: "
198+
"0: (default) OpenCV implementation + CPU, "
199+
"1: CUDA + GPU (CUDA), "
200+
"2: CUDA + GPU (CUDA FP16), "
201+
"3: TIM-VX + NPU, "
202+
"4: CANN + NPU}";
203+
204+
pair<Mat, double> letterBox(Mat srcimg, Size targetSize = Size(640, 640))
205+
{
206+
Mat paddedImg(targetSize.height, targetSize.width, CV_32FC3, Scalar::all(114.0));
207+
Mat resizeImg;
208+
209+
double ratio = min(targetSize.height / double(srcimg.rows), targetSize.width / double(srcimg.cols));
210+
resize(srcimg, resizeImg, Size(int(srcimg.cols * ratio), int(srcimg.rows * ratio)), INTER_LINEAR);
211+
resizeImg.copyTo(paddedImg(Rect(0, 0, int(srcimg.cols * ratio), int(srcimg.rows * ratio))));
212+
return pair<Mat, double>(paddedImg, ratio);
213+
}
214+
215+
Mat unLetterBox(Mat bbox, double letterboxScale)
216+
{
217+
return bbox / letterboxScale;
218+
}
219+
220+
Mat visualize(Mat dets, Mat srcimg, double letterbox_scale, double fps = -1)
221+
{
222+
Mat resImg = srcimg.clone();
223+
224+
if (fps > 0)
225+
putText(resImg, format("FPS: %.2f", fps), Size(10, 25), FONT_HERSHEY_SIMPLEX, 1, Scalar(0, 0, 255), 2);
226+
227+
for (int row = 0; row < dets.rows; row++)
228+
{
229+
Mat boxF = unLetterBox(dets(Rect(0, row, 4, 1)), letterbox_scale);
230+
Mat box;
231+
boxF.convertTo(box, CV_32S);
232+
float score = dets.at<float>(row, 4);
233+
int clsId = int(dets.at<float>(row, 5));
234+
235+
int x0 = box.at<int>(0, 0);
236+
int y0 = box.at<int>(0, 1);
237+
int x1 = box.at<int>(0, 2);
238+
int y1 = box.at<int>(0, 3);
239+
240+
string text = format("%s : %f", labelYolox[clsId].c_str(), score * 100);
241+
int font = FONT_HERSHEY_SIMPLEX;
242+
int baseLine = 0;
243+
Size txtSize = getTextSize(text, font, 0.4, 1, &baseLine);
244+
rectangle(resImg, Point(x0, y0), Point(x1, y1), Scalar(0, 255, 0), 2);
245+
rectangle(resImg, Point(x0, y0 + 1), Point(x0 + txtSize.width + 1, y0 + int(1.5 * txtSize.height)), Scalar(255, 255, 255), -1);
246+
putText(resImg, text, Point(x0, y0 + txtSize.height), font, 0.4, Scalar(0, 0, 0), 1);
247+
}
248+
249+
return resImg;
250+
}
251+
252+
int main(int argc, char** argv)
253+
{
254+
CommandLineParser parser(argc, argv, keys);
255+
256+
parser.about("Use this script to run Yolox deep learning networks in opencv_zoo using OpenCV.");
257+
if (parser.has("help"))
258+
{
259+
parser.printMessage();
260+
return 0;
261+
}
262+
263+
string model = parser.get<String>("model");
264+
float confThreshold = parser.get<float>("confidence");
265+
float objThreshold = parser.get<float>("obj");
266+
float nmsThreshold = parser.get<float>("nms");
267+
bool vis = parser.get<bool>("vis");
268+
bool save = parser.get<bool>("save");
269+
int backendTargetid = parser.get<int>("backend");
270+
271+
if (model.empty())
272+
{
273+
CV_Error(Error::StsError, "Model file " + model + " not found");
274+
}
275+
276+
YoloX modelNet(model, confThreshold, nmsThreshold, objThreshold,
277+
backendTargetPairs[backendTargetid].first, backendTargetPairs[backendTargetid].second);
278+
//! [Open a video file or an image file or a camera stream]
279+
VideoCapture cap;
280+
if (parser.has("input"))
281+
cap.open(samples::findFile(parser.get<String>("input")));
282+
else
283+
cap.open(0);
284+
if (!cap.isOpened())
285+
CV_Error(Error::StsError, "Cannot opend video or file");
286+
Mat frame, inputBlob;
287+
double letterboxScale;
288+
289+
static const std::string kWinName = model;
290+
int nbInference = 0;
291+
while (waitKey(1) < 0)
292+
{
293+
cap >> frame;
294+
if (frame.empty())
295+
{
296+
cout << "Frame is empty" << endl;
297+
waitKey();
298+
break;
299+
}
300+
pair<Mat, double> w = letterBox(frame);
301+
inputBlob = get<0>(w);
302+
letterboxScale = get<1>(w);
303+
TickMeter tm;
304+
tm.start();
305+
Mat predictions = modelNet.infer(inputBlob);
306+
tm.stop();
307+
cout << "Inference time: " << tm.getTimeMilli() << " ms\n";
308+
Mat img = visualize(predictions, frame, letterboxScale, tm.getFPS());
309+
if (vis)
310+
{
311+
imshow(kWinName, img);
312+
}
313+
}
314+
return 0;
315+
}

0 commit comments

Comments
 (0)