-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxcamera.py
291 lines (240 loc) · 9.5 KB
/
xcamera.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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# -*- coding: utf-8 -*-
"""
lantz.drivers.xenics.xcamera
~~~~~~~~~~~~~~~~~~~~~~~~~~
Implements Xenics XControl driver for Xenics cameras
Implementation Notes
--------------------
This wrapper uses the "old" Xcontrol driver.
Only tested under CCD under Windows XP
---
:copyright: 2015, see AUTHORS for more details.
:license: GPL, see LICENSE for more details.
"""
import time
import os.path
import ctypes as ct
import threading
import numpy as np
from numpy.ctypeslib import ndpointer
from lantz import Action, Feat
from lantz.errors import InstrumentError
from lantz.foreign import LibraryDriver
class Status(object):
READ_BUSY = 1
BUFFER_EMPTY = 2
COC_RUNNING = 4
BUFFERS_FULL = 8
_ERRORS = {
0: 'I_OK',
10000: 'E_BUG',
10001: 'E_NOINIT',
10002: 'E_LOGICLOADFAILED',
10003: 'E_OUT_OF_RANGE',
10004: 'E_NOT_SUPPORTED',
10005: 'E_NOT_FOUND',
10006: 'E_FILTER_DONE',
10007: 'E_SAVE_ERROR',
10008: 'E_MISMATCHED',
10009: 'E_BUSY',
10010: 'E_TIMEOUT'}
# List of functions that should not be checked for errorcodes
_IGNORE_ERR = ['XC_OpenCamera',
'XC_IsInitialised',
'XC_GetHeight',
'XC_GetWidth',
'XC_GetFrameSizeInBytes',
'XC_CloseCamera'
]
# Read lock for all devices that uses the same driver
readlock = threading.Lock()
class Xcamera(LibraryDriver):
"""Xenics Xcontrol Xcamera driver for Xenics CCD cameras
"""
# 'c:/Program Files/X-Control/xcamera.dll'
LIBRARY_NAME = 'xcamera.dll'
readlock = readlock
def __init__(self, camera_num=0,
#config_file='C:\Documents and Settings\MONA\Desktop\\vis\Xlin16BitFvB3.xcf',
#config_file=r'C:\Program Files\X-Control\Settings\Xlin16BitFvB3.xcf',
config_file=None, #r'C:\Program Files\X-Control\Settings\20130701_Vasco.xcf',
*args, **kwargs):
"""
@params
:type camera_num: int, The usb device index: 0,1,..
:type config_file: string, Path of the config file for the camera
"""
super().__init__(*args, **kwargs)
self.camera_num = camera_num
self.config_file = config_file
def _add_types(self):
self.lib.XC_OpenCamera.argtypes = [ct.c_uint]
self.lib.XC_CloseCamera.argtypes = [ct.c_uint]
self.lib.XC_IsInitialised.argtypes = [ct.c_uint]
self.lib.XC_LoadFromFile.argtypes = [ct.c_uint, ct.c_char_p]
self.lib.XC_SetGainCamera.argtypes = [ct.c_uint, ct.c_double]
self.lib.XC_SetIntegrationTime.argtypes = [ct.c_uint, ct.c_ulong]
self.lib.XC_SetCoolingTemperature.argtypes = [ct.c_uint, ct.c_short]
self.lib.XC_SetFan.argtypes = [ct.c_uint, ct.c_bool]
self.lib.XC_StartCapture.argtypes = [ct.c_uint]
self.lib.XC_StopCapture.argtypes = [ct.c_uint]
self.lib.XC_GetFrameSizeInBytes.argtypes = [ct.c_uint]
self.lib.XC_CloseCamera.restype = ct.c_void_p
self.lib.XC_StopCapture.restype = ct.c_void_p
def _return_handler(self, func_name, ret_value):
if self.lib.__getattribute__(func_name).restype != ct.c_void_p and (func_name not in _IGNORE_ERR):
if ret_value > 0:
raise InstrumentError(_ERRORS[ret_value])
return ret_value
def initialize(self):
""" Connect the camera."""
self.capturing = False
self.wait = 0.02
self.log_debug("Connecting to Camera")
self.xcamera_id = self.lib.XC_OpenCamera(self.camera_num)
if self.xcamera_id == None:
self.log_critical("Could not connect to camera {}".format(self.camera_num))
else:
self.log_debug("Connected. xcamera_id = %d" % self.xcamera_id)
if self.lib.XC_IsInitialised(self.xcamera_id) == 0:
self.log_error("Camera could not be initialized. Retry.")
self.finalize()
self.initialize()
else:
self.log_debug("Camera initialized.")
self.__load_config()
self.__sensor_shape()
self.__frame_size()
self.buffer = np.zeros(shape=self.shape, dtype=np.uint16)
def finalize(self):
self.log_info("Disconnecting Camera")
self.lib.XC_CloseCamera(self.xcamera_id)
@Action()
def __load_config(self):
if self.config_file:
if not os.path.exists(self.config_file):
raise FileExistsError('The specified configfile does not exist: {}'.format(self.config_file))
self.log_debug("Loading config file: %s" % self.config_file)
self.lib.XC_LoadFromFile(self.xcamera_id,
self.config_file)
@Action()
def __sensor_shape(self):
""" Read shape of sensor from camera """
height = self.lib.XC_GetHeight(self.xcamera_id)
width = self.lib.XC_GetWidth(self.xcamera_id)
self.shape = (height, width)
self.log_debug("Read camera shape %s" % str(self.shape))
@Action()
def __frame_size(self):
self.frame_size = self.lib.XC_GetFrameSizeInBytes(self.xcamera_id)
self.log_debug("Read frame size %d" % self.frame_size)
self.lib.XC_CopyFrameBuffer.argtypes = [ct.c_uint,
ndpointer(dtype=np.uint16, shape=self.shape),
ct.c_uint]
@Feat(values={'low': 3, 'medium': 2, 'high': 1, 'super_high': 0})
def gain(self):
gain = ct.c_double()
self.lib.XC_GetGainCamera(self.xcamera_id,
ct.byref(gain))
return gain.value
@gain.setter
def gain(self, gain):
(self.lib.XC_SetGainCamera(self.xcamera_id,
gain))
self.log_debug("Gain set to %d" % gain)
@Feat(units='us')
def exposure_time(self):
us = ct.c_uint()
(self.lib.XC_GetIntegrationTime(self.xcamera_id,
ct.byref(us)))
self.log_debug('Type us: {}'.format(type(us)))
return us.value
@exposure_time.setter
def exposure_time(self, us):
(self.lib.XC_SetIntegrationTime(self.xcamera_id,
int(us)))
self.log_debug("Integration time set to %d us" % us)
@Feat(units='K')
def temperature(self):
temp = ct.c_short()
(self.lib.XC_GetTemperature(self.xcamera_id,
ct.byref(temp)))
return temp.value
@temperature.setter
def temperature(self, k):
(self.lib.XC_SetCoolingTemperature(self.xcamera_id,
k))
self.log_debug("Temperature set to %d K" % k)
@Feat(values={True: True, False: False})
def fan(self):
fan = ct.c_bool()
(self.lib.XC_GetFan(self.xcamera_id,
ct.byref(fan)))
return fan.value
@fan.setter
def fan(self, k):
""" Set fan on (True) """
(self.lib.XC_SetFan(self.xcamera_id,
k))
self.log_debug("Switch fan %s" % ('on' if k else 'off'))
@Action()
def start_capture(self):
self.lib.XC_StartCapture(self.xcamera_id)
self.log_debug("Start capture")
@Action()
def stop_capture(self):
self.lib.XC_StopCapture(self.xcamera_id)
self.log_debug("Stop capture")
def _read_frame(self):
"""Copy the buffer from the camera"""
if self.readlock.acquire(blocking=False):
# make sure that there is only one read
# at the time, else the driver will freeze
(self.lib.XC_CopyFrameBuffer(self.xcamera_id,
self.buffer,
self.frame_size))
self.readlock.release()
self.log_debug("Captured 1 frame")
return self.buffer
else:
time.sleep(0.001)
self._read_frame()
@Action()
def single_frame(self):
""" Read a single frame
"""
time.sleep(self.exposure_time.to('s').magnitude + self.wait)
time.sleep(0.0002) # can be very short
self._read_frame()
return self.buffer
@Action()
def single_shot(self):
""" Start and stop camera and capture one frame. Takes more than 20ms"""
self.start_capture()
self.single_frame()
self.stop_capture()
return self.buffer
@Action(values={True: True, False: False})
def shutdown(self, fan=False):
""" Shutdown camera and put fan off
:param fan: put fan off (False), or leave it on (True)"""
self.fan = fan
self.finalize()
if __name__ == '__main__':
import argparse
import lantz.log
parser = argparse.ArgumentParser(description='Test Xcamera')
parser.add_argument('-i', '--interactive', action='store_true',
default=False, help='Show interactive GUI')
args = parser.parse_args()
lantz.log.log_to_socket(lantz.log.DEBUG)
with Xcamera() as cam:
if args.interactive:
from lantz.ui.app import start_test_app
start_test_app(cam)
else:
import matplotlib.pyplot as plt
image = cam.single_shot()
print(np.min(image), np.max(image), np.mean(image))
plt.imshow(image, cmap='gray')
plt.show()