def init_cameras(): # vimba object vimba = Vimba() # Start vimba system vimba.startup() vmFactory = vimba.camera_ids() # Get connected cameras cams = [vimba.camera(id) for id in vmFactory] if len(cams) == 0: raise OSError("No camera present.") for idx, device in enumerate(vmFactory): print("Device {} ID: {}".format(idx, device)) observerList = [] for idx, cam in enumerate(cams): observerList.append(FrameObserver(idx, cam)) try: cam.open() cam.arm('Continuous', observerList[idx].frame_callback) cam.start_frame_acquisition() except VimbaException as e: if e.error_code == VimbaException.ERR_TIMEOUT: print(e) cam.disarm() cam.arm('Continuous', observerList[idx].frame_callback) cam.start_frame_acquisition() elif e.error_code == VimbaException.ERR_DEVICE_NOT_OPENED: print(e) cam.open() cam.arm('Continuous', observerList[idx].frame_callback) cam.start_frame_acquisition() else: print(e) return cams
def __init__(self, serial_number): global Vimba global VimbaException from pymba import Vimba, VimbaException self.data = [] self.frames = [] self.itr = 0 vimba = Vimba() vimba.startup() s_n = str(serial_number) camera_id = "50-0" + s_n # print(serial_number) # serial_number='DEV_000F315C1307'+str(serial_number)'DEV_000F315C57F9''50-0536923001' # pos self.camera = vimba.camera( camera_id) # vimba.camera_ids()[serial_number])#Device id. self.camera.open(camera_access_mode=1)
class AvtCamera(Camera): """Class for controlling an AVT camera. Uses the Vimba interface pymba (module documentation `here <https://github.com/morefigs/pymba>`_). Parameters ---------- Returns ------- """ def __init__(self, camera_id=None, **kwargs): # Set timeout for frame acquisition. Give this as input? self.timeout_ms = 1000 self.camera_id = camera_id super().__init__(**kwargs) try: self.vimba = Vimba() except NameError: raise Exception("The pymba package must be installed to use an AVT camera!") self.frame = None def open_camera(self): """ """ self.vimba.startup() messages = [] # Get available cameras: camera_ids = self.vimba.camera_ids() if self.camera_id is None: camera_index = 0 if len(camera_ids) > 0: messages.append( "I:Multiple cameras detected: {}. {} wiil be used.".format( camera_ids, self.camera_id ) ) else: try: camera_index = camera_ids.index(self.camera_id) except KeyError: raise KeyError( f"Camera id {self.camera_id} is not available (available cameras: {self.camera_ids})" ) messages.append("I:Detected camera {}.".format(camera_ids[camera_index])) self.cam = self.vimba.camera(camera_index) # Start camera: self.cam.open() self.frame = self.cam.new_frame() self.frame.announce() self.cam.start_capture() self.frame.queue_for_capture() self.cam.run_feature_command("AcquisitionStart") return messages def set(self, param, val): """ Parameters ---------- param : val : Returns ------- """ messages = [] try: if param == "exposure": # camera wants exposure in us: self.cam.ExposureTime = int(val * 1000) else: # To set new frame rate for AVT cameras acquisition has to be # interrupted: messages.append("E:" + param + " setting not supported on AVT cameras") except VimbaException: messages.append("E:Invalid value! {} will not be changed.".format(param)) return messages def read(self): """ """ try: self.frame.wait_for_capture(self.timeout_ms) self.frame.queue_for_capture() raw_data = self.frame.buffer_data() frame = np.ndarray( buffer=raw_data, dtype=np.uint8, shape=(self.frame.data.height, self.frame.data.width), ) except VimbaException: frame = None return frame def release(self): """ """ self.frame.wait_for_capture(self.timeout_ms) self.cam.run_feature_command("AcquisitionStop") self.cam.end_capture() self.cam.revoke_all_frames() self.vimba.shutdown()
def test_camera(vimba: Vimba): camera = vimba.camera(vimba.camera_ids()[0])
class PymbaCam: PIXEL_FORMATS_CONVERSIONS = { 'BayerRG8': cv.COLOR_BAYER_RG2RGB, } def __init__(self, mode='Continuous', cam_idx=0): self.vimba = Vimba() self.vimba.startup() self.camera = self.vimba.camera(cam_idx) self.is_last_frame = True self.framerate = 0 self.framerate_sum = 0 self.img_buffer = [] self.img_IDs = [] if mode not in 'Continuous': # SingleFrame']: raise NotImplementedError( f"{mode} is not a valid mode or not implemented. Use Continuous" ) self.camera.open() exposure = self.camera.feature('ExposureTimeAbs') exposure.value = 1000 self.camera.arm('Continuous', self.continous_cb) def __del__(self): # stop frame acquisition # start_frame_acquisition can simply be called again if the camera is still armed self.camera.stop_frame_acquisition() self.camera.disarm() self.camera.close() def continous_cb(self, frame: Frame): """Callback for receiving frames when they're ready Args: frame: The frame object """ self.img_IDs.append([frame.data.frameID, False]) # If the frame is incomplte, discard it (VmbFrame_t.receiveStatus does not equal VmbFrameStatusComplete) if frame.data.receiveStatus == -1: print(f"Incomplete frame: ID{frame.data.frameID}") return # get a copy of the frame data try: image = frame.buffer_data_numpy() except NotImplementedError: print(f"Empty frame: ID{frame.data.frameID}") return # convert colour space if desired try: image = cv.cvtColor( image, self.PIXEL_FORMATS_CONVERSIONS[frame.pixel_format]) except KeyError: pass self.img_IDs[-1][1] = True self.framerate_sum += self.camera.AcquisitionFrameRateAbs self.img_buffer.append(image) def capture(self, num_of_images=100): print("Started capture") self.img_buffer = [] self.camera.start_frame_acquisition() # stream images for a while... stop one image before, as an additional frame is captured when acquisition is stopped while len(self.img_buffer) < num_of_images - 1: sleep(0.001) self.camera.stop_frame_acquisition() sleep(0.5) self.framerate = self.framerate_sum / len(self.img_buffer) print(f"Average framerate: {self.framerate}") print(f"Good frames {len(self.img_buffer)}/{len(self.img_IDs)}") def save_images(self, dir, overwrite=False): """Save the image buffer to a folder of frames Args: dir: The directory to save the images in. overwrite: If the folder should be removed if it exists. Default: False """ print("Saving images:") out_dir = Path(dir) if out_dir.is_dir(): if not overwrite: raise FileExistsError( f"{dir} already exists, and overwrite=False") rmtree(out_dir) while out_dir.is_dir(): pass os.makedirs(out_dir) with open(f'{out_dir.as_posix()}/framerate', 'w') as framerate_file: framerate_file.write(str(self.framerate)) for img in self.img_buffer: # Get the next valid frame ID idx = self.img_IDs.pop(0) while not idx[1]: idx = self.img_ID self.img_IDs.pop(0) print('a') idx = idx[0] cv.imwrite(f'{out_dir.as_posix()}/VimbaImage_{idx}.png', img) print(f"\t{out_dir.as_posix()}/VimbaImage_{idx}.png") print('All images saved') idx = 0 def get_frame(self): """Get the next frame in the sequence Args: Returns: frame (list): RGB values or [] """ if self.idx == len(self.img_buffer) - 1: self.is_last_frame = True else: self.is_last_frame = False if self.idx >= len(self.img_buffer): idx = 0 self.idx += 1 return self.img_buffer[idx - 1]