Последняя активность 1 month ago

V4L Loopback Python Streamer

example.py Исходник
1import fcntl, sys, os
2from v4l2 import *
3import time
4import scipy.misc as misc
5import numpy as np
6import cv2
7import signal
8import sys
9
10import streamer
11
12st = streamer.Streamer('/dev/video1')
13
14def signal_handler(signal, frame):
15 print('You pressed Ctrl+C!')
16 st.stop()
17 sys.exit(0)
18
19signal.signal(signal.SIGINT, signal_handler)
20
21imageBuffer = []
22for i in range(1,9,1):
23 im = misc.imread("test/%s.JPG" %i)
24 im = misc.imresize(im, (480, 640))
25 imageBuffer.append(im)
26
27st.start()
28
29i = 0
30while True:
31 st.updateFrame(imageBuffer[i])
32 time.sleep(1./5.)
33 i+=1
34 i%=8
35
36st.stop()
streamer.py Исходник
1#!/usr/bin/env python
2
3import fcntl, sys, os
4from v4l2 import *
5from threading import Thread, Lock
6import time
7import numpy as np
8import scipy.misc as misc
9import cv2
10import tools
11
12
13class Streamer(Thread):
14
15 _width = 640
16 _height = 480
17 _frameRate = 30
18 _fmt = V4L2_PIX_FMT_YUYV
19 _curFrame = None
20 _running = False
21 _mutex = Lock()
22
23 def __init__(self, devName):
24 Thread.__init__(self)
25 if not os.path.exists(devName):
26 print "Warning: device does not exist",devName
27 self._device = open(devName, 'wr', 0)
28 capability = v4l2_capability()
29 print "Get capabilities result: %s" % (fcntl.ioctl(self._device, VIDIOC_QUERYCAP, capability))
30 print "Capabilities: %s" % hex(capability.capabilities)
31 print "V4l2 driver: %s" % capability.driver
32
33 format = v4l2_format()
34 format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT
35 format.fmt.pix.pixelformat = self._fmt
36 format.fmt.pix.width = self._width
37 format.fmt.pix.height = self._height
38 format.fmt.pix.field = V4L2_FIELD_NONE
39 format.fmt.pix.bytesperline = self._width * 2
40 format.fmt.pix.sizeimage = self._width * self._height * 2
41 format.fmt.pix.colorspace = V4L2_COLORSPACE_JPEG
42
43 print "Set format result: %s" % (fcntl.ioctl(self._device, VIDIOC_S_FMT, format))
44 self._curFrame = np.zeros((self._height, self._width, 2), dtype=np.uint8)
45
46 def updateFrame(self, frame):
47 frame = misc.imresize(frame, (self._height, self._width))
48 buff = tools.ConvertToYUYV(frame)
49 self._mutex.acquire()
50 self._curFrame = buff
51 self._mutex.release()
52
53 def start(self):
54 print "Starting Streamer on %s" % self._device
55 self._running = True
56 Thread.start(self)
57
58 def stop(self):
59 self._running = False
60 self.join()
61
62 def run(self):
63 while self._running:
64 self._mutex.acquire()
65 self._device.write(self._curFrame)
66 self._mutex.release()
67 time.sleep(1./self._frameRate)