我使用此代码检测动作并使用系统时间保存图片名称,如2013-11-26_01:20,但每秒只能有1张图片。我想拍多张照片,如2013-11-26_01:20-1,2013-11-26_01:20-2 ... 2013-11-26_01:21-1,2013-11-26_01:22-2。
bool saveImg(Mat image, const string DIRECTORY, const string EXTENSION, const char * DIR_FORMAT, const char * FILE_FORMAT){
stringstream ss;
time_t seconds;
struct tm * timeinfo;
char TIME[80];
time (&seconds);
timeinfo = localtime (&seconds);
// convert dir...
strftime (TIME,80,DIR_FORMAT,timeinfo);
ss.str("");
ss << DIRECTORY << TIME;
if(!directoryExists(ss.str().c_str()))
mkdir(ss.str().c_str(), 0777);
// convert image name
strftime (TIME,80,FILE_FORMAT,timeinfo);
ss.str("");
ss << DIRECTORY << TIME << EXTENSION;
// save image
return imwrite(ss.str().c_str(), image);
}
int main (int argc, char * const argv[]) {
// const
const string DIR = "/home/balice/Desktop/";
const string EXT = ".jpg";
const int DELAY = 100; // mseconds
string DIR_FORMAT = "%d-%m-%Y";
string FILE_FORMAT = DIR_FORMAT + "/" + "%d-%m-%Y_%H:%M:%S";
// create all necessary instances
CvCapture * camera = cvCaptureFromCAM(CV_CAP_ANY);
Mat original = cvQueryFrame(camera);
Mat next_frame = original;
Mat current_frame = cvQueryFrame(camera);
Mat prev_frame = cvQueryFrame(camera);
cvtColor(current_frame, current_frame, CV_RGB2GRAY);
cvtColor(prev_frame, prev_frame, CV_RGB2GRAY);
cvtColor(next_frame, next_frame, CV_RGB2GRAY);
Mat d1, d2, result;
int window = 200;
bool movement;
while (true){
movement = false;
absdiff(next_frame, current_frame, d1);
absdiff(current_frame, prev_frame, d2);
bitwise_xor(d1, d2, result);
int middle_y = result.rows/2;
int middle_x = result.cols/2;
// Center window
threshold(result, result, 140, 255, CV_THRESH_BINARY);
for(int i = middle_x-window; i < middle_x+window; i++)
for(int j = middle_y-window; j < middle_y+window; j++)
if(result.at<int>(j,i)>0)
{
movement = true;
break;
}
if(movement==true)
saveImg(original,DIR,EXT,DIR_FORMAT.c_str(),FILE_FORMAT.c_str());
imshow("Motion", result);
prev_frame = current_frame;
current_frame = next_frame;
// get image from webcam
next_frame = cvQueryFrame(camera);
cvtColor(next_frame, next_frame, CV_RGB2GRAY);
break;
}
return 0;
}
答案 0 :(得分:0)
您的问题是文件名限制。在同一秒拍摄的所有图像都具有相同的文件名。作为解决方案,我可以建议使用毫秒,或者在图像写入磁盘后添加一些计数器递增,并重新设置每一秒。您需要将此计数器值添加到filename。