Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "barter.h"
- #include "fps_stats.hpp"
- #include <opencv2/core/utility.hpp>
- #include <opencv2/highgui.hpp>
- #include <opencv2/imgproc.hpp>
- #include <opencv2/video.hpp>
- #include <string>
- #include <list>
- #include <thread>
- #include <iostream>
- enum ThreadState {
- Pause, Running, Quit
- };
- std::list<cv::Mat> frames;
- cv::VideoCapture cap;
- barter<cv::Mat> frame_barter;
- std::atomic_int t_state{ ThreadState::Pause };
- // thread function for video getting and show
- void StreamThread(barter<cv::Mat>& frame_barter_, std::atomic_int& t_state_)
- {
- auto frame = std::make_unique<cv::Mat>();
- auto grey = std::make_unique<cv::Mat>();
- auto prevGrey = std::make_unique<cv::Mat>();
- cv::Mat flow, flow_uv[2];
- cv::Mat mag, ang;
- cv::Mat hsv_split[3], hsv;
- cv::Ptr<cv::DenseOpticalFlow> denseOpticalFlow = cv::DISOpticalFlow::create(cv::DISOpticalFlow::PRESET_MEDIUM);
- for (;;) {
- // wait for a new frame to arrive
- while (t_state_ != ThreadState::Running) {
- if (t_state_ == ThreadState::Quit) return;
- std::this_thread::sleep_for(std::chrono::microseconds(30));
- }
- frame_barter_.exchange(frame);
- CV_Assert(frame);
- if (frame->empty()) continue;
- // do the actual stuff
- cv::cvtColor(*frame, *grey, cv::COLOR_RGB2GRAY);
- if (!prevGrey->empty())
- {
- cv::Mat result;
- denseOpticalFlow->calc(*prevGrey, *grey, flow);
- cv::split(flow, flow_uv);
- cv::multiply(flow_uv[1], -1, flow_uv[1]);
- cv::cartToPolar(flow_uv[0], flow_uv[1], mag, ang, true);
- cv::normalize(mag, mag, 0, 1, cv::NORM_MINMAX);
- hsv_split[0] = ang;
- hsv_split[1] = mag;
- hsv_split[2] = cv::Mat::ones(ang.size(), ang.type());
- cv::merge(hsv_split, 3, hsv);
- cv::cvtColor(hsv, result, cv::COLOR_HSV2BGR);
- cv::imshow("result", result);
- cv::waitKey(30);
- }
- std::swap(*prevGrey, *grey);
- }
- }
- int main(int, char) {
- // Open camera
- cap.open(0);
- if (!cap.isOpened()) {
- std::cerr << "Stream open failed : " << std::endl;
- return 1;
- }
- // multi-threading setup
- cv::setNumThreads(8);
- std::thread t1{ &StreamThread, std::ref(frame_barter), std::ref(t_state) };
- auto frame = std::unique_ptr<cv::Mat>(new cv::Mat);
- std::this_thread::sleep_for(std::chrono::seconds(1));
- std::cout << "cv::getNumThreads(): " << cv::getNumThreads() << std::endl;
- fps_stats fps{ "Video" };
- cap >> *frame;
- while (!frame->empty()) {
- cv::imshow("Original", *frame);
- frame_barter.exchange(frame);
- t_state = ThreadState::Running;
- if (cv::waitKey(30) >= 0) {
- break;
- }
- cap >> *frame;
- fps.tick();
- }
- if (t1.joinable()) {
- t_state = ThreadState::Quit;
- t1.join();
- std::cout << "t1 is joined" << std::endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement