2
我正在編寫我的第一個OpenCV
程序,並在我的Macbook上使用相機進行一些圖像處理。下面的代碼只是顯示相機,並允許我按正常顯示的0
,1
,2
或3
將GRB和4
更改爲黑白。我不得不按下鍵來響應。什麼原因導致了這種延遲,以及如何讓代碼更加響應輸入?加速OpenCV的輸入響應
#include "opencv2/core/core.hpp"
#include "opencv2/flann/miniflann.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/photo/photo.hpp"
#include "opencv2/video/video.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/ml/ml.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core_c.h"
#include "opencv2/highgui/highgui_c.h"
#include "opencv2/imgproc/imgproc_c.h"
using namespace cv;
using namespace std;
Mat channel(Mat A, int ich) {
Mat Channel[3];
Mat B = A.clone();
split(B, Channel);
for(int i = 0; i < 3; i++) {
if(ich-1 != i) Channel[i] = Mat::zeros(B.rows, B.cols, CV_8UC1);
}
merge(Channel, 3, B);
return B;
}
Mat BW(Mat A) {
Mat B;
B = A.clone();
cvtColor(A, B, CV_BGR2GRAY);
return B;
}
int main() {
int waitCount = 1; // wait for this many milliseconds to check for input
VideoCapture stream1(0);
namedWindow("cam", CV_WINDOW_NORMAL);
if(!stream1.isOpened()) {
cout << "Cannot open camera!" << endl;
}
int showKind = 0;
Mat cameraFrame; // showKind = 0
Mat grey; // showkind = 4
while(true) {
/// read the cameraFrame
stream1.read(cameraFrame);
/// show the cameraFrame
if(showKind == 0) imshow("cam", cameraFrame);
else if(showKind > 0 && showKind < 4) imshow("cam", channel(cameraFrame, showKind));
else if(showKind == 4) imshow("cam", BW(cameraFrame));
else {
cout << "ERROR: Unknown showKind = " << showKind << endl;
}
////////////////////////////////////////////////////////////
/// check for input
////////////////////////////////////////////////////////////
// close down
if(waitKey(waitCount) == 27) {
cout << "ESC pressed ... exiting" << endl;
break;
}
// convert showKind
else if(waitKey(waitCount) == 48) {
cout << "Showkind changed to 0" << endl;
showKind = 0;
}
else if(waitKey(waitCount) == 49){
cout << "Showkind changed to 1" << endl;
showKind = 1;
}
else if(waitKey(waitCount) == 50){
cout << "Showkind changed to 2" << endl;
showKind = 2;
}
else if(waitKey(waitCount) == 51){
cout << "Showkind changed to 3" << endl;
showKind = 3;
}
else if(waitKey(waitCount) == 52){
cout << "Showkind changed to 4" << endl;
showKind = 4;
}
}
return 0;
}