def test_startup_shutdown(): with pytest.raises(VimbaException) as e: Vimba().system().feature_names() assert e.value.error_code == VimbaException.ERR_STARTUP_NOT_CALLED # manual Vimba().startup() Vimba().system().feature_names() Vimba().shutdown() # context manager with Vimba() as vmb: vmb.system().feature_names()
def initCam(self): '''initialisation of cam parameter ''' if self.nbcam == 'camDefault': try: self.cam0 = Vimba().camera(cameraIds[0]) self.ccdName = 'CAM0' self.camID = cameraIds[0] self.isConnected = True except: self.isConnected = False self.ccdName = 'no camera' else: self.camID = self.conf.value(self.nbcam + "/camID") ## read cam serial number try: self.cam0 = Vimba().camera(self.camID) self.ccdName = self.conf.value(self.nbcam + "/nameCDD") self.isConnected = True except: # if it doesn't work we take the first one try: self.nbcam = 'camDefault' self.cam0 = Vimba().camera(cameraIds[0]) self.ccdName = 'CAM0' self.camID = cameraIds[0] self.isConnected = True except: print('not ccd connected') self.isConnected = False self.ccdName = 'no camera' self.setWindowTitle(self.ccdName + ' v.' + version) if self.isConnected == True: print(self.ccdName, 'is connected @:', self.camID) self.cam0.open() ## init cam parameter## self.LineTrigger = str( self.conf.value(self.nbcam + "/LineTrigger") ) # line2 for Mako Line 1 for guppy (not tested) self.cam0.feature('ExposureTime').value = float( self.conf.value(self.nbcam + "/shutter")) * 1000 self.cam0.feature('Gain').value = int( self.conf.value(self.nbcam + "/gain")) self.cam0.feature('TriggerMode').value = 'Off' self.cam0.feature('TriggerActivation').value = 'RisingEdge' #self.cam0.feature('TriggerSelector').value='FrameStart' self.cam0.feature('TriggerSource').value = 'Software'
def getFeatureInfo(self, feature): """ Retrieve some basic feature information for a given feature. Values are returned as a nested list, with the first slot being the current value, and the second being the range. Min and max are the first and second slots respectively for the latter. Arguments: - feature: Character string. Name of feature to retrieve info from. """ with Vimba() as vimba: camera = vimba.camera(self.cameraID) camera.open() feature = camera.feature(feature) try: value = feature.value range_ = feature.range except VimbaException as e: value = e range_ = None feature_info = [value, range_] camera.close() return feature_info
def setMultiFeature(self, features, verbose=False): """ Set the value for a given set of features Arguments: - features: Dictionary. Feature names and corresponding values to set them to. - verbose: Boolean. Whether to print additional information. Default is False. """ with Vimba() as vimba: camera = vimba.camera(self.cameraID) camera.open() for feature in features: if verbose == True: feat = camera.feature(feature) initial = feat.value feat.value = features[feature] print( str(feature) + " is now: " + str(features[feature]) + ", was " + str(initial)) elif verbose == False: feat = camera.feature(feature) feat.value = features[feature] else: print( "Expected value of type Boolean. Available values for 'verbose' are True or False." ) camera.close()
def __init__(self, cam_num=0, pixelFormat="Mono16"): if not AVT_Camera.vimba: AVT_Camera.vimba = Vimba().__enter__() if not AVT_Camera.system: AVT_Camera.system = AVT_Camera.vimba.getSystem() self.cameraDesc = AVT_Camera.get_camera_list()[cam_num] # self.info = vimba.getCameraInfo(self.cameraDesc) self.camera = AVT_Camera.vimba.getCamera(self.cameraDesc) self.camera.openCamera() AVT_Camera.active_cameras.add(self) self.num = cam_num self.name = "AVT " + str(cam_num) self.model_name = self.camera.DeviceModelName.decode("ascii") print("cam" + str(self.num) + ":", self.model_name) # par défaut, on démarre en Mode 0 avec la résolution maximale à la # création de l'objet self.camera.IIDCMode = "Mode0" self.camera.Width = self.camera.WidthMax self.camera.Height = self.camera.HeightMax print( "cam" + str(self.num) + ": maximum resolution is", self.camera.Width, "x", self.camera.Height, ) print( "cam" + str(self.num) + ": maximum framerate is", self.camera_feature_info("AcquisitionFrameRate")["range"][1], ) self.camera.PixelFormat = pixelFormat.encode("ascii")
def route(self) -> None: self.first_frame() with Vimba() as vimba: camera = vimba.camera(0) camera.open() camera.ExposureTime = 200 # play around with this if exposure is too low camera.ExposureAuto = "Off" camera.AcquisitionFrameRateMode = 'Basic' max_fps = camera.AcquisitionFrameRate camera.AcquisitionFrameRate = max_fps # arm the camera and provide a function to be called upon frame ready camera.arm('Continuous', self.acquire_frame) camera.start_frame_acquisition() while self.live: time.sleep(0.1) print("Terminating capture...") camera.stop_frame_acquisition() camera.disarm() camera.close()
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 initialize(self): """ Params: camera -- number in list of show_cameras or friendly_name """ self.vimba = Vimba() self.vimba.startup() cameras = self.vimba.getCameraIds() self.log_debug('Available cameras are:' + str(cameras)) try: if isinstance(self.camera, int): cam = cameras[self.camera] self.cam = self.vimba.getCamera(cam) else: self.cam = self.vimba.getCamera(self.camera) except RuntimeError as err: self.log_error(err) raise RuntimeError(err) self.frame = self.cam.getFrame() self.frame.announceFrame() self.cam.startCapture() self._dynamically_add_properties() self._aliases() # get rid of Mono12Packed and give a log error: fmt = self.pixel_format if fmt == str('Mono12Packed'): self.log_error('PixelFormat {} not supported. Using Mono12 ' 'instead'.format(fmt)) self.pixel_format = 'Mono12'
def __init__(self): self.vimba = Vimba() self.vimba.startup() self.system = self.vimba.getSystem() self.cameraIds = self.vimba.getCameraIds() self.init_win() self.init_camera()
def setSingleFeature(self, feature, value, verbose=False): """ Set the value for a given feature. Arguments: - feature: Character string. Name of feature to set value for. - value: Numeric or character string. New value to set feature to. - verbose: Boolean. Whether to print additional information. Default is False. """ with Vimba() as vimba: camera = vimba.camera(self.cameraID) camera.open() feat = camera.feature(feature) if verbose == True: initial = feat.value feat.value = value print( str(feature) + " is now: " + str(value) + ", was " + str(initial)) elif verbose == False: feat.value = value else: print( "Expected value of type Boolean. Available values for 'verbose' are True or False." ) camera.close()
def bead_height(imshow=False): # Same algorithm used with ROI set, but called seperately with option to show image # with highlighted bead with Vimba() as vimba: vimba.startup() camera = vimba.camera(0) camera.open() camera.arm('SingleFrame') frame = camera.acquire_frame() image = frame.buffer_data_numpy() camera.disarm() x_mean = np.mean(image, axis=0) y_mean = np.mean(image, axis=1) x_pos = int(np.argmax(x_mean)) y_pos = int(np.argmax(y_mean)) camera.close() vimba.shutdown() if imshow: plt.figure() plt.imshow(image) plt.annotate('detected bead: {},{}'.format(x_pos,y_pos), xy=(x_pos,y_pos), xytext=(x_pos+25,y_pos+25), c='w') plt.scatter(x_pos, y_pos, c='r') plt.show() return x_pos, y_pos
def acquire_frame(self, features=None, path=None, filename=None, returnFilename=False): """ Acquire a frame and export to a given path. The path argument is optional for users who would like to export to a specific path. If left empty, the frame will be exported to the path specified in the given instance. This will be the current working directory if you did not specify path when creating the instance or set a new path with .setPath(). Arguments: - features: Dictionary. Feature names and corresponding values to set them to. - path: Character string. File path to save frames. Default is None. - filename: Character string. Filename to save frame by. Default is the current time if left as None. - returnFilename: Boolean. Whether to return the full file-path to the saved frame. Default is False. """ if path == None: path = self.path with Vimba() as vimba: camera = vimba.camera(self.cameraID) camera.open() if not features == None: for feature in features: feat = camera.feature(feature) feat.value = features[feature] camera.arm(mode="SingleFrame") frame = camera.acquire_frame() if frame.data.receiveStatus == -1: self.incompleteFrameErrorMsg() else: image = frame.buffer_data_numpy() try: image = cv2.cvtColor(image, self.pixelFormatConversions[frame.pixel_format]) except: pass if filename == None: timestamp = datetime.datetime.now().strftime('%Y-%m-%d_%Hh%Mm%Ss%fµs') filename = str(timestamp) + ".jpg" cv2.imwrite(path + filename, image) camera.disarm() camera.close() if returnFilename == True: return path + filename
def _setupVimba(self): from pymba import Vimba self._vimba = Vimba() self._vimba.startup() system = self._vimba.getSystem() if system.GeVTLIsPresent: system.runFeatureCommand("GeVDiscoveryAllOnce") time.sleep(0.2)
def getCameraID(): """ Obtain the ID's of all connected Allied Vision cameras. """ with Vimba() as vimba: cameras = vimba.camera_ids() return cameras
def initialize(self): self.vimba = Vimba() self.vimba.startup() self.cam = self.vimba.getCamera(self.vimba.getCameraIds()[0]) self.cam.openCamera() self.cam.PixelFormat = 'Mono8' self.frame = self.cam.getFrame() self.frame.announceFrame() self.cam.startCapture() return
def list_cameras(): with Vimba() as vimba: # get system object system = vimba.getSystem() # list available cameras (after enabling discovery for GigE cameras) if system.GeVTLIsPresent: system.runFeatureCommand("GeVDiscoveryAllOnce") time.sleep(0.2) cameraIds = vimba.getCameraIds() for cameraId in cameraIds: print(cameraId)
def openFirstCam(self): try: self.cam0 = Vimba().camera(cameraIds[0]) self.camID = cameraIds[0] self.isConnected = True self.nbcam = 'camDefault' except: self.isConnected = False self.ccdName = 'no camera' if self.isConnected == True: self.setCamParameter() return self.isConnected
def get_camera_list(cls): """This methods returns the list of camera numbers connected to the computer. :return: camera ids :rtype: list """ if cls.vimba: return cls.vimba.getCameraIds() else: with Vimba() as vimba_: return vimba_.getCameraIds()
def __init__(self, **kwargs): # Set timeout for frame acquisition. Give this as input? self.timeout_ms = 1000 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 first_frame(self) -> None: # load first frame with Vimba() as vimba: camera = vimba.camera(0) camera.open() camera.arm('SingleFrame') frame = camera.acquire_frame() camera.disarm() image = frame.buffer_data_numpy() height, width = frame.shape self.arm(width, height, image)
def set_camera_defaults(): # Resets frame from ROI to default (full frame) with Vimba() as vimba: vimba.startup() camera = vimba.camera(0) camera.open() camera.feature('OffsetX').value = 0 camera.feature('OffsetY').value = 0 camera.feature('Height').value = MAX_HEIGHT camera.feature('Width').value = MAX_WIDTH camera.close()
def openCamByID(self, camID): ''' read cam serial number ''' self.camID = camID print(self.camID, 'icff') try: self.cam0 = Vimba().camera(self.camID) self.isConnected = True print(self.camID, 'ceee') except: # if id number doesn't work we take the first one try: print('Id not valid open the fisrt camera') self.cam0 = Vimba().camera(cameraIds[0]) self.camID = cameraIds[0] self.isConnected = True except: print('not ccd connected') self.isConnected = False self.ccdName = 'no camera' if self.isConnected == True: self.setCamParameter()
def __init__(self): """ Camera controller for AVT camera devices. This implementation uses pymba as backend. """ super(Controller, self).__init__() self.logger = logging.getLogger(__name__) if LOGGING_LEVEL is not None: self.logger.setLevel(LOGGING_LEVEL) self.logger.debug('Starting AVT Camera Controller') self._vimba = Vimba() self._vimba.startup() self.__system = self._vimba.getSystem() self.__system.runFeatureCommand('GeVDiscoveryAllOnce') time.sleep(0.2)
def select_scale(): with Vimba() as vimba: camera = vimba.camera(0) camera.open() #Single frame capture camera.arm('SingleFrame') frame_data = camera.acquire_frame() frame = frame_data.buffer_data_numpy() scale_image = frame camera.disarm() camera.close() #cv2.imwrite('Scale_image.jpg', scale_image) global resize_factor_w global resize_factor_h global outside_d global ROI1 global d_tube global scale global middle_y #Scale image to fit screen scale_image_scaled = cv2.resize(scale_image,(1280,720)) resize_factor_w = (4024/1280) resize_factor_h = (3026/720) ROI1 = cv2.selectROI(scale_image_scaled) #select tube diameter cv2.destroyAllWindows() d_tube = ROI1[3]*resize_factor_h scale = outside_d/d_tube print('Scale: ', scale, ' mm/px') middle_y = round(ROI1[1]*resize_factor_h + (d_tube/2)) #tube middle point #Define meniscus search area global search_area y = int(middle_y - 100) y1 = int(middle_y + 100) x = 0 x1 = 4024 search_area_image = frame[y:y1, x:x1] #cv2.imwrite('Search_area.jpg', search_area_image) search_area = (y,y1,x,x1)
def set_camera_defaults(): # Resets frame from ROI to default (full frame) with Vimba() as vimba: vimba.startup() camera = vimba.camera(0) camera.open() camera.feature('OffsetX').value = 0 camera.feature('OffsetY').value = 0 camera.feature('Height').value = MAX_HEIGHT camera.feature('Width').value = MAX_WIDTH camera.feature('ExposureTime').value = MIN_EXPOSURE camera.feature('AcquisitionFrameRateMode').value = 'Basic' camera.close()
def aquire_frames(frame_rate, duration, path): # Handles frame capture, according to params frame_rate and duration if os.getcwd() != path: os.chdir(path) global total # for use with progress bar in save_frame total = frame_rate*duration with Vimba() as vimba: vimba.startup() camera = vimba.camera(0) camera.open() # Create frame buffer queue buffer = 50 frame_pool = [camera.new_frame() for _ in range(buffer)] for frame in frame_pool: # Tell camera about each frame in queue with designated callback frame.announce() frame.queue_for_capture(frame_callback=save_frame) # Initialize camera in MultiFrame mode and announce how many frames it will capture camera.feature('AcquisitionMode').value = 'MultiFrame' camera.feature('AcquisitionFrameCount').value = frame_rate*duration camera.feature('AcquisitionFrameRate').value = frame_rate print("Starting Acquisition\n") # Start/stop acquisition start = time.time() camera.start_capture() camera.AcquisitionStart() sleep(duration) camera.AcquisitionStop() end = time.time() sleep(0.2) camera.end_capture() camera.flush_capture_queue() camera.close() vimba.shutdown() print('\n') print('total time: ', end-start) print('Capture complete\n')
def take_picture(gain_dB, exposure_time_s, bitdepth=Bitdepth.EIGHT, props={}, debug_mode=False) -> np.ndarray: props['ExposureTimeAbs'] = int(exposure_time_s * 1e6) #exposure time in us props['Gain'] = gain_dB #gain in dB props['BlackLevel'] = 0 props['PixelFormat'] = Camera.PIXEL_FORMAT[bitdepth] if debug_mode: time.sleep(exposure_time_s) return generate_toy_image() #Connect to the Prosilica GT camera via a Power over Ethernet cable. Make #sure that the drivers are installed. This is tested the the Vimba 3.0 SDK. with Vimba() as vimba: #start camera interface camera = vimba.camera(0) try: camera.open() except VimbaException: message = "It is likely that the VimbaViewer is open. \ (Only a single program can access the camera at a time)" raise RuntimeError(message) camera.feature('ExposureTimeAbs').value = props['ExposureTimeAbs'] camera.feature('Gain').value = props['Gain'] camera.feature("BlackLevel").value = props['BlackLevel'] camera.feature("PixelFormat").value = props['PixelFormat'] camera.arm('SingleFrame') try: frame = camera.acquire_frame( timeout_ms=int(exposure_time_s * 1000 + 1000)) except VimbaException as e: # rearm camera upon frame timeout if e.error_code == VimbaException.ERR_TIMEOUT: print(e) camera.disarm() camera.arm('SingleFrame') else: raise image = Camera._frame_to_image(frame) return image
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)
def main(): cams = init_cameras() global flag flag = True while flag: try: c = cv2.waitKey(5) if c == ord('q'): flag = False except KeyboardInterrupt: sys.exit(1) for cam in cams: cam.stop_frame_acquisition() cam.disarm() cam.close() cv2.destroyAllWindows() Vimba().shutdown()
def run(self): print('Record video process started:', self, self.is_alive()) with Vimba() as vimba: print(vimba.camera_ids()) self.camera = vimba.camera(self.index) self.camera.open() self.camera.arm('Continuous', self.frame_retrieval.frame_callback) self.camera.AcquisitionFrameRateAbs = 30 self.camera.TriggerSource = 'FixedRate' self.camera.PixelFormat = 'BayerRG8' self.camera.SyncOutSelector = 'SyncOut1' self.camera.SyncOutSource = 'Exposing' self.camera.start_frame_acquisition() while self.manager.get_state(): pass self.stop_recording()