Skip to content

Commit 0ba612f

Browse files
authored
v0.15.2
version 0.15.2
2 parents b8b2765 + 7d224fd commit 0ba612f

File tree

5 files changed

+93
-61
lines changed

5 files changed

+93
-61
lines changed

.pre-commit-config.yaml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
repos:
2+
- repo: https://github.com/psf/black
3+
rev: 21.12b0
4+
hooks:
5+
- id: black
6+
language_version: python3.9

pyobs_aravis/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
from .araviscamera import AravisCamera
22

33

4-
__all__ = ['AravisCamera']
4+
__all__ = ["AravisCamera"]

pyobs_aravis/aravis.py

Lines changed: 50 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -9,27 +9,31 @@
99
import numpy as np
1010
import ctypes
1111
import gi
12-
gi.require_version('Aravis', '0.8')
12+
13+
gi.require_version("Aravis", "0.8")
1314
from gi.repository import Aravis
1415

1516
__author__ = "Olivier Roulet-Dubonnet, Morten Lind"
1617
__copyright__ = "Copyright 2011-2013, Sintef Raufoss Manufacturing"
1718
__license__ = "GPLv3"
1819
__version__ = "0.5"
1920

21+
2022
class AravisException(Exception):
2123
pass
2224

25+
2326
class Camera(object):
2427
"""
25-
Create a Camera object.
28+
Create a Camera object.
2629
name is the camera ID in aravis.
2730
If name is None, the first found camera is used.
2831
If no camera is found an AravisException is raised.
2932
"""
33+
3034
def __init__(self, name=None, loglevel=logging.WARNING):
3135
self.logger = logging.getLogger(self.__class__.__name__)
32-
if len(logging.root.handlers) == 0: #dirty hack
36+
if len(logging.root.handlers) == 0: # dirty hack
3337
logging.basicConfig()
3438
self.logger.setLevel(loglevel)
3539
self.name = name
@@ -50,15 +54,17 @@ def __init__(self, name=None, loglevel=logging.WARNING):
5054
self._last_payload = 0
5155

5256
def __getattr__(self, name):
53-
if hasattr(self.cam, name): # expose methods from the aravis camera object which is also relatively high level
57+
if hasattr(
58+
self.cam, name
59+
): # expose methods from the aravis camera object which is also relatively high level
5460
return getattr(self.cam, name)
55-
#elif hasattr(self.dev, name): #epose methods from the aravis device object, this might be confusing
61+
# elif hasattr(self.dev, name): #epose methods from the aravis device object, this might be confusing
5662
# return getattr(self.dev, name)
5763
else:
5864
raise AttributeError(name)
5965

6066
def __dir__(self):
61-
tmp = list(self.__dict__.keys()) + self.cam.__dir__()# + self.dev.__dir__()
67+
tmp = list(self.__dict__.keys()) + self.cam.__dir__() # + self.dev.__dir__()
6268
return tmp
6369

6470
def load_config(self, path):
@@ -85,7 +91,9 @@ def get_feature_type(self, name):
8591
genicam = self.dev.get_genicam()
8692
node = genicam.get_node(name)
8793
if not node:
88-
raise AravisException("Feature {} does not seem to exist in camera".format(name))
94+
raise AravisException(
95+
"Feature {} does not seem to exist in camera".format(name)
96+
)
8997
return node.get_node_name()
9098

9199
def get_feature(self, name):
@@ -134,7 +142,9 @@ def get_feature_vals(self, name):
134142
if ntype == "Enumeration":
135143
return self.dev.get_available_enumeration_feature_values_as_strings(name)
136144
else:
137-
raise AravisException("{} is not an enumeration but a {}".format(name, ntype))
145+
raise AravisException(
146+
"{} is not an enumeration but a {}".format(name, ntype)
147+
)
138148

139149
def read_register(self, address):
140150
return self.dev.read_register(address)
@@ -150,7 +160,9 @@ def create_buffers(self, nb=10, payload=None):
150160
self.stream.push_buffer(Aravis.Buffer.new_allocate(payload))
151161

152162
def pop_frame(self, timestamp=False):
153-
while True: #loop in python in order to allow interrupt, have the loop in C might hang
163+
while (
164+
True
165+
): # loop in python in order to allow interrupt, have the loop in C might hang
154166
if timestamp:
155167
ts, frame = self.try_pop_frame(timestamp)
156168
else:
@@ -186,7 +198,7 @@ def _array_from_buffer_address(self, buf):
186198
if not buf:
187199
return None
188200
pixel_format = buf.get_image_pixel_format()
189-
bits_per_pixel = pixel_format >> 16 & 0xff
201+
bits_per_pixel = pixel_format >> 16 & 0xFF
190202
if bits_per_pixel == 8:
191203
INTP = ctypes.POINTER(ctypes.c_uint8)
192204
else:
@@ -208,42 +220,41 @@ def __str__(self):
208220

209221
def __repr__(self):
210222
return self.__str__()
211-
223+
212224
def start_acquisition(self, nb_buffers=10):
213225
self.logger.info("starting acquisition")
214226
payload = self.cam.get_payload()
215227
if payload != self._last_payload:
216-
#FIXME should clear buffers
217-
self.create_buffers(nb_buffers, payload)
228+
# FIXME should clear buffers
229+
self.create_buffers(nb_buffers, payload)
218230
self._last_payload = payload
219231
self.cam.start_acquisition()
220232

221233
def start_acquisition_trigger(self, nb_buffers=1):
222-
self.set_feature("AcquisitionMode", "Continuous") #no acquisition limits
223-
self.set_feature("TriggerSource", "Software") #wait for trigger t acquire image
224-
self.set_feature("TriggerMode", "On") #Not documented but necesary
234+
self.set_feature("AcquisitionMode", "Continuous") # no acquisition limits
235+
self.set_feature(
236+
"TriggerSource", "Software"
237+
) # wait for trigger t acquire image
238+
self.set_feature("TriggerMode", "On") # Not documented but necesary
225239
self.start_acquisition(nb_buffers)
226240

227241
def start_acquisition_continuous(self, nb_buffers=20):
228-
self.set_feature("AcquisitionMode", "Continuous") #no acquisition limits
229-
#self.set_feature("TriggerSource", "Freerun") #as fast as possible
230-
#self.set_string_feature("TriggerSource", "FixedRate")
231-
#self.set_feature("TriggerMode", "On") #Not documented but necesary
242+
self.set_feature("AcquisitionMode", "Continuous") # no acquisition limits
243+
# self.set_feature("TriggerSource", "Freerun") #as fast as possible
244+
# self.set_string_feature("TriggerSource", "FixedRate")
245+
# self.set_feature("TriggerMode", "On") #Not documented but necesary
232246
self.start_acquisition(nb_buffers)
233247

234248
def stop_acquisition(self):
235249
self.cam.stop_acquisition()
236250

237251
def shutdown(self):
238-
#Delete the objects on shutdown: socket will be closed!
252+
# Delete the objects on shutdown: socket will be closed!
239253
del self.stream
240254
del self.dev
241255
del self.cam
242256

243257

244-
245-
246-
247258
def get_device_ids():
248259
Aravis.update_device_list()
249260
n = Aravis.get_n_devices()
@@ -252,60 +263,59 @@ def get_device_ids():
252263

253264
def show_frame(frame):
254265
import cv2
266+
255267
cv2.imshow("capture", frame)
256268
cv2.waitKey(0)
257269

270+
258271
def save_frame(frame, path="frame.png"):
259272
print("Saving frame to ", path)
260273
np.save(path, frame)
261274

275+
262276
def sfn(cam, path="frame.png"):
263277
from PIL import Image
278+
264279
cam.start_acquisition()
265280
frame = cam.pop_frame()
266281
cam.stop_acquisition()
267282
im = Image.fromarray(frame)
268283
print("Saving image to ", path)
269284
im.save(path)
270285

286+
271287
def get_frame(cam):
272288
cam.start_acquisition()
273289
frame = cam.pop_frame()
274290
cam.stop_acquisition()
275291
return frame
276292

277293

278-
279-
280-
281-
282-
283294
if __name__ == "__main__":
284-
#cam = Camera("Prosilica-02-2110A-06145")
285-
#cam = Camera("AT-Automation Technology GmbH-20805103")
295+
# cam = Camera("Prosilica-02-2110A-06145")
296+
# cam = Camera("AT-Automation Technology GmbH-20805103")
286297
cam = Camera(None)
287298
try:
288-
#Aravis.enable_interface ("Fake")
289-
#x, y, width, height = cam.get_region()
299+
# Aravis.enable_interface ("Fake")
300+
# x, y, width, height = cam.get_region()
290301
print("Camera model: ", cam.get_model_name())
291302
print("Vendor Name: ", cam.get_vendor_name())
292303
print("Device id: ", cam.get_device_id())
293-
#print("Image size: ", width, ",", height)
294-
print("Sensor size: ", cam.get_sensor_size())
304+
# print("Image size: ", width, ",", height)
305+
print("Sensor size: ", cam.get_sensor_size())
295306
print("Exposure: ", cam.get_exposure_time())
296307
print("Frame rate: ", cam.get_frame_rate())
297308
print("Payload: ", cam.get_payload())
298309
print("AcquisitionMode: ", cam.get_feature("AcquisitionMode"))
299310
print("Acquisition vals: ", cam.get_feature_vals("AcquisitionMode"))
300-
#print("TriggerMode: ", cam.get_feature("TriggerMode"))
301-
#print("Bandwidth: ", cam.get_feature("StreamBytesPerSecond"))
311+
# print("TriggerMode: ", cam.get_feature("TriggerMode"))
312+
# print("Bandwidth: ", cam.get_feature("StreamBytesPerSecond"))
302313
print("PixelFormat: ", cam.get_feature("PixelFormat"))
303-
#print("ExposureAuto: ", cam.get_feature("ExposureAuto"))
314+
# print("ExposureAuto: ", cam.get_feature("ExposureAuto"))
304315
print("PacketSize: ", cam.get_feature("GevSCPSPacketSize"))
305316

306-
307317
from IPython import embed
318+
308319
embed()
309320
finally:
310321
cam.shutdown()
311-

pyobs_aravis/araviscamera.py

Lines changed: 33 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import asyncio
22
import logging
33
import time
4-
from typing import Any, Dict, Optional
4+
import numpy.typing as npt
5+
from typing import Any, Dict, Optional, List
56

67
from . import aravis
78

@@ -14,9 +15,16 @@
1415

1516
class AravisCamera(BaseVideo, IExposureTime):
1617
"""A pyobs module for Aravis cameras."""
17-
__module__ = 'pyobs_aravis'
1818

19-
def __init__(self, device: str, settings: Optional[Dict[str, Any]] = None, **kwargs: Any):
19+
__module__ = "pyobs_aravis"
20+
21+
def __init__(
22+
self,
23+
device: str,
24+
settings: Optional[Dict[str, Any]] = None,
25+
buffers: int = 5,
26+
**kwargs: Any,
27+
):
2028
"""Initializes a new AravisCamera.
2129
2230
Args:
@@ -29,21 +37,24 @@ def __init__(self, device: str, settings: Optional[Dict[str, Any]] = None, **kwa
2937
self._camera: Optional[aravis.Camera] = None
3038
self._settings: Dict[str, Any] = {} if settings is None else settings
3139
self._camera_lock = asyncio.Lock()
40+
self._buffers = buffers
3241

3342
# thread
3443
if device is not None:
3544
self.add_background_task(self._capture)
3645
else:
37-
log.error('No device name given, not connecting to any camera.')
46+
log.error("No device name given, not connecting to any camera.")
3847

3948
async def open(self) -> None:
4049
"""Open module."""
4150
await BaseVideo.open(self)
4251

4352
# list devices
44-
ids = aravis.get_device_ids()
53+
ids: List[str] = aravis.get_device_ids() # type: ignore
4554
if self._device_name not in ids:
46-
raise ValueError('Could not find given device name in list of available cameras.')
55+
raise ValueError(
56+
"Could not find given device name in list of available cameras."
57+
)
4758

4859
# open camera
4960
await self.activate_camera()
@@ -58,25 +69,25 @@ def _open_camera(self) -> None:
5869
"""Open camera."""
5970

6071
# open camera
61-
log.info('Connecting to camera %s...', self._device_name)
62-
self._camera = aravis.Camera(self._device_name)
63-
log.info('Connected.')
72+
log.info("Connecting to camera %s...", self._device_name)
73+
self._camera = aravis.Camera(self._device_name) # type: ignore
74+
log.info("Connected.")
6475

6576
# settings
6677
for key, value in self._settings.items():
67-
log.info(f'Setting value {key}={value}...')
68-
self._camera.set_feature(key, value)
78+
log.info(f"Setting value {key}={value}...")
79+
self._camera.set_feature(key, value) # type: ignore
6980

7081
# start acquisition
71-
self._camera.start_acquisition_continuous(nb_buffers=5)
82+
self._camera.start_acquisition_continuous(nb_buffers=self._buffers) # type: ignore
7283

7384
def _close_camera(self) -> None:
7485
"""Close camera."""
7586
# stop camera
7687
if self._camera is not None:
77-
log.info('Closing camera...')
78-
self._camera.stop_acquisition()
79-
self._camera.shutdown()
88+
log.info("Closing camera...")
89+
self._camera.stop_acquisition() # type: ignore
90+
self._camera.shutdown() # type: ignore
8091
self._camera = None
8192

8293
async def _activate_camera(self) -> None:
@@ -107,7 +118,7 @@ async def _capture(self) -> None:
107118
continue
108119

109120
# read frame
110-
frame = self._camera.pop_frame()
121+
frame: npt.NDArray[float] = self._camera.pop_frame() # type: ignore
111122
last = time.time()
112123

113124
# process it
@@ -123,7 +134,7 @@ async def set_exposure_time(self, exposure_time: float, **kwargs: Any) -> None:
123134
ValueError: If exposure time could not be set.
124135
"""
125136
await self.activate_camera()
126-
self._camera.set_exposure_time(exposure_time * 1e6)
137+
self._camera.set_exposure_time(exposure_time * 1e6) # type: ignore
127138

128139
async def get_exposure_time(self, **kwargs: Any) -> float:
129140
"""Returns the exposure time in seconds.
@@ -132,7 +143,10 @@ async def get_exposure_time(self, **kwargs: Any) -> float:
132143
Exposure time in seconds.
133144
"""
134145
await self.activate_camera()
135-
return self._camera.get_exposure_time() / 1e6
146+
return self._camera.get_exposure_time() / 1e6 # type: ignore
147+
148+
async def get_exposure_time_left(self, **kwargs: Any) -> float:
149+
return 0.0
136150

137151

138-
__all__ = ['AravisCamera']
152+
__all__ = ["AravisCamera"]

pyproject.toml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "pyobs-aravis"
3-
version = "0.15.1"
3+
version = "0.15.2"
44
description = "pyobs module for Aravis cameras"
55
authors = ["Tim-Oliver Husser <[email protected]>"]
66
license = "MIT"
@@ -11,6 +11,8 @@ numpy = "^1.21"
1111
PyGObject = "^3.42"
1212

1313
[tool.poetry.dev-dependencies]
14+
black = "^21.12b0"
15+
pre-commit = "^2.16.0"
1416

1517
[build-system]
1618
requires = ["poetry-core>=1.0.0"]

0 commit comments

Comments
 (0)