-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOpenCVCam.py
74 lines (60 loc) · 2.61 KB
/
OpenCVCam.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
72
73
74
import cv
from cv import CV_CAP_PROP_FRAME_WIDTH as FRAME_WIDTH
from cv import CV_CAP_PROP_FRAME_HEIGHT as FRAME_HEIGHT
import numpy as np
from Camera import Camera, CameraError
def ipl2array(im):
'''Converts an IplImage @im to a NumPy array.
Adapted from http://opencv.willowgarage.com/wiki/PythonInterface'''
depth2dtype = {
cv.IPL_DEPTH_8U: 'uint8',
cv.IPL_DEPTH_8S: 'int8',
cv.IPL_DEPTH_16U: 'uint16',
cv.IPL_DEPTH_16S: 'int16',
cv.IPL_DEPTH_32S: 'int32',
cv.IPL_DEPTH_32F: 'float32',
cv.IPL_DEPTH_64F: 'float64',
}
a = np.fromstring(im.tostring(),
dtype=depth2dtype[im.depth],
count=im.width * im.height * im.nChannels)
a.shape = (im.height, im.width, im.nChannels)
return a
class OpenCVCam(Camera):
plugin_info = {
'name': 'OpenCV',
'description': 'Video camera interfacing through OpenCV',
'author': 'Philip Chimento',
'copyright year': '2011',
}
def __init__(self, **traits):
super(OpenCVCam, self).__init__(
id_string='OpenCV driver, unknown camera',
**traits)
self._capture = None
def open(self):
self._capture = cv.CaptureFromCAM(self.camera_number)
# doesn't raise an exception on error, so we test it explicitly
iplimage = cv.QueryFrame(self._capture)
if iplimage is None:
raise CameraError('Could not query image', self.camera_number)
def close(self):
cv.ReleaseCapture(self._capture)
def query_frame(self):
iplimage = cv.QueryFrame(self._capture)
if iplimage is None:
raise CameraError('Could not query image', self.camera_number)
self.frame = ipl2array(iplimage)
def _resolution_default(self):
'''Resolution of the webcam - a 2-tuple'''
width = cv.GetCaptureProperty(self._capture, FRAME_WIDTH)
height = cv.GetCaptureProperty(self._capture, FRAME_HEIGHT)
return (int(width), int(height))
def _resolution_changed(self, value):
width, height = value
cv.SetCaptureProperty(self._capture, FRAME_WIDTH, width)
cv.SetCaptureProperty(self._capture, FRAME_HEIGHT, height)
if cv.GetCaptureProperty(self._capture, FRAME_WIDTH) != width:
raise CameraError('Width {0} not supported'.format(width), self.camera_number)
if cv.GetCaptureProperty(self._capture, FRAME_HEIGHT) != height:
raise CameraError('Height {0} not supported'.format(height), self.camera_number)