以下の要件を満たすプログラムを教えてください。
////////////////////////////////////////////
- C++言語
- OpenCVを使用
- 1台のwebカメラ(外付け・PC内蔵どちらもOK)を使用
- 以下のようにスレッドを分けて動作させる
a. 4つのスレッドで並列処理を行う
b. スレッド1は、カメラから画像を取得する
c. スレッド2は、スレッド1で取得した画像を表示する
e. スレッド2は、ユーザーのキーボード入力を待ち受ける(cv::waitKey)
f. スレッド2は、キーボードの"2"を押されたら、カメラ画像を"th2.png"という名前で保存する
g. スレッド3とスレッド4は、スレッド1とスレッド2と同じ関係である
h. スレッド3は、カメラから画像を取得する
i. スレッド4は、スレッド1で取得した画像を表示する
j. スレッド4は、ユーザーのキーボード入力を待ち受ける(cv::waitKey)
k. スレッド4は、キーボードの"4"を押されたら、カメラ画像を"th4.png"という名前で保存する
l. キーボードで"esc"が押されたらプログラムを終了する
///////////////////////////////////////////
以下のようなプログラムを作成しましたがうまく動きません.
c++
1#include "pch.h" 2#include<thread> 3#include<iostream> 4#include<opencv2/videoio.hpp> 5#include<opencv2/opencv.hpp> 6#include<mutex> 7 8using namespace std; 9using namespace cv; 10 11mutex m1, m2; 12const std::string WIN_NAME = "Capture"; 13cv::VideoCapture cap(0); 14int inp_key = cv::waitKey(1); 15cv::Mat frame; 16cv::Mat frame2; 17 18void thfunc1() { 19 20 unique_lock<mutex> lock(m1); 21 cap >> frame; 22 23} 24 25void thfunc2() { 26 while (1) 27 { 28 unique_lock<mutex> lock(m1); 29 cv::imshow(WIN_NAME, frame); 30 int inp_key = cv::waitKey(1); 31 if (inp_key == 50) cv::imwrite("th2.png", frame); 32 } 33} 34 35 36void thfunc3() { 37 unique_lock<mutex> lock(m2); 38 cap >> frame2; 39} 40 41void thfunc4() { 42 while (1) 43 { 44 unique_lock<mutex> lock(m1); 45 cv::imshow(WIN_NAME, frame); 46 if (inp_key == 52) cv::imwrite("th4.png", frame); 47 } 48} 49 50int main(int argh, char* argv[]) 51{ 52 53 while (1) 54 { 55 thread th1(thfunc1); 56 thread th2(thfunc2); 57 thread th3(thfunc3); 58 thread th4(thfunc4); 59 60 // [ESC] 61 if (inp_key == 27) break; 62 63 th1.join(); 64 th2.detach(); 65 th4.detach(); 66 th3.join(); 67 } 68 69 70 71 cv::destroyAllWindows(); 72 return 0; 73}
回答1件
あなたの回答
tips
プレビュー