I have no idea about this.My code has no errors,and I try to install Xvid,but nothing is useful.It keeps flashing back
Here is my code
#include <iostream>
#include <opencv2/opencv.hpp>
#include<thread>
#include <conio.h>
#include <windows.h>
#include <time.h>
using namespace std;
std::mutex g_mutex;
int width = 640;
int heigth = 480;
int FPS_SET = 30;
int key = 0;
std::queue<cv::Mat> frames;
void getframe()
{
cout << "正在打开摄像头" << endl;
cv::VideoCapture cap;
cap.open(0);
cap.set(cv::CAP_PROP_FRAME_WIDTH, width);
cap.set(cv::CAP_PROP_FRAME_HEIGHT, heigth);
cap.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'));
cap.set(cv::CAP_PROP_FPS, FPS_SET);
if (!cap.isOpened())
{
cout << "打开失败" << endl;
return;
}
cout << "打开成功" << endl;
int delay = 1000 / FPS_SET;
while (key != 27)
{
while (frames.size() > 3) Sleep(delay);
Sleep(delay);
cv::Mat frame2;
cap >> frame2;
g_mutex.lock();
frames.push(frame2);
g_mutex.unlock();
}
cout << "正在解除摄像头占用" << endl;
cap.release();
cout << "成功解除摄像头占用" << endl;
}
void showframe()
{
int font_face = cv::FONT_HERSHEY_COMPLEX;
double font_scale = 1;
int thickness = 2;
int baseline;
cv::Point origin;
origin.x = 10;
origin.y = 30;
int FPS = 0;
double time = 0;
LARGE_INTEGER nFreq;
LARGE_INTEGER nBeginTime;
LARGE_INTEGER nEndTime;
QueryPerformanceFrequency(&nFreq);
cv::Mat frame;
cv::namedWindow("Tennis");
do
{
QueryPerformanceCounter(&nBeginTime);
if (!frames.empty())
{
g_mutex.lock();
frame = frames.front();
frames.pop();
g_mutex.unlock();
string s = "FPS:" + to_string(FPS);
cv::putText(frame, s.c_str(), origin, font_face, font_scale, cv::Scalar(0, 255, 255), thickness, 8, 0);
}
if (!frame.empty())
cv::imshow("Tennis", frame);
cv::waitKey(1000 / FPS_SET);
QueryPerformanceCounter(&nEndTime);
time = (double)(nEndTime.QuadPart - nBeginTime.QuadPart) / (double)nFreq.QuadPart;
FPS = 1 / time;
} while (key != 27);
cv::destroyWindow("Tennis");
}
int main()
{
thread t1(getframe);
t1.detach();
thread t2(showframe);
t2.detach();
while (1)
{
Sleep(500);
if (_kbhit())
break;
};
key = 27;
Sleep(1000);
return 0;
}
There we go…