-
Notifications
You must be signed in to change notification settings - Fork 0
/
OneShot.py
71 lines (59 loc) · 2.38 KB
/
OneShot.py
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
#!/usr/bin/env python3
from fcntl import ioctl
import v4l2
import mmap
import numpy as np
import cv2
class LegoVisionCommandCamera(object):
def __init__(self, device_name):
self.device_name = device_name
self.nub_buffers = 3
self.buffers = []
self.open_device()
self.init_device()
self.init_mmap()
def open_device(self):
self.fd = open(self.device_name, 'rb+', buffering=0)
def close_device(self):
buf_type = v4l2.v4l2_buf_type(v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE)
ioctl(self.fd, v4l2.VIDIOC_STREAMOFF, buf_type)
self.fd.close()
def init_device(self):
fmt = v4l2.v4l2_format()
fmt.type = v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE
ioctl(self.fd, v4l2.VIDIOC_G_FMT, fmt)
ioctl(self.fd, v4l2.VIDIOC_S_FMT, fmt)
def init_mmap(self):
self.req = v4l2.v4l2_requestbuffers()
self.req.count = self.nub_buffers
self.req.type = v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE
self.req.memory = v4l2.V4L2_MEMORY_MMAP
ioctl(self.fd, v4l2.VIDIOC_REQBUFS, self.req)
for x in range(self.req.count):
buf = v4l2.v4l2_buffer()
buf.type = v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE
buf.memory = v4l2.V4L2_MEMORY_MMAP
buf.index = x
ioctl(self.fd, v4l2.VIDIOC_QUERYBUF, buf)
buf.buffer = mmap.mmap(self.fd.fileno(), buf.length, mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE, offset=buf.m.offset)
self.buffers.append(buf)
def start_capturing(self):
for buf in self.buffers:
ioctl(self.fd, v4l2.VIDIOC_QBUF, buf)
buf_type = v4l2.v4l2_buf_type(v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE)
ioctl(self.fd, v4l2.VIDIOC_STREAMON, buf_type)
def read(self):
#while True:
#for x in range(self.req.count):
buf = self.buffers[0]
ioctl(self.fd, v4l2.VIDIOC_DQBUF, buf)
mm = self.buffers[buf.index].buffer
raw_data = mm.read(buf.bytesused)
mm.seek(0)
#yield np.frombuffer(raw_data, dtype=np.uint8).reshape((292, 356))
image = cv2.cvtColor(np.frombuffer(raw_data, dtype=np.uint8).reshape((292, 356)), cv2.COLOR_BayerGR2RGB)
cv2.imwrite('test.jpg', image)
ioctl(self.fd, v4l2.VIDIOC_QBUF, buf)
camera = LegoVisionCommandCamera('/dev/video0')
camera.start_capturing()
camera.read()