-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathframe-grabber.cpp
More file actions
102 lines (86 loc) · 2.32 KB
/
frame-grabber.cpp
File metadata and controls
102 lines (86 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "frame-grabber.h"
#include <map>
#include <unistd.h> // usleep
#include "logger.h"
using namespace std;
FrameGrabber::FrameGrabber(){
grab_on.store(false);
}
FrameGrabber::~FrameGrabber() {
end_grabbing();
}
void FrameGrabber::begin_grabbing(cv::VideoCapture * _cap, string _name = "unnamed")
{
name = _name;
cap = _cap;
grab_thread = thread(&FrameGrabber::grab_thread_proc, this);
grab_on.store(true);
}
void FrameGrabber::end_grabbing() {
if(grab_on.load()==true) {
grab_on.store(false); //stop the grab loop
grab_thread.join(); //wait for the grab loop
while (!buffer.empty()) //flush buffer
{
buffer.pop();
}
}
}
bool FrameGrabber::get_one_frame(cv::Mat & frame)
{
lock_guard<mutex> lock(grabber_mutex);
if (buffer.size() == 0)
return false;
frame = buffer.front(); //get the oldest grabbed frame (queue=FIFO)
buffer.pop(); //release the queue item
return true;
}
bool FrameGrabber::get_latest_frame(cv::Mat & frame) {
{
lock_guard<mutex> lock(grabber_mutex);
while(buffer.size()>1) {
buffer.pop();
}
}
return get_one_frame(frame);
}
int FrameGrabber::get_frame_count_grabbed() {
return frames_grabbed;
}
int FrameGrabber::ready_frame_count()
{
lock_guard<mutex> lock(grabber_mutex);
return buffer.size();
}
void FrameGrabber::grab_thread_proc()
{
pthread_setname_np(pthread_self(), "car-grabber");
try {
while (grab_on.load() == true) //this is lock free
{
cv::Mat frame;
//grab will wait for frame
if(!cap->read(frame)){
usleep(1000);
continue;
}
{
cv::flip( frame, frame, -1); // tood: make pre-processing user-definable
frames_topic.send(frame);
// only lock after frame is grabbed
lock_guard<mutex> lock(grabber_mutex);
++frames_grabbed;
//log_info((string)"grabbed " + to_string(frames_grabbed) + " frames from " + name + " buffer size: " + to_string(buffer.size()));
buffer.push(frame);
while(buffer.size() > max_frames_to_buffer) {
buffer.pop();
}
}
}
} catch (cv::Exception &e) {
log_error("caught cv::Exception in FrameGrabber::grab_thread_proc");
log_error(e.what());
} catch (...) {
log_error("unknown exception caught FrameGrabber::grab_thread_proc");
}
}