我想减去从网络摄像头拍摄的两张连续图像。
你可以看到我在一个while循环中做这个。在while循环的最后一行,我设置frame2 = frame
,因此我可以从下一次迭代中减去它们。但是函数cv :: subtract在终端中返回上述错误。
我做错了什么?
#include <iostream>
#include "core.hpp"
#include "highgui.hpp"
#include "imgcodecs.hpp"
#include "cv.h"
using namespace std;
using namespace cv;
int main(int argc, char* argv[])
{
VideoCapture cap(0); ///open the video camera no. 0 (laptop's default camera)
///make a writer object:
cv::VideoWriter writer;
if (!cap.isOpened()) /// if not success, exit program
{
cout << "ERROR INITIALIZING VIDEO CAPTURE" << endl;
return -1;
}
char* windowName = "Webcam Feed(diff image)";
namedWindow(windowName,WINDOW_NORMAL); ///create a window to display our webcam feed
///we need to define 4 arguments for initializing the writer object:
//filename string:
string filename = "C:\\Users\\PEYMAN\\Desktop\\ForegroundExtraction\\openCV_tutorial\\2.writing from video to file\\Payman.avi";
//fourcc integer:
int fcc = CV_FOURCC('D','I','V','3');
//frame per sec integer:
int fps = 10;
//frame size:
cv::Size framesize(cap.get(CV_CAP_PROP_FRAME_WIDTH),cap.get(CV_CAP_PROP_FRAME_HEIGHT));
///initialize the writet object:
writer = VideoWriter(filename,fcc,fps,framesize);
if(!writer.isOpened()){
cout << "Error opening the file" << endl;
getchar();
return -1;
}
int counter = 0;
while (1) {
Mat frame,frame2,diff_frame;
///read a new frame from camera feed and save it to the variable frame:
bool bSuccess = cap.read(frame);
if (!bSuccess) ///test if frame successfully read
{
cout << "ERROR READING FRAME FROM CAMERA FEED" << endl;
break;
}
/// now the last read frame is stored in the variable frame and here it is written to the file:
writer.write(frame);
if (counter > 0){
cv::subtract(frame2,frame,diff_frame);
imshow(windowName, diff_frame ); ///show the frame in "MyVideo" window
}
///wait for 10ms for a key to be pressed
switch(waitKey(1)){
///the writing from webcam feed will go on until the user presses "esc":
case 27:
///'esc' has been pressed (ASCII value for 'esc' is 27)
///exit program.
return 0;
}
frame2 = frame;
counter++;
}
return 0;
}
答案 0 :(得分:2)
每次执行while循环时frame2
都会被创建并默认初始化。当你打电话
cv::subtract(frame2,frame,diff_frame);
您正尝试从其中包含图片的Mat
中减去默认构造的Mat
。这两个Mat
的大小不同,因此您会收到错误。
如果希望它们在每次执行while循环后保留其值,则需要将frame
和frame2
的声明移到while循环之外。您还需要将frame2
初始化为相同的尺寸或将第二张图片捕获到其中,以便第一次使用subtract
。
答案 1 :(得分:2)
您需要在frame2
循环范围之外声明while
,就像使用counter
一样。现在,每次迭代循环都会得到一个空的frame2
。
您也可以移动Mat
循环之外的所有while
,以便在每次迭代结束时不必取消分配内存并重新分配下一次,尽管这不是错误,在这种情况下您可能不会看到性能损失。
另外,@ rhcpfan是正确的,你需要注意浅拷贝和深拷贝。使用cv::swap(frame, fram2)
。