Esempio n. 1
0
    def find(self, serial_number=None, assign=True):
        """ Find a camera.

        The search can be conducted with or without a serial number. If 
        [serial_number] is not specified, the routine will return the first 
        available camera.

        If [assign] is set to True, the returned camera will be assigned to 
        [self.camera].
        """
        tlFactory = pylon.TlFactory.GetInstance()
        devices = tlFactory.EnumerateDevices()
        try:
            if serial_number is not None:
                for i, dev in enumerate(devices):
                    if int(dev.GetSerialNumber()) == int(serial_number):
                        camera = pylon.InstantCamera(
                            tlFactory.CreateDevice(devices[i]))
                        break
            else:
                if len(devices) > 0:
                    camera = pylon.InstantCamera(
                        pylon.TlFactory.GetInstance().CreateFirstDevice())
            assert camera is not None
        except:
            raise Exception("Failed to find camera.")

        if assign:
            self.camera = camera
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        # create the basler camera instances
        self.top_left_cam = BaslerCam(
            pylon.InstantCamera(
                pylon.TlFactory.GetInstance().CreateFirstDevice()),
            "Top Left Camera")
        self.top_right_cam = BaslerCam(
            pylon.InstantCamera(
                pylon.TlFactory.GetInstance().CreateFirstDevice()),
            "Top Right Camera")
        self.side_cam = BaslerCam(
            pylon.InstantCamera(
                pylon.TlFactory.GetInstance().CreateFirstDevice()),
            "Side Camera")
        self.cameras = [self.top_left_cam, self.top_right_cam, self.side_cam]

        self.main_tab_control = ttk.Notebook(self)
        self.train_tab = TrainTab(
            self, self.cameras)  # create a tab view for the train tab
        self.calibrate_camera_tab = CalibrateCameraTab(
            self, self.cameras)  # create a tab view for the calibrate tab
        self.preprocess_tab = PreprocessTab(
            self, self.cameras)  # create a tab view for the pre-process tab

        self.main_tab_control.add(
            self.train_tab,
            text="Train")  # add the tab for threshold image view
        self.main_tab_control.add(
            self.calibrate_camera_tab,
            text="Calibrate Camera")  # add the tab for normal image view
        self.main_tab_control.add(
            self.preprocess_tab,
            text="Preprocess")  # add the tab for threshold image view

        # pack the tab control
        self.main_tab_control.pack(side="top", fill="both", expand=True)

        # create a button for starting the inspection
        self.start_inspection_button = tk.Button(self, text="Start Inspection")
        self.start_inspection_button.pack(side="right")

        # create a button to set the part delay time (in ms)
        tk.Label(self, text="Part Delay Time (ms)").pack(side="left")
        self.part_delay_time = tk.Entry(self)
        self.part_delay_time.pack(side="left")
Esempio n. 3
0
 def CameraConnect(self):
     """
     conecting to the first available camera
     """
     camera = pylon.InstantCamera(
         pylon.TlFactory.GetInstance().CreateFirstDevice())
     return camera
Esempio n. 4
0
def OpenCamera(cam_params, bufferSize=500, validation=False):
    n_cam = cam_params["n_cam"]
    cam_index = cam_params["cameraSelection"]
    camera_name = cam_params["cameraName"]

    # Open and load features for all cameras
    tlFactory = pylon.TlFactory.GetInstance()
    devices = tlFactory.EnumerateDevices()
    camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateDevice(
        devices[cam_index]))
    serial = devices[cam_index].GetSerialNumber()
    camera.Close()
    camera.StopGrabbing()
    camera.Open()
    pylon.FeaturePersistence.Load(cam_params['cameraSettings'],
                                  camera.GetNodeMap(), validation)

    # Get camera information and save to cam_params for metadata
    cam_params['cameraSerialNo'] = serial
    cam_params['cameraModel'] = camera.GetDeviceInfo().GetModelName()

    # Set features manually or automatically, depending on configuration
    cam_params['frameWidth'] = camera.Width.GetValue()
    cam_params['frameHeight'] = camera.Height.GetValue()

    # Start grabbing frames (OneByOne = first in, first out)
    camera.MaxNumBuffer = bufferSize
    print("Started", camera_name, "serial#", serial)

    return camera, cam_params
Esempio n. 5
0
    def connect_camera(self):
        if self.camera is None:
            try:
                self.camera = pylon.InstantCamera(
                    pylon.TlFactory.GetInstance().CreateDevice(
                        self.full_name_list[self.camera_list.currentIndex()]))
                self.camera.Open()
            except:
                QMessageBox.critical(
                    self, "Error",
                    f"Selected Camera\n{self.camera_list.currentText()}\ncould not be opened"
                )
                self.camera = None
                return

            self.grab_thread.set_camera(self.camera)
            self.preview_toggle.setDisabled(False)
            self.thread.start()
            self.connect_button.setText("Close")
            self.setup_camera_features()

        else:
            self.grab_thread.stop()
            self.connect_button.setDisabled(True)
            self.preview_toggle.setDisabled(True)
            if self.preview_enabled:
                self.preview_enabled = False
                self.preview_toggle.setText("Show Preview")
                self.preview_thread.disable_preview()
            self.connect_button.setText("Open")
            self.camera = None
            clearLayout(self.camera_feature_box)

            self.thread.exit()
            self.thread.wait()
Esempio n. 6
0
    def _setup_cams(self):
        """ Searches for attached Basler cams and puts them into our list of cameras. """
        # reset cams
        self._camera_list, self._camera_names_list = list(), list()

        # Get the transport layer factory.
        tlFactory = pylon.TlFactory.GetInstance()

        devices = tlFactory.EnumerateDevices()
        if len(devices) == 0:
            print('No camera present. Quitting')
            exit()

        if self._verbosity > 0:
            print('Found %d cameras' % len(devices))

        for did, dev in enumerate(devices):
            self._camera_list.append(
                pylon.InstantCamera(tlFactory.CreateDevice(dev)))
            assert devices[did].IsSerialNumberAvailable(
            ), 'Could not read serial number.'
            sn = dev.GetSerialNumber()
            msg = 'Camera with serial number %s does not have a given name. Please define one in config/camera_names.py' % sn
            assert sn in self._camera_info.keys(), msg
            give_name = self._camera_info[sn]['name']
            self._camera_names_list.append(give_name)
            if self._verbosity > 0:
                print('Device %d: %s %s' % (did, give_name, sn))
Esempio n. 7
0
    def __init__(self):
        '''
        Initializing the camera configuration'
        '''
        try:
            self.camera = pylon.InstantCamera(
                pylon.TlFactory.GetInstance().CreateFirstDevice())
            self.camera.Open()
            self.camera.PixelFormat = "RGB8"
            self.camera.BslColorSpaceMode.SetValue("sRGB")
            self.camera.SensorShutterMode.SetValue("Rolling")
            self.camera.GainAuto.SetValue("Off")
            self.camera.ExposureAuto.SetValue("Off")
            self.camera.BalanceWhiteAuto.SetValue("Off")
            self.camera.BslContrastMode.SetValue("Linear")
            self.camera.MaxNumBuffer = 500
            self.originSetting()
            self.converter = pylon.ImageFormatConverter()
            self.converter.OutputPixelFormat = pylon.PixelType_BGR8packed
            self.converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned

        except Exception as e:
            print('An exception occurred' + str(e))
            print(e.GetDescription())
            raise
    def __init__(self):  #initialize Camera

        self.camera = pylon.InstantCamera(pylon.TlFactory.GetInstance(
        ).CreateFirstDevice())  #create instance of Camera

        #Open camera
        self.camera.Open()
        print("Using device:", self.camera.GetDeviceInfo().GetModelName())
        self.converter = pylon.ImageFormatConverter()
        self.converter.OutputPixelFormat = pylon.PixelType_BGR8packed
        self.converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned

        #Set Auto-Gain and Auto-Exposure to be OFF
        self.camera.ExposureAuto.SetValue("Off")
        self.camera.GainAuto.SetValue("Off")

        self.camera.Gain.GetValue()
        self.camera.ExposureTime.GetValue()
        self.camera.Gamma.GetValue()

        #Create an image window
        self.imageWindow = pylon.PylonImageWindow()
        self.imageWindow.Create(1)

        #Change save directory
        os.chdir("C:\\Users\\Wyss User\\Pictures\\Basler Test")
        print("Current working directory (save location):", os.getcwd())

        print("Camera initialized.")
 def quit_and_open(self):
     # Close camera
     self.cap.Close()
     # Create new capture
     self.cap = pylon.InstantCamera(
         pylon.TlFactory.GetInstance().CreateFirstDevice())
     self.cap.Open()
Esempio n. 10
0
def init_camera(time_for_capture):
    # conecting to the first available camera
    camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())

    try:

        camera.RegisterConfiguration(PylonViewer(), pylon.RegistrationMode_Append, pylon.Cleanup_Delete)
    
    except Exception as e :
        print("\n\n\n \n\n!%$$$$$$$$$$$$$$$$$", e,"\n\n\n\n")
    camera.MaxNumBuffer = 5000

    # Grabing Continusely (video) with minimal delay
    camera.StartGrabbing(pylon.GrabStrategy_OneByOne) 
    converter = pylon.ImageFormatConverter()

    camera.Gamma.SetValue(1.0)
    camera.ExposureTime.SetValue(5739)  #(7840)  # 32670
    camera.BalanceWhiteAuto.SetValue('Off')
    # print(dir(camera))
    camera.AcquisitionFrameRateEnable.SetValue(True)
    camera.AcquisitionFrameRate.SetValue(30)
    # print(camera.AcquisitionFrameRate.GetValue(), camera.ResultingFrameRate.GetValue())

    # converting to opencv bgr format
    converter.OutputPixelFormat = pylon.PixelType_BGR8packed
    converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned
    return camera, converter
Esempio n. 11
0
    def initialize(self):
        """ Initializes the communication with the camera. Get's the maximum and minimum width. It also forces
        the camera to work on Software Trigger.

        .. warning:: It may be useful to integrate other types of triggers in applications that need to
            synchronize with other hardware.

        """
        self.logger.debug('Initializing Basler Camera')
        tl_factory = pylon.TlFactory.GetInstance()
        devices = tl_factory.EnumerateDevices()
        if len(devices) == 0:
            #print('No camera found')
            self.logger.warning('No camera found')

        self._driver = None
        for device in devices:
            if self.cam_num in device.GetFriendlyName():
                self._driver = pylon.InstantCamera()
                self._driver.Attach(tl_factory.CreateDevice(device))
                self._driver.Open()
                self.friendly_name = device.GetFriendlyName()
            print(device.GetFriendlyName())

        if not self._driver:
            msg = f'Basler {self.cam_num} not found. Please check if the camera is connected'
            self.logger.error(msg)
            return
Esempio n. 12
0
    def openMenuCam(self):
        '''create a message box to choose a camera
        '''

        items = ()
        for i, cam in enumerate(cameras):
            cam.Attach(tlFactory.CreateDevice(devices[i]))
            items = items + (str(cam.GetDeviceInfo().GetFriendlyName()), )

        item, ok = QInputDialog.getItem(self,
                                        "Select Basler camera",
                                        "List of avaible camera",
                                        items,
                                        0,
                                        False,
                                        flags=QtCore.Qt.WindowStaysOnTopHint)

        if ok and item:
            items = list(items)
            index = items.index(item)
            self.id = cameras[index].GetDeviceInfo().GetSerialNumber()
            for i in devices:
                if i.GetSerialNumber() == self.id:
                    camConnected = i
            self.cam0 = pylon.InstantCamera(
                tlFactory.CreateDevice(camConnected))
            self.ccdName = self.cam0.GetDeviceInfo().GetFriendlyName()
            self.isConnected = True
            self.nbcam = 'camDefault'
        else:
            self.isConnected = False
            self.nbcam = 'camDefault'

        if self.isConnected == True:
            self.setCamParameter()
Esempio n. 13
0
    def openCamByID(self, camID=0):
        '''connect to a serial number
        '''

        # if
        # self.camID=self.conf.value(self.nbcam+"/camID") ## read cam serial number
        # self.ccdName=self.conf.value(self.nbcam+"/nameCDD")
        self.camID = camID

        for i in devices:

            if i.GetSerialNumber() == self.camID:
                camConnected = i
                # print(('ici'))
                self.cam0 = pylon.InstantCamera(
                    tlFactory.CreateDevice(camConnected))

                self.isConnected = True
                break
            else:
                self.isConnected = False
        # print('la',self.isConnected)
        if self.isConnected == True:

            self.setCamParameter()
def save_image(ruta):
    img = pylon.PylonImage()
    tlf = pylon.TlFactory.GetInstance()
    cam = pylon.InstantCamera(tlf.CreateFirstDevice())
    cam.Open()

    #configuracion de parametros de tamano
    cam.Width.SetValue(1920)
    cam.Height.SetValue(1200)
    cam.OffsetX = 0  #debe ser multiplo de 2
    cam.OffsetY = 0  #debe ser multiplo de 2

    #inicia captura de imagenes
    cam.StartGrabbing()
    result = cam.RetrieveResult(2000)

    # codigo para obtener la matriz RGB sin guardar la imagen
    #converter = pylon.ImageFormatConverter()
    #converter.OutputPixelFormat = pylon.PixelType_RGB8packed
    #converted = converter.Convert(result)
    #image_rgb = converted.GetArray()
    #print("el tamano de la matriz es", image_rgb.shape)

    #codigo para guardar la imagen
    img.AttachGrabResultBuffer(result)
    img.Save(pylon.ImageFileFormat_Tiff, ruta)

    img.Release()
    cam.StopGrabbing()
    cam.Close()
def initialize_camera():
    cam = pylon.InstantCamera(
        pylon.TlFactory.GetInstance().CreateFirstDevice())
    print("Camera Connected : ", cam.GetDeviceInfo().GetModelName())
    cam.Open()
    cam.PixelFormat.SetValue('RGB8')
    return cam
Esempio n. 16
0
 def __init__(self):
     # conecting to the first available camera
     self.camera = pylon.InstantCamera(
         pylon.TlFactory.GetInstance().CreateFirstDevice())
     self.camera.Open()
     self.temp_exp = 16.0
     self.acquisition()
Esempio n. 17
0
    def __init__(self, parent=None):
        """ 初始化
              - self.connect:連接狀態
              - self.running:讀取狀態
        """
        # 將父類初始化
        super().__init__(parent)
        # 建立 cv2 的攝影機物件
        self.isCatch = False
        self.connect = True
        self.running = False

        # 判斷攝影機是否正常連接
        try:
            # conecting to the first available camera
            self.cam = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
            # Grabing Continusely (video) with minimal delay
            self.cam.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) 
            self.converter = pylon.ImageFormatConverter()
            # converting to opencv bgr format
            self.converter.OutputPixelFormat = pylon.PixelType_BGR8packed
            self.converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned          
        except:
            self.connect = False
            print('Check pylon IP Status.')
Esempio n. 18
0
def Cam():

	# conecting to the first available camera
	camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())

	# Grabing Continusely (video) with minimal delay
	camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) 
	converter = pylon.ImageFormatConverter()

	# converting to opencv bgr format
	converter.OutputPixelFormat = pylon.PixelType_BGR8packed
	converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned

	while camera.IsGrabbing():
		grabResult = camera.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException)

		if grabResult.GrabSucceeded():
			# Access the image data
			image = converter.Convert(grabResult)
			img = image.GetArray()
			cv2.namedWindow('Title', cv2.WINDOW_NORMAL)
			cv2.imshow('Title', img)
		
			k = cv2.waitKey(1)
			if k == 27:
				break

		grabResult.Release()

	# Releasing the resource    
	camera.StopGrabbing()

	cv2.destroyAllWindows()
Esempio n. 19
0
def connect_camera(serial_number):
    ''' Connects camera specified with its serial number

    Parameters
    ----------
    serial_number : string
        Camera's serial number.
    Returns
    -------
    camera : object
    '''
    info = None
    for i in pylon.TlFactory.GetInstance().EnumerateDevices():
        if i.GetSerialNumber() == serial_number:
            info = i
            break
    else:
        print('Camera with {} serial number not found'.format(serial_number))

    # VERY IMPORTANT STEP! To use Basler PyPylon OpenCV viewer you have to call .Open() method on you camera
    if info is not None:
        camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateDevice(info))
        camera.Open()
        return camera
    else:
        return None
Esempio n. 20
0
def capture():
    # nombre d'image à enregistrer
    countOfImagesToGrab = 1

    # code sortie de l'application.
    exitCode = 0

    #.On cree un objet camera attaché à la première caméra trouvée
    camera = pylon.InstantCamera(
        pylon.TlFactory.GetInstance().CreateFirstDevice())

    # noombre de buffers autorisé pour la capture d'images
    camera.MaxNumBuffer = 5

    # images.commence l'aquisition d'une image
    # paramètres par defaut
    #aquisition continue.
    camera.StartGrabbingMax(countOfImagesToGrab)

    while camera.IsGrabbing():
        # attendre maximum 5000ms pour une image.
        grabResult = camera.RetrieveResult(
            5000, pylon.TimeoutHandling_ThrowException)
        if grabResult.GrabSucceeded():
            # on affuche les données de l'image
            print("SizeX: ", grabResult.Width)
            print("SizeY: ", grabResult.Height)
            img = grabResult.Array
        else:
            print("Error: ", grabResult.ErrorCode, grabResult.ErrorDescription)
        grabResult.Release()
    return (img)
Esempio n. 21
0
def init_camera(myinfo, reinit_time=True):
    """
    Initialises the Basler camera ; 
    Sets some parameters that are input at the beginning of the script
    """
    camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
    camera.Close()
    camera.Open()
    myinfo['cameraname'] = camera.GetDeviceInfo().GetModelName()
    camera.AcquisitionFrameRateEnable.SetValue(True), camera.AcquisitionFrameRateAbs.SetValue(5)         # Setting fps to 5
    camera.BinningModeVertical.SetValue('Averaging'), camera.BinningModeHorizontal.SetValue('Averaging') # Activating binning in x & y
    camera.BinningHorizontal.SetValue(myinfo['binning']), camera.BinningVertical.SetValue(myinfo['binning'])                 # Setting n_binning
    camera.Width.SetValue(myinfo['width']), camera.Height.SetValue(myinfo['height'])   # Setting width AFTER binning to avoid weird things
    camera.CenterX.SetValue(True), camera.CenterY.SetValue(True)
    camera.ExposureTimeAbs.SetValue(myinfo['exposure'])
    camera.PixelFormat.SetValue(myinfo['pixel_fmt'])
    camera.GevSCPD.SetValue(10000)
    camera.GevSCFTD.SetValue(10000)
    camera.GevSCBWR.SetValue(10)
    camera.GevSCBWRA.SetValue(3)

    if reinit_time:
        camera.GevTimestampControlReset()
    
    return camera
Esempio n. 22
0
 def singleCaptureUI(self): # add laser control when testing on rpi
     self.editTextBox("single capture starting/processing.")
     if hasattr(self, "camera"): # deactivate if video is interrupted with single capture
         self.camera.Close()
         self.videoOn = False
         pass
     self.camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
     self.camera.Open()
     self.camera = cameraSetVals(self.camera, singleConfig)
     self.laser.on()
     sleep(0.5)
     buffer = self.camera.GrabOne(int(singleConfig['expo']*1.1))
     if not buffer:
         raise RuntimeError("Camera failed to capture single image")
     image = self.singleConverter.Convert(buffer).GetArray()
     image = (image * 16)
     image = cv2.medianBlur(image, 3)
     self.laser.off()
     self.im_widget.setImage(np.transpose(image))
     buffer.Release()
     self.camera.Close()
     # save image with what is in the lineEdit box, unique number increasing
     if self.autoCircles:
         self.autoAnalyze(image, "single")
     else:
         self.editTextBox("saved slide" + str(self.slideNumber) + " ar" + str(self.arrayCount))
     self.saveImage(image)
 def auto_exposure(self):
     self.cap0.release()  # lâche le flux vidéo
     self.camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
     self.camera.Open()
     self.camera.ExposureAuto.SetValue('Off')#Continuous, SingleFrame
     self.camera.ExposureTime.SetValue(self.temp_exp)
     self.camera.AcquisitionMode.SetValue('SingleFrame')
     exp_ok=False
     max=self.max_photo()
     while exp_ok == False:
         if max<=180:
             self.temp_exp=self.temp_exp*2.
             max=self.max_photo()
             print(self.temp_exp)
         elif max >=255:
             self.temp_exp=self.temp_exp/1.6
             max=self.max_photo()
             print(self.temp_exp)
         elif self.temp_exp>=2000000.0:
             exp_ok=True
             print('Exp time too big')
             break
         elif self.temp_exp<=16.0:
             exp_ok=True
             print('Exp time too short')
             break
         else:
             exp_ok=True
             break
     self.camera.Close()
     self.cap0 = cv2.VideoCapture(self.cam0)
     return
Esempio n. 24
0
    def __init__(self, sources='streams.txt', img_size=640):
        self.mode = 'images'
        self.img_size = img_size
        sources = [sources]
        n = len(sources)
        self.imgs = [None] * n
        self.sources = sources
        converter = pylon.ImageFormatConverter()
        # converting to opencv bgr format
        converter.OutputPixelFormat = pylon.PixelType_BGR8packed
        converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned
        for i, s in enumerate(sources):
            # Start the thread to read frames from the video stream
            print('%g/%g: %s... ' % (i + 1, n, s), end='')
            # conecting to the first available camera
            camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
            # Grabing Continusely (video) with minimal delay
            camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly) 
            grabResult = camera.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException)
            if grabResult.GrabSucceeded():
                self.imgs[i] = converter.Convert(grabResult).GetArray()
            thread = Thread(target=self.update, args=([i, camera]), daemon=True)
            thread.start()

        print('')  # newline
        # check for common shapes
        s = np.stack([letterbox(x, new_shape=self.img_size)[0].shape for x in self.imgs], 0)  # inference shapes
        self.rect = np.unique(s, axis=0).shape[0] == 1  # rect inference if all shapes equal
        if not self.rect:
            print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
Esempio n. 25
0
def save_image(ruta,logger):
  img = pylon.PylonImage()
  tlf = pylon.TlFactory.GetInstance()
  try:
      cam = pylon.InstantCamera(tlf.CreateFirstDevice())     
      try:
          cam.Open()
          #configuracion de parametros de tamano
          cam.Width.SetValue(1920)
          cam.Height.SetValue(1200)
          cam.OffsetX=0 #debe ser multiplo de 2
          cam.OffsetY=0  #debe ser multiplo de 2
          #inicia captura de imagenes
          cam.StartGrabbing()
          result=cam.RetrieveResult(2000)
          #codigo para guardar la imagen
          img.AttachGrabResultBuffer(result)     
          img.Save(pylon.ImageFileFormat_Tiff, ruta)
          img.Release()
          cam.StopGrabbing()
          return True
      except: # excepcion en caso de que no se pueda generar la coneccion
          cam.Close()
          return False
      finally:#si finaliza la obtencion de la foto
          cam.Close()         
  except: #escepcion en caso de que la camara no este conectada
      logger.error("Error conectando la camara") 
      return False  
    def camera_show(self):
        # if timer is stopped
        if not self.timer_camera_big.isActive(
        ) and not self.timer_camera_small.isActive():

            # start timer
            self.timer_camera_big.start(
            )  # timeout interval = default = 0 msec
            self.timer_camera_small.start()

            # conecting to the first available camera and loading its features
            self.camera = pylon.InstantCamera(
                pylon.TlFactory.GetInstance().CreateFirstDevice())
            self.camera.Open()
            nodeFile = "daA1920-30uc_22901961.pfs"
            pylon.FeaturePersistence.Load(nodeFile, self.camera.GetNodeMap(),
                                          True)
            self.camera.Close()

            # Grabing Continusely (video) with minimal delay
            self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)
            self.converter_RGB = pylon.ImageFormatConverter()

            # converting to opencv bgr format
            self.converter_RGB.OutputPixelFormat = pylon.PixelType_RGB8packed
            self.converter_RGB.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned

            self.cap_signal.emit("Capture Done!")

        else:
            self.cap_signal.emit("Camera has already been in capture mode!")
Esempio n. 27
0
    def test_grab(self):
        countOfImagesToGrab = 5
        imageCounter = 0
        camera = pylon.InstantCamera(
            pylon.TlFactory.GetInstance().CreateFirstDevice())

        camera.Open()

        camera.Width.Value = camera.Width.Max
        camera.Height.Value = camera.Height.Max
        camera.ExposureTime.SetValue(camera.ExposureTime.Min)

        camera.StartGrabbingMax(countOfImagesToGrab)
        # Camera.StopGrabbing() is called automatically by the RetrieveResult() method
        # when c_countOfImagesToGrab images have been retrieved.
        while camera.IsGrabbing():
            # Wait for an image and then retrieve it. A timeout of 5000 ms is used.
            grabResult = camera.RetrieveResult(
                5000, pylon.TimeoutHandling_ThrowException)
            # Image grabbed successfully?
            if grabResult.GrabSucceeded():
                # Access the image data.
                imageCounter = imageCounter + 1
                self.assertEqual(camera.Width.Max, grabResult.Width)
                self.assertEqual(camera.Height.Max, grabResult.Height)
                img = grabResult.Array
            grabResult.Release()
        self.assertEqual(countOfImagesToGrab, imageCounter)
        camera.Close()
Esempio n. 28
0
def take_picutre(file_path):
    """
    Basler相机拍照
    """
    num_img_to_save = 1
    img = pylon.PylonImage()
    tlf = pylon.TlFactory.GetInstance()

    cam = pylon.InstantCamera(tlf.CreateFirstDevice())
    cam.Open()
    cam.StartGrabbing()
    for i in range(num_img_to_save):
        with cam.RetrieveResult(2000) as result:

            # Calling AttachGrabResultBuffer creates another reference to the
            # grab result buffer. This prevents the buffer's reuse for grabbing.
            img.AttachGrabResultBuffer(result)

            filename = file_path
            img.Save(pylon.ImageFileFormat_Png, filename)

            # In order to make it possible to reuse the grab result for grabbing
            # again, we have to release the image (effectively emptying the
            # image object).
            img.Release()

    cam.StopGrabbing()
    cam.Close()

    return 0
Esempio n. 29
0
 def connectDisconnectCam(self):
     # Callback for connect/disconnect cam button.
     # If cam is connected: disconnect cam.
     if self.cam_connected:
         try:
             # Close cam.
             self.cam.Close()
             # Reset button text.
             self.connectBtn.setText('Connect Cam')
             # Disable video button.
             self.startStopBtn.setEnabled(False)
             self.cam_connected = False
             # Disable slider and text edit for exposure time.
             self.expEdit.setEnabled(False)
             self.expSlider.setEnabled(False)
         except:
             # If an error occured: display message box.
             msgBox = QtGui.QMessageBox()
             msgBox.setText("Cam Connection Error")
             msgBox.exec_()
     # If no cam is connected: try to connect to first device.
     else:
         try:
             # Try to create InstantCamera object from first device.
             self.cam = py.InstantCamera(
                     py.TlFactory.GetInstance().CreateFirstDevice())
             # Open cam.
             self.cam.Open()
             # Disable auto exposure.
             self.cam.ExposureAuto = "Off"
             # Disable auto gain.
             self.cam.GainAuto = "Off"
             # Get current exposure time.
             T = int(self.cam.ExposureTime())
             # Set exposure time text edit to current exposure time value.
             self.expEdit.setText(str(T))
             # Check if exposure time is within limits and
             # set slider and cam exposure time accordingly.
             if T > self.eMax:
                 self.expSlider.setValue(self.eMax)
                 self.cam.ExposureTime = self.eMax
             else:
                 self.expSlider.setValue(T)
             # Set button text to "Disconnect Cam".
             self.connectBtn.setText('Disconnect Cam')
             self.cam_connected = True
             # Enable start/stop-video-button.
             self.startStopBtn.setEnabled(True)
             # Enable text edit and slider for exposure time.
             self.expEdit.setEnabled(True)
             self.expSlider.setEnabled(True)
             self.cam.StartGrabbing(py.GrabStrategy_LatestImages)
         except:
             # Catch connection error with message box.
             msgBox = QtGui.QMessageBox()
             msgBox.setText("Cam Connection Error")
             msgBox.exec_()
     # Emit connection changed signal.
     self.connection_changed.emit()
Esempio n. 30
0
    def __init__(self):
        t = time.time()
        self.img0 = []
        nodeFile = "NodeMap.pfs"
        self.windowName = 'title'
        self.temp_exp = 100.0

        try:
            # Create an instant camera object with the camera device found first.
            self.camera = pylon.InstantCamera(
                pylon.TlFactory.GetInstance().CreateFirstDevice())
            self.camera.Open()  #Ouvre la communication avec la caméra
            self.Model = self.camera.GetDeviceInfo().GetModelName()

            if self.Model == "acA1920-40uc":
                self.camera.PixelFormat.SetValue('Mono8')
                self.tps_exp_min = 50
                self.pixel_size = 5.86  #microns (pixels carrés sur les baslers)
                self.pixel_max = 255

            elif self.Model == "acA5472-17um":
                self.camera.PixelFormat.SetValue('Mono12')
                self.tps_exp_min = 50
                self.pixel_size = 2.4  #microns (pixels carrés sur les baslers)
                self.pixel_max = 4095

            else:
                print("Camera non reconnue")

            self.width = self.camera.Width.GetValue()
            self.height = self.camera.Height.GetValue()
            self.ratio = float(self.width / self.height)

            pylon.FeaturePersistence.Save(nodeFile, self.camera.GetNodeMap())

            # Print the model name of the camera.
            print("Using device ", self.camera.GetDeviceInfo().GetModelName())
            #print("Exposure time ", self.camera.ExposureTime.GetValue())
            #print("Pixels formats :", self.camera.PixelFormat.Symbolics)

            self.auto_exposure()  #This line HAS TO STAY HERE :')

            # converting to opencv bgr format
            self.converter = pylon.ImageFormatConverter()
            self.converter.OutputPixelFormat = pylon.PixelType_Mono16
            self.converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned

            # According to their default configuration, the cameras are
            # set up for free-running continuous acquisition.
            #Grabbing continuously (video) with minimal delay
            #self.camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)

        except genicam.GenericException as e:
            # Error handling
            print("An exception occurred.", e.GetDescription())
            exitCode = 1

        temps = time.time() - t
        print("Temps acquisition caméra  : ", temps)