代码有问题,先备份下
#include <thread>
#include <mutex>
std::mutex io_mutex;
using namespace cv;
using namespace std;
Mat image_catch;
volatile bool thread_all_exit = false;
Mat display_mat_origin;
Mat display_mat_process;
void catch_image()
{
std::cout << "start catch image" << std::endl;
Mat frame;
VideoCapture capture("rtsp://admin:[email protected]:554/h264/ch1/main/av_stream");
if (!capture.isOpened()) {
std::lock_guard<std::mutex> lock(io_mutex);
cout << "fail to open!" << endl;
thread_all_exit = true;
return;
}
while (1)
{
std::cout << "catch image" << std::endl;
capture.read(frame);
if (frame.empty())
{
std::cout << "catch empty frame" << std::endl;
capture.release();
thread_all_exit = true;
break;
}
else
{
std::cout << "catch full frame" << std::endl;
}
std::lock_guard<std::mutex> lock(io_mutex);
image_catch = frame.clone();
display_mat_origin = frame.clone();
if (thread_all_exit) {
std::cout << "ERROR,退出" << std::endl;
capture.release();
break;
}
}
capture.release();
}
void process_image()
{
std::cout << "start process image" << std::endl;
Mat img;
while (1) {
std::cout << "process image" << std::endl;
if (!image_catch.empty())
{
std::cout << "process full image " << std::endl;
std::lock_guard<std::mutex> lock(io_mutex);
img = image_catch.clone();
resize(img, img, Size(320, 240), 0, 0, CV_INTER_LINEAR);
display_mat_process = img.clone();
if (thread_all_exit) {
std::cout << "ERROR,退出" << std::endl;
break;
}
}
else
{
std::cout << "process empty image" << std::endl;
}
}
}
void main()
{
std::thread thread_catch_img(std::bind(&catch_image));
std::thread thread_process_img(std::bind(&process_image));
thread_catch_img.detach();
thread_process_img.detach();
while (1) {
if (!display_mat_origin.empty())
{
std::lock_guard<std::mutex> lock(io_mutex);
imshow("data", display_mat_origin);
imshow("process", display_mat_process);
if (waitKey(1) == 27 || thread_all_exit)
{
thread_all_exit = true;
break;
}
}
if (!display_mat_process.empty())
{
std::lock_guard<std::mutex> lock(io_mutex);
imshow("process", display_mat_process);
if (waitKey(1) == 27 || thread_all_exit)
{
thread_all_exit = true;
break;
}
}
}
}