def capture_and_save_png(camera, filename): """ Captures an image to save it as a png in the given path. Can also use opencv to saved any converted images. Arguments: camera : Active camera object. It must be in imaging mode. filename : Path to the image Returns: None """ img = pylon.PylonImage() with camera.RetrieveResult(5000) as result: # Calling AttachGrabResultBuffer creates another reference to the # grab result buffer. This prevents the buffer's reuse for grabbing. img.AttachGrabResultBuffer(result) 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() return
def cont_acq(stop, cam): #import pdb #pdb.set_trace() #print("inside cont_acq") img = pylon.PylonImage() #tlf = pylon.TlFactory.GetInstance() #cam = pylon.InstantCamera(tlf.CreateFirstDevice()) #cam.Open() cam.StartGrabbing() t_grab = time.time() for i in range(1000): if stop(): print("STOP!!!!!!") break 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) # 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() if i % 10 == 0: print(i) cam.StopGrabbing() print("Continuous acquisition stopped after", time.time() - t_grab, "seconds")
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 update(self, dt): if self.camera == False: self.connect() if self.camera == False: return try: if self.camera.IsGrabbing(): grabResult = self.camera.RetrieveResult(1000, pylon.TimeoutHandling_ThrowException) if grabResult.GrabSucceeded(): image = grabResult.GetArray() self.array = image image_texture = Texture.create(size=(image.shape[1],image.shape[0]), colorfmt='luminance') image_texture.blit_buffer(image.flatten(), colorfmt='luminance', bufferfmt='ubyte') # display image from the texture self.texture = image_texture self.lastGrab = pylon.PylonImage() self.lastGrab.AttachGrabResultBuffer(grabResult) if self.record == True: self.capture(append = 'ms') grabResult.Release() except genicam.GenericException as e: if self.camera != False: print("It looks like a Lumaview compatible camera was unplugged") self.camera = False
def getHDRImage(self, name='test', saveImage=True, saveNumpy=True, timeout=5000): if self.calibration is None: print("Initialize calibration object of camera class first") self.cap.StartGrabbingMax(1) img = pylon.PylonImage() frames = [] for e in self.hdr_exposures: self.setExposure(e) while self.cap.IsGrabbing(): # Grabs photo from camera grabResult = self.cap.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException) if grabResult.GrabSucceeded(): # Access the image data. frame = grabResult.Array img.AttachGrabResultBuffer(grabResult) grabResult.Release() frames.append(frame) hdr_frame = self.calibration.radio_calib.get_HDR_image(frames, self.hdr_exposures) if saveNumpy: np.save('CapturedNumpyData/' + name, hdr_frame) if saveImage: png_frame = (hdr_frame - np.min(hdr_frame)) / (np.max(hdr_frame) - np.min(hdr_frame)) png_frame *= 255.0 io.imsave('CapturedImages/' + name + '.PNG', png_frame.astype(np.uint8)) return hdr_frame
def getImage(self, name='test', saveImage=True, saveNumpy=True, calibration=False, timeout=5000): try: # Take and return current camera frame self.cap.StartGrabbingMax(1) img = pylon.PylonImage() while self.cap.IsGrabbing(): # Grabs photo from camera grabResult = self.cap.RetrieveResult(timeout, pylon.TimeoutHandling_ThrowException) if grabResult.GrabSucceeded(): # Access the image data. frame = grabResult.Array img.AttachGrabResultBuffer(grabResult) grabResult.Release() # Save if desired if saveImage: if calibration: filename = 'CalibrationImages/' + name + '.raw' filenamePNG = 'CalibrationImages/' + name + '.PNG' img.Save(pylon.ImageFileFormat_Raw, filename) img.Save(pylon.ImageFileFormat_Png, filenamePNG) else: filename = 'CapturedImages/' + name + '.PNG' img.Save(pylon.ImageFileFormat_Png, filename) if saveNumpy: if calibration: np.save('CalibrationNumpyData/' + name, frame) else: np.save('CapturedNumpyData/' + name, frame) img.Release() self.cap.StopGrabbing() return frame except SystemError: self.quit_and_open() return None
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 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
def save_images(cam): num_img_to_save = 9 img = pylon.PylonImage() #tlf = pylon.TlFactory.GetInstance() #cam = pylon.InstantCamera(tlf.CreateFirstDevice()) #cam.Open() cam.StartGrabbing() t_grab = time.time() 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) if platform.system() == 'Windows': # The JPEG format that is used here supports adjusting the image # quality (100 -> best quality, 0 -> poor quality). #ipo = pylon.ImagePersistenceOptions() #quality = 90 - i * 10 #ipo.SetQuality(quality) filename = "saved_pypylon_img_%d.tiff" % i img.Save(pylon.ImageFileFormat_Tiff, filename) else: filename = "saved_pypylon_img_%d.tiff" % i img.Save(pylon.ImageFileFormat_Tiff , 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() print("time of only grabbing 9 im, (no startup): ", time.time() - t_grab) cam.StopGrabbing()
def start(self): print('START OBCS') self.stop_camera = False try: img = pylon.PylonImage() tlf = pylon.TlFactory.GetInstance() # Create an instant camera object with the camera device found first. while(True): try: camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice()) break except: print('Can not find camera device. Trying again... ') time.sleep(3) print("Using device ", camera.GetDeviceInfo().GetModelName()) camera.MaxNumBuffer = 5 camera.Open() while True: if self.stop_camera : break self.img_counter += 1 camera.StartGrabbingMax(self.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(): # Calling AttachGrabResultBuffer creates another reference to the # grab result buffer. This prevents the buffer's reuse for grabbing. img.AttachGrabResultBuffer(grabResult) filename = os.path.join(self.image_dir, "image_%d.png" % self.img_counter) self.image_lock.acquire() img.Save(pylon.ImageFileFormat_Png, filename) self.image_lock.release() else: print("Error: ", grabResult.ErrorCode, grabResult.ErrorDescription) img.Release() # check if m a tab grabResult.Release() time.sleep(20) except genicam.GenericException as e: # Error handling. print("An exception occurred.") print(e.GetDescription()) self.exitCode = 1
def __init__(self, folder_path, queue): self.queue = queue self.img = pylon.PylonImage() self.cam = pylon.InstantCamera( pylon.TlFactory.GetInstance().CreateFirstDevice()) self.nbr_im = 9 self.folder_path = folder_path os.mkdir(self.folder_path) # unique folder for this measurement self.counter = 0 self.thread_move = None self.nodefile = "acA1920-155um_bin_3.pfs" #"daA1600-60um_gain.pfs"#"acA1920-155um_bin_2.pfs"#"daA1600-60um_gain.pfs"
def guardar_imagen(camara,ruta,logger): try: #inicia captura de imagenes camara.StartGrabbing() result=camara.RetrieveResult(2000, pylon.TimeoutHandling_ThrowException) #result = camara.GrabOne(2000, pylon.TimeoutHandling_ThrowException)#timeout 2000 ms #otra opcion para adquirir una imagen #codigo para guardar la imagen img = pylon.PylonImage() img.AttachGrabResultBuffer(result) img.Save(pylon.ImageFileFormat_Tiff, ruta) img.Release() camara.StopGrabbing() return camara except: logger.error("Error adquiriendo la imagen") return 0
def guardar_imagen(camara, ruta): try: #inicia captura de imagenes camara.StartGrabbing() #result = camara.GrabOne(2000, pylon.TimeoutHandling_ThrowException)#timeout 2000 ms result = camara.RetrieveResult(2000, pylon.TimeoutHandling_ThrowException) #codigo para guardar la imagen img = pylon.PylonImage() img.AttachGrabResultBuffer(result) img.Save(pylon.ImageFileFormat_Tiff, ruta) img.Release() print("foto obtenida") camara.StopGrabbing() return camara except: sleep(1) print("error adquiriendo la imagen") return 0
def saveImage(self): if self.save_dir is "./": self.saveDir() self.isSaving = True self.saveButton.setText("Saving...") now = "{}".format(datetime.now()).replace(":", "-") filename = now + ".png" path = self.save_dir + "/" + filename #print(path) try: img = pylon.PylonImage() img.AttachGrabResultBuffer(self.grabResult) img.Save(pylon.ImageFileFormat_Png, path) except: QtWidgets.QMessageBox.about(None, "Saving Error", "Camera is not connected")
def update(self, dt): if self.camera == False: self.connect() if self.camera == False: self.source = "./data/camera to USB.png" return try: if self.camera.IsGrabbing(): grabResult = self.camera.RetrieveResult( 1000, pylon.TimeoutHandling_ThrowException) if grabResult.GrabSucceeded(): image = grabResult.GetArray() self.array = image image_texture = Texture.create(size=(image.shape[1], image.shape[0]), colorfmt='luminance') image_texture.blit_buffer( image.flatten(), colorfmt='luminance', bufferfmt='ubyte') # display image from the texture self.texture = image_texture self.lastGrab = pylon.PylonImage() self.lastGrab.AttachGrabResultBuffer(grabResult) if self.record == True: global lumaview lumaview.capture(0) grabResult.Release() except: if self.camera == False: print( "A LumaViewPro compatible camera or scope was disconnected." ) print("Error: PylonCamera.update() exception") self.camera = False
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 guardar la imagen img.AttachGrabResultBuffer(result) img.Save(pylon.ImageFileFormat_Tiff, ruta) img.Release() cam.StopGrabbing() cam.Close()
def Photo(e, hd, device, token, exp): try: if device == "N/A": raise Exception('This camera is not avaiable') tlf = pylon.TlFactory.GetInstance() dev = tlf.EnumerateDevices() i = 0 while True: if (dev[i].GetIpAddress() == device): break i = i + 1 if (i == len(dev)): raise Exception('This camera is not avaiable') cam = pylon.InstantCamera(tlf.CreateDevice(dev[i])) cam.Open() img = pylon.PylonImage() print(hd["name"] + " camera started.") if (exp != "auto"): cam.ExposureTime.SetValue(int(exp)) while e.is_set(): if (synchronizer.Synchro(token) == 1): try: if (not cam.IsGrabbing()): cam.StartGrabbing() result = cam.RetrieveResult(2000) # Calling AttachGrabResultBuffer creates another reference to the # grab result buffer. This prevents the buffer's reuse for grabbing. img.AttachGrabResultBuffer(result) if (img.IsGrabResultBufferAttached()): filename = hd["name"] + "_%d" % (int(time.time())) Save.SaveMetadata(filename + ".png") img.Save(pylon.ImageFileFormat_Png, filename) hd["timestamp"] = str( time.gmtime().tm_year) + "-" + str( time.gmtime().tm_mon) + "-" + str( time.gmtime().tm_mday) + "T" + str( time.gmtime().tm_hour) + ":" + str( time.gmtime().tm_min) + ":" + str( time.gmtime().tm_sec) img.Release() cam.StopGrabbing() print("New image " + hd["name"]) hd["acquiredImages"] = hd["acquiredImages"] + 1 synchronizer.Update() except genicam.RuntimeException as exc: hd["error"] = str(exc) hd["status"] = "GenError" except genicam.LogicalErrorException as exc: hd["error"] = str(exc) hd["status"] = "GenError" except Exception as exc: hd["error"] = str(exc) synchronizer.Update() cam.Close() except Exception as err: hd["error"] = str(err) hd["status"] = "error" synchronizer.removefromQueue(token) e.clear()
"""This sample shows how grabbed images can be saved using pypylon only (no need to use openCV). Available image formats are (depending on platform): - pylon.ImageFileFormat_Bmp (Windows) - pylon.ImageFileFormat_Tiff (Linux, Windows) - pylon.ImageFileFormat_Jpeg (Windows) - pylon.ImageFileFormat_Png (Linux, Windows) - pylon.ImageFileFormat_Raw (Windows) """ from pypylon import pylon import platform num_img_to_save = 5 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) if platform.system() == 'Windows': # The JPEG format that is used here supports adjusting the image # quality (100 -> best quality, 0 -> poor quality). ipo = pylon.ImagePersistenceOptions() quality = 90 - i * 10