c++ - why a vector of cv::mat always return the first image? -
i'm reading video frames webcam , storing them in std::vector < cv::mat > variable.
each time want calculate frame difference between 2 consecutive frames, use following code result 0 , 0 matrix !! have 2 threads in program, 1 reading video frames , 1 processing video frames. whenever i'm going write vector use mutex in order prevent further problems in pushing or removing frames.
here pseudo code :
std::vector<cv::mat> image_vec; qmutex image_vec_mutex; main_thread() { while(1) { cv::mat frame,reserved_frame; camera.read(frame); frame.copyto(reserved_frame); qmutexlocker locker(&image_vec_mutex); image_vec.pushback(reserved_frame); locker.unlock(); cv::imshow("frame",frame); cv::waitkey(); } }
and process thread is:
process_thread() { (; image_vec.size() > 1 ;) { cv::mat frame1; image_vec[0].copyto(frame1); cv::mat frame2; image_vec[1].copyto(frame2); cv::subtract(frame1,frame2,result); qmutexlocker locker(&image_vec_mutex); image_vec[0].release(); //qdebug()<<"image_vec step2 size is: "<<image_vec.size()<<"\n"; image_vec.erase(image_vec.begin()); locker.unlock(); } }
i calculated mean , standard deviation of each frame in process thread , same ! solve problem changing thread process code code
process_thread() { (; image_vec.size() > 1 ;) { cv::mat frame1; image_vec[0].copyto(frame1); qmutexlocker locker(&image_vec_mutex); image_vec[0].release(); //qdebug()<<"image_vec step2 size is: "<<image_vec.size()<<"\n"; image_vec.erase(image_vec.begin()); locker.unlock(); delay_ms(1000); // more 1 second delay !!! cv::mat frame2; image_vec[0].copyto(frame2); cv::subtract(frame1,frame2,result); } }
why happens ? why delay more 1 second should used make code work ? tried delay less 1 second , result previous step ...
i'd appreciate comments on this.
you may need copy or clone frame mat, push vector, change code like
cv::mat frame; camera.read(frame); mat tmp=frame.clone(); //clone frame new mat image_vec.pushback(tmp);
otherwise passing same pointer on each pushback.
Comments
Post a Comment