系统:ubuntu 16.04
处理器:Intel i5-8300H
显卡:GTX1050Ti
代码如下:
#include <opencv2/opencv.hpp>
#include <iostream>
#include <chrono>
using namespace std::chrono;
using namespace cv;
using namespace std;
void process_frame(Mat &image, int opts);
int main()
{
VideoCapture capture("/home/liuzhirong/桌面上1/videosave/camera_right_010.avi");
if (!capture.isOpened()) {
printf("could not open camera...\n");
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
int fps = capture.get(CAP_PROP_FPS);
int width = capture.get(CAP_PROP_FRAME_WIDTH);
int height = capture.get(CAP_PROP_FRAME_HEIGHT);
int num_of_frames = capture.get(CAP_PROP_FRAME_COUNT);
printf("frame width: %d, frame height: %d, FPS : %d \n", width, height, fps);
Mat frame;
int index = 0;
while (true) {
bool ret = capture.read(frame);
if (!ret) break;
imshow("input", frame);
char c = waitKey(200);
auto start = chrono::system_clock::now();
process_frame(frame, index);
auto end = chrono::system_clock::now();
auto dura = chrono::duration_cast<chrono::microseconds>(end-start);
std::cout<<"耗时"<<double(dura.count())*microseconds::period::num / microseconds::period::den <<"秒"<<std::endl;
imshow("result", frame);
if (c == 27) {
break;
}
}
waitKey(0);
return 0;
}
void process_frame(Mat &image, int opts) {
Mat hsv, mask;
cvtColor(image, hsv, COLOR_BGR2HSV);
Mat se = getStructuringElement(MORPH_RECT, Size(15, 15), Point(-1, -1));
inRange(hsv, Scalar(156, 90, 90), Scalar(180, 255, 255), mask);
morphologyEx(mask, mask, MORPH_OPEN, se);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(mask, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
int index = -1;
int max = 0;
for (size_t t = 0; t < contours.size(); t++) {
double area = contourArea(contours[t]);
if (area > max) {
max = area;
index = t;
}
}
if (index >= 0) {
RotatedRect rect = minAreaRect(contours[index]);
ellipse(image, rect, Scalar(0, 255, 0), 2, 8);
circle(image, rect.center, 2, Scalar(255, 0, 0), 2, 8, 0);
}
}
运行结果截图:
在球刚发射到没有飞过柱子时,没有成功识别;
在球飞过天花板上灯附近位置时,没有成功识别。
其余位置成功识别。
耗时:
4到11ms