Пример #1
0
    def capture_image(self, image_path):
        # Kludge - keep trying to capture the image
        # gphoto throws exceptions if for example the camera can't focus
        for x in range(0, 5):
            try:
                if hasattr(self, 'camera'):
                    # Delete the camera object. This causes the mirror to close, otherwise
                    # we don't get autofocus!
                    del self.camera
                self.camera = piggyphoto.camera()

                self.set_settings_for_capture()
                self.camera.capture_image(image_path)
                self.reset_settings()

                if x > 0:
                    logger.info("Captured image after %d attempts", x)
                return
            except Exception, e:
                logger.exception("Failed to capture image, attempt %d", x)
                if x >= 4:
                    if hasattr(self, 'camera'):
                        # Release the camera. Hopefully its more likely to work after a restart
                        del self.camera
                    raise e
                else:
                    time.sleep(x)
Пример #2
0
    def userEvent(self):
        Logging.info('UserEvent Received. Current State is',
                     state)  # Adding logging to current state
        self.mutex.acquire()

        # check if we can connect to the camera
        if self.camera == None:
            try:
                self.camera = piggyphoto.camera()
                self.previewImage.setCamera(capturePreviewFile, self.camera)
            except:
                self.camera = None

        if self.state == EState.PREVIEW:
            self.mutex.release()
            self.runCounter()
            Logging.info('Transitioning to runCounter method')

        elif self.state == EState.INSPECTION:
            self.mutex.release()
            self.removeLatestImage()

        elif self.state == EState.SLIDESHOW:
            self.mutex.release()
            self.stopSlideShow()

        else:
            self.mutex.release()

        pass
Пример #3
0
	def userEvent(self):
				
		self.mutex.acquire()
		
		# check if we can connect to the camera
		if self.camera == None:
			try:
				self.camera = piggyphoto.camera()
				self.previewImage.setCamera(capturePreviewFile, self.camera)	
			except:
				self.camera = None

		if self.state == EState.PREVIEW:
			self.mutex.release()
			self.runCounter()
		
		elif self.state == EState.INSPECTION:
			self.mutex.release()
			self.removeLatestImage()
			
		elif self.state == EState.SLIDESHOW:
			self.mutex.release()
			self.stopSlideShow()
			
		else:
			self.mutex.release()
			
		pass
Пример #4
0
def grab_image2(filename, i, usecamera=True):
	# Only capture image if it's one of the four... 
	if i in range(4): 
		# grab from camera or make a copy of the dummy images (for testing...)
		if usecamera:
			# create PTP connection to camera...
			C = piggyphoto.camera() 
			C.capture_image(filename+'_'+suffix[i] + '.jpg')
		else: shellcmd('cp images/DSCdummy'+str(i+1)+'.jpg '+filename+'_'+suffix[i] + '.jpg')
Пример #5
0
def take_both():
    uid = request.form.get('uid', str(int(time.time())))
    img_name = '%s.jpg' % (uid)
    img_loc = 'static/both/%s' % img_name

    C = piggyphoto.camera()
    C.capture_image('/tmp/both.jpg')
    os.rename('/tmp/both.jpg', img_loc)

    return jsonify({'url' : img_loc})
Пример #6
0
def take_photo(surface, images):
    global IDLE

    if IDLE:
        IDLE = False

        play_sequence(surface, images['sequence'])

        try:
            camera = piggyphoto.camera()
        except piggyphoto.libgphoto2error, errormessage:
            error_handling(surface, str(errormessage))

        if not os.path.exists(IMAGES_PATH):
            os.makedirs(IMAGES_PATH, 0777)
        filename = os.path.join(
            IMAGES_PATH,
            IMAGE_NAME_TEMPLATE.format(
                format(get_next_image_number(IMAGES_PATH), '04d')))

        try:
            camera.capture_image(filename)

            images['processed_image'] = pygame.transform.scale(
                images['processed_image'], DISPLAY_SIZE)

            surface.blit(images['processed_image'], TOP_LEFT)
            pygame.display.update()
            #pygame.time.delay(500)

            if CREATE_THUMBNAIL:
                thumbnail_file = create_thumbnail(filename, THUMBNAIL_PATH,
                                                  THUMBNAIL_WIDTH)

                photo = pygame.transform.scale(
                    pygame.image.load(thumbnail_file).convert_alpha(),
                    surface.get_size())
                surface.blit(photo, TOP_LEFT)
                pygame.display.update()
                pygame.time.delay(5000)
                surface.fill(BLACK)
                pygame.time.delay(500)

            else:
                photo = pygame.transform.scale(
                    pygame.image.load(filename).convert_alpha(),
                    surface.get_size())
                surface.blit(photo, TOP_LEFT)
                pygame.display.update()
                pygame.time.delay(5000)
                surface.fill(BLACK)
                pygame.time.delay(500)

        except piggyphoto.libgphoto2error, errormessage:
            error_handling(surface, str(errormessage))
Пример #7
0
def grab_image(filename, i, usecamera=True):
	# Only capture image if it's one of the four... 
	if i in range(4): 
		# grab from camera or make a copy of the dummy images (for testing...)
		if usecamera:
			# create PTP connection to camera...
			C = piggyphoto.camera() 
			C.capture_image(filename+'_'+suffix[i] + '.jpg')
		else: shellcmd('cp images/DSCdummy'+str(i+1)+'.jpg '+filename+'_'+suffix[i] + '.jpg')
	# create flag file indicating that photo file download from camera completed...
	open(filename+'_'+suffix[i]+'_done', 'w').write('done') 
Пример #8
0
    def __init__(self,
                 resolution=(1488, 1120),
                 num_images=1,
                 temp_filename_prefix='gphoto_temp',
                 debug_ptr=None,
                 callsign="N0CALL"):
        """ Instantiate a WenetGPhoto Object
			used to capture images using GPhoto.

			Keyword Arguments:
			callsign: The callsign to be used when converting images to SSDV. Must be <=6 characters in length.
			
			resolution: Tuple (x,y) containing desired image *transmit* resolution.
						NOTE: The raw image from the camera will be saved with whatever resolution is set on the camera.
						NOTE: both x and y need to be multiples of 16 to be used with SSDV.


			num_images: Number of images to capture in sequence when the 'capture' function is called.
						The 'best' (largest filesize) image is selected and saved.

			temp_filename_prefix: prefix used for temporary files.

			debug_ptr:	'pointer' to a function which can handle debug messages.
						This function needs to be able to accept a string.
						Used to get status messages into the downlink.

		"""

        self.debug_ptr = debug_ptr
        self.temp_filename_prefix = temp_filename_prefix
        self.num_images = num_images
        self.callsign = callsign
        self.resolution = resolution

        # Attempt to set camera time.
        # This also tells us if we can communicate with the camera or not.
        proc = subprocess.Popen(['gphoto2', '--set-config', 'datetime=now'],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        proc.wait()
        if "Error" in proc.stderr.read():
            print("Could not communicate with camera!")

        # Now open a 'piggyphoto' (py-gphoto) instance for all further communication.
        self.camera_connected = False
        while not self.camera_connected:
            try:
                self.cam = piggyphoto.camera()
                self.camera_connected = True
            except Exception as e:
                self.debug_message("ERROR: %s - Is the camera connected?" %
                                   str(e))
                sleep(5)
Пример #9
0
	def __init__(self, **kwargs):
		super(CaptureApp, self).__init__(**kwargs)
		
		if HasRpiGPIO == False:
			self.keyboard = Window.request_keyboard(self.onKeyboardClosed, self)
			self.keyboard.bind(on_key_down = self.onKeyDown)

		
		try:
			self.camera = piggyphoto.camera()
		except:
			self.camera = None
			
		pass
Пример #10
0
	def __init__(self,resolution=(1488,1120), 
				num_images=1, 
				temp_filename_prefix = 'gphoto_temp',
				debug_ptr = None,
				callsign = "N0CALL"):

		""" Instantiate a WenetGPhoto Object
			used to capture images using GPhoto.

			Keyword Arguments:
			callsign: The callsign to be used when converting images to SSDV. Must be <=6 characters in length.
			
			resolution: Tuple (x,y) containing desired image *transmit* resolution.
						NOTE: The raw image from the camera will be saved with whatever resolution is set on the camera.
						NOTE: both x and y need to be multiples of 16 to be used with SSDV.


			num_images: Number of images to capture in sequence when the 'capture' function is called.
						The 'best' (largest filesize) image is selected and saved.

			temp_filename_prefix: prefix used for temporary files.

			debug_ptr:	'pointer' to a function which can handle debug messages.
						This function needs to be able to accept a string.
						Used to get status messages into the downlink.

		"""

		self.debug_ptr = debug_ptr
		self.temp_filename_prefix = temp_filename_prefix
		self.num_images = num_images
		self.callsign = callsign
		self.resolution = resolution

		# Attempt to set camera time.
		# This also tells us if we can communicate with the camera or not.
		proc = subprocess.Popen(['gphoto2','--set-config','datetime=now'],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		proc.wait()
		if "Error" in proc.stderr.read():
			print("Could not communicate with camera!")

		# Now open a 'piggyphoto' (py-gphoto) instance for all further communication.
		self.camera_connected = False
		while not self.camera_connected:
			try:
				self.cam = piggyphoto.camera()
				self.camera_connected = True
			except Exception as e:
				self.debug_message("ERROR: %s - Is the camera connected?" % str(e))
				sleep(5)
Пример #11
0
    def __init__(self, id = 0):
        try:
            import piggyphoto
        except:
            warn("Initializing piggyphoto failed, do you have piggyphoto installed?")
            return

        devices = piggyphoto.cameraList(autodetect=True).toList()
        if not len(devices):
            warn("No compatible digital cameras attached")
            return            

        self.device, self.usbid = devices[id]
        self.camera = piggyphoto.camera()
Пример #12
0
    def __init__(self, **kwargs):
        super(CaptureApp, self).__init__(**kwargs)

        if HasRpiGPIO == False:
            self.keyboard = Window.request_keyboard(self.onKeyboardClosed,
                                                    self)
            self.keyboard.bind(on_key_down=self.onKeyDown)

        try:
            self.camera = piggyphoto.camera()
        except:
            self.camera = None

        pass
Пример #13
0
 def __init__(self, picture_size):
     self.picture_size = picture_size
     # Print the capabilities of the connected camera
     try:
         if piggyphoto_enabled:
             self.cap = piggyphoto.camera()
             print(self.cap.abilities)
         else:
             print(self.call_gphoto("-a", "/dev/null"))
     except CameraException as e:
         print('Warning: Listing camera capabilities failed (' + e.message +
               ')')
     except piggyphoto.libgphoto2error as e:
         print('Warning: Listing camera capabilities failed (' + e.message +
               ')')
Пример #14
0
def take_photo(surface, images):
	global IDLE

	if IDLE:
		IDLE = False

		play_sequence(surface, images['sequence'])
		
		try:
			camera = piggyphoto.camera()
		except piggyphoto.libgphoto2error, errormessage:
			error_handling(surface, str(errormessage))
			
		if not os.path.exists(IMAGES_PATH):
			os.makedirs(IMAGES_PATH, 0777)
		filename = os.path.join(IMAGES_PATH, IMAGE_NAME_TEMPLATE.format(format(get_next_image_number(IMAGES_PATH), '04d')))
		
		try:
			camera.capture_image(filename)
			
			images['processed_image'] = pygame.transform.scale(images['processed_image'], DISPLAY_SIZE)

			surface.blit(images['processed_image'], TOP_LEFT)
			pygame.display.update()
			#pygame.time.delay(500)

			if CREATE_THUMBNAIL:
				thumbnail_file = create_thumbnail(filename, THUMBNAIL_PATH, THUMBNAIL_WIDTH)

				photo = pygame.transform.scale(pygame.image.load(thumbnail_file).convert_alpha(), surface.get_size())
				surface.blit(photo, TOP_LEFT)
				pygame.display.update()
				pygame.time.delay(5000)
				surface.fill(BLACK)
				pygame.time.delay(500)

			else:
				photo = pygame.transform.scale(pygame.image.load(filename).convert_alpha(), surface.get_size())
				surface.blit(photo, TOP_LEFT)
				pygame.display.update()
				pygame.time.delay(5000)
				surface.fill(BLACK)
				pygame.time.delay(500)	
		
			

		except piggyphoto.libgphoto2error, errormessage:
			error_handling(surface, str(errormessage))
Пример #15
0
    def yield_devices(cls, config):
        """ Search for usable devices, yield one at a time

        :param config:  spreads configuration
        :type config:   spreads.config.ConfigView

        """
        pil = pp.portInfoList()
        for name, path in pp.cameraList(autodetect=True).toList():
            pi = pil.get_info(pil.lookup_path(path))
            logger = logging.getLogger('GPhoto2Camera')
            logger.debug("Connecting to camera {} at {}".format(name, path))
            cam = pp.camera(autoInit=False)
            cam.port_info = pi
            cam.init()
            yield cls(config, cam)
Пример #16
0
    def yield_devices(cls, config):
        """ Search for usable devices, yield one at a time

        :param config:  spreads configuration
        :type config:   spreads.config.ConfigView

        """
        pil = pp.portInfoList()
        for name, path in pp.cameraList(autodetect=True).toList():
            pi = pil.get_info(pil.lookup_path(path))
            logger = logging.getLogger('GPhoto2Camera')
            logger.debug("Connecting to camera {} at {}".format(name, path))
            cam = pp.camera(autoInit=False)
            cam.port_info = pi
            cam.init()
            yield cls(config, cam)
Пример #17
0
    def trigger_callback(self, _msg):
        if not "photo" in _msg.data:
            print("Received unknown trigger")
            return
        print("Received trigger!")

        try:
            # Convert your ROS Image message to OpenCV2
            C = piggyphoto.camera()
            print C.abilities
            C.capture_image('/home/human4/photobot/camera_image.jpg')
        except e:
            print(e)
        else:

            # Save your OpenCV2 image as a jpeg
            self.event_trigger.publish("Photo taken")
Пример #18
0
def connect_camera():
    global C
    if not C:
        try:
            C = camera()
            C.leave_locked()
            return True
        except:
            C = False
            return False
    else:
        clist = cameraList(autodetect=True)
        if str(clist).startswith("cameraList object with 0 elements"):
            C = False
            return False
        elif C.initialized:
            return True
Пример #19
0
def connect_camera():
    global C
    if not C:
        try:
            C = camera()
            C.leave_locked()
            return True
        except:
            C = False
            return False
    else:
        clist = cameraList(autodetect=True)
        if str(clist).startswith("cameraList object with 0 elements"):
            C = False
            return False
        elif C.initialized:
            return True
Пример #20
0
 def try_set_capturesettings(self, setting):
     for x in range(0, 10):
         try:
             con = self.camera.config
             con.main.capturesettings.autoexposuremode.value = setting
             self.camera.config = con
             if x > 0:
                 logger.info("Set capture settings after %d attempts", x)
             return
         except Exception, e:
             logger.exception("Failed to set capturesettings, attempt %d",
                              x)
             if x >= 9:
                 raise e
             else:
                 time.sleep(x / 2)
             if x > 4 and x % 2 == 1:
                 del self.camera
                 self.camera = piggyphoto.camera()
Пример #21
0
    def __init__(self, host="localhost", port=8010, nowindow=False):
        self.nowindow = nowindow
        self.host = host
        self.port = port

        # osc
        self.oscServer = OSCServer((host, int(port)))
        self.oscServer.addDefaultHandlers()
        self.oscServer.addMsgHandler("/pyying/stream", self.stream_handler)
        self.oscServer.addMsgHandler("/pyying/shoot", self.shoot_handler)
        self.oscThread = threading.Thread(target=self.oscServer.serve_forever)
        self.oscThread.start()
        print "Starting OSCServer. Use ctrl-C to quit."


        # TERM
        signal.signal(signal.SIGTERM, self.sigclose)

        try:
          # check folders exist
          if not os.path.exists(self.path):
                os.makedirs(self.path)
          if not os.path.exists(self.snap_path):
                os.makedirs(self.snap_path)
          self.find_last_number_in_directory()

          # camera
          self.camera = piggyphoto.camera()
          self.camera.leave_locked()
          fullpath = self.path + self.filename + ("%05d" % self.number) + '.' + self.extension
          self.camera.capture_preview(fullpath)

          # create window from first preview
          if (not self.nowindow):
            picture = pygame.image.load(fullpath)
            pygame.display.set_mode(picture.get_size())
            self.main_surface = pygame.display.get_surface()
        except KeyboardInterrupt:
          self.close()
        except Exception as e:
          print str(e)
          self.close()
Пример #22
0
    def __init__(self, width=900, height=768, fps=5, fullscreen=True):
        """Initialize the bits"""
        pygame.init()
        pygame.display.set_caption(CAPTION)
        dir = os.path.dirname(PREVIEW)
        if not os.access(dir, os.W_OK):
            print 'Directory {} is not writable. Ensure it exists and is writable.\n'.format(dir)
            print 'Try `mount -t tmpfs -o size=100m tmpfs {}` to create a ramdisk in that location\n'.format(dir)
            pygame.quit()
            sys.exit()
        self.width = width
        self.height = height
        self.screen = None
        self.fullscreen = fullscreen
        if fullscreen:
            self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN | pygame.DOUBLEBUF)
            (self.width, self.height) = self.screen.get_size()
        else:
            self.screen = pygame.display.set_mode((self.width, self.height), pygame.DOUBLEBUF)
        self.background = pygame.Surface(self.screen.get_size()).convert()
        self.clock = pygame.time.Clock()
        self.base_fps = fps
        self.fps = fps
        self.countdown = READY_WAIT
        self.small_font = pygame.font.SysFont('Arial', 20, bold=True)
        self.large_font = pygame.font.SysFont('Arial', 40, bold=True)
        self.huge_font = pygame.font.SysFont('Arial', 150, bold=True)

        self.camera = piggyphoto.camera()
        self.camera.leave_locked()
        self.camera.capture_preview(PREVIEW)

        self.state = BoothState.waiting
        self.shoot_phase = ShootPhase.get_ready
        self.phase_start = time.time()
        self.shots_left = SHOT_COUNT
        self.shot_counter = 0
        self.session_counter = 1
        self.images = []
        self.pid = os.getpid()
Пример #23
0
    def __init__(self, cam_type):
        self.cam_type = cam_type
        print 'Initializing %s...' % cam_type
        if cam_type == 'sony':
            self.C = piggyphoto.camera()
            self.C.leave_locked()
            self.capture('temp.jpg')
        elif cam_type == 'rs':
            self.pipeline = rs.pipeline()
            config = rs.config()
            config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
            config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)

            # Start streaming
            self.pipeline.start(config)
            self.capture('temp.jpg')

        picture = pygame.image.load('temp.jpg')
        pygame.display.set_mode(picture.get_size())
        self.main_surface = pygame.display.get_surface()

        os.remove('temp.jpg')
Пример #24
0
def main():
    a, b = 0, 0
    zoom = 0
    capt = 'no'
    frames_raz = 'yes'
    camera = piggyphoto.camera()
    camera.leave_locked()
    cx = redis.Redis()
    frames = 0
    cx.set('frames', 0)    
    interval = int(cx.get('interval'))
    stop = False
    while not stop:    
        print time.time(), 'capture preview ...'
        camera.capture_preview('data/preview.jpg')      
        
        if zoom != 0:
            with Image(filename = 'data/preview.jpg') as img:
                with img.clone() as i:
                    i.resize(x, y)
                    i.save(filename='data/preview.jpg')
        
        preview = pygame.image.load('data/preview.jpg')
        screen.blit(preview, (b, a))
        pygame.display.update()
        
        #cx.publish('preview', '')
        
        evts = pygame.event.get()
        for evt in evts:
            if evt.type == pygame.locals.KEYDOWN:
                if evt.key == 27:
                    print "Fin du programme"
                    cx.publish('exit','sys.exit()')
                    stop = True
                elif evt.key == 112: # P
                    pass

                elif evt.key == 115: # S
                    print 'demande de stacking rapide ...'
                    cx.publish('stack_rapide', '')

                elif evt.key == 273: # UP
                    a -= 10    
                elif evt.key == 276: # LEFT
                    b -= 10
                elif evt.key == 275: # RIGHT
                    b += 10
                elif evt.key == 274: # DOWN
                    a += 10
                else:
                    print 'touche inconnue ', evt.key
                
            elif evt.type == pygame.locals.JOYBUTTONDOWN:
                i = evt.button
                nb_photo = ((i-3)*5)
                      
                if nb_photo == -15:
                    nb_photo = 1
                    cx.set('nb_photo', nb_photo)
                    frames_raz = 'no'
                    capt = 'yes'        
                if nb_photo >=5 and nb_photo <=30:
                    cx.set('nb_photo', nb_photo)
                    frames_raz = 'yes'
                    capt = 'yes'
                if evt.button == 11:
                    cx.publish('exit','sys.exit()')
                    sys.exit()
                if evt.button == 1: # Boutton 2
                    print 'demande de stacking lent ...'
                    frames = 0
                    cx.publish('stack_lent', '')
                if evt.button == 3: # Boutton 4
                    cx.publish('envoi', '')
                else:
                    pass
            
            elif evt.type == pygame.locals.JOYAXISMOTION:
                if evt.axis == 3:
                        if evt.value == 1:
                            zoom = 0
                            a, b = 0, 0 
                        elif evt.value < 0.9 and evt.value > 0:
                            zoom = 1
                            x = 1300
                            y = 867
                        elif evt.value == 0:
                            zoom = 2
                            x = 1500
                            y = 1000
                        elif evt.value < 0 and evt.value > -0.9:
                            zoom = 3
                            x = 1700
                            y = 1133
                        elif evt.value <= -1:
                            zoom = 4
                            x = 1900
                            y = 1267
                        else:
                            pass
            
            else:
                pass
        while capt == "yes":
            for i in range(0, nb_photo):
                time.sleep(interval)    
                print 'capture image ...'
                source_capture = 'data/capture.jpg'
                camera.capture_image(source_capture)
                frames += 1          
                cx.set('frames', frames)
                
                # Déplacer la photo 
                time_stamp = time.strftime('%Y%m%d%H%M%S', time.localtime())
                dest_capture = os.path.join('data/images', 'capt%s.jpg' % time_stamp)
                shutil.move(source_capture, dest_capture)
                
                # obtenir les infos saisis
                souche = cx.get('souche')
                substrat = cx.get('substrat')
                fermentation = cx.get('fermentation')
                
                # Modification des données "EXIF"
                metadata = pyexiv2.ImageMetadata(dest_capture)
                metadata.read()
                try:
                    pyexiv2.xmp.register_namespace('Souche/', 'Souche')
                except:
                    pass
                try: 
                    pyexiv2.xmp.register_namespace('Substrat/', 'Substrat')
                except:
                    pass
                try:
                    pyexiv2.xmp.register_namespace('Fermentation/', 'Fermentation')
                except:
                    pass
                metadata['Xmp.Souche.Souche'] = souche
                metadata['Xmp.Substrat.Substrat'] = substrat
                metadata['Xmp.Fermentation.Fermentation'] = fermentation
                tag = metadata['Xmp.Souche.Souche']
                tag2 = metadata['Xmp.Substrat.Substrat']
                tag3 = metadata['Xmp.Fermentation.Fermentation']
                print 'Souche : ', tag.value
                print 'Substrat : ', tag2.value
                print 'Fermentation : ', tag3.value
                
                
                # On ajoute à la liste des photos prises
                cx.rpush('captures', dest_capture)
                # trim de la liste ???
                
                # on informe qu'une capture vient d'être faite
                cx.publish('capture', dest_capture)
                time.sleep(2)
            if frames_raz == 'yes':
                frames = 0
            capt = "no"                
Пример #25
0
def main():
    print 'capture ...'

    camera = piggyphoto.camera()
    camera.leave_locked()

    cx = redis.Redis()
    
    stop = False
    while not stop:    
        time.sleep(0.)
        print time.time(), 'capture preview ...'
        camera.capture_preview('data/preview.jpg')
        with Image(filename='data/preview.jpg') as img:
            with img.clone() as i:
                i.resize((800), (600))
                i.save(filename='data/preview.jpg')      
        preview = pygame.image.load('data/preview.jpg')
        screen.blit(preview, (0, 0))
        pygame.display.update()
        
        cx.publish('preview', '')
        
        
        evts = pygame.event.get()
        for evt in evts:
            if evt.type == pygame.locals.KEYDOWN:
                if evt.key == 27:
                    print "Fin du programme"
                    stop = True
                elif evt.key == 112: # P
                    pass
                elif evt.key == 99: # C
                    print 'capture image ...'
                    source_capture = 'data/capture.jpg'
                    camera.capture_image(source_capture)
                    
                    # obtenir les infos saisis
                    auteur = cx.get('auteur')
                    souche = cx.get('souche')
                    desc = cx.get('desc')
                    
                    # Modifier les données "EXIF"
                    print "info:", auteur, desc
                    
                    # Déplacer la photo 
                    time_stamp = time.strftime('%Y%m%d%H%M%S', time.localtime())
                    dest_capture = os.path.join('data/images', 'capt%s.jpg' % time_stamp)
                    shutil.move(source_capture, dest_capture)
                    
                    # On ajoute à la liste des photos prises
                    cx.rpush('captures', dest_capture)
                    # trim de la liste ???
                    
                    # on informe qu'une capture vient d'être faite
                    cx.publish('capture', dest_capture)

                elif evt.key == 115: # S
                    print 'demande de stacking rapide ...'
                    cx.publish('stack_rapide', '')

                elif evt.key == 116: # T
                    print 'demande de stacking lent ...'
                    cx.publish('stack_lent', '')
                    
                else:
                    print 'touche inconnue ', evt.key
Пример #26
0
                break
            except IOError: pass
    finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

def runProgram(command):
    print 'RUNNING: ' + command
    os.system(command)

cameras = []
pil = pp.portInfoList()
for name, path in pp.cameraList(autodetect=True).toList():
    pi = pil.get_info(pil.lookup_path(path))
    print "Connecting to camera {} at {}".format(name, path)
    cam = pp.camera(autoInit=False)
    cam.port_info = pi
    cam.init()
    cameras.append(cam)

if len(cameras) != 1:
    print "Required 1 camera. Not enough or too many."
    exit(1)

cam = cameras[0]
#print cam.config.main.capturesettings.shutterspeed2
config = cam.config
config['capturesettings']['shutterspeed2'].value = '1/5'
config['capturesettings']['f-number'].value = 'f/11'
config['capturesettings']['imagequality'].value = 'JPEG Fine'
config['imgsettings']['iso'].value = '100'
Пример #27
0
def main():
    prs = argparse.ArgumentParser()
    prs.add_argument("-p", "--prefix_name", type=str, default='')
    prs.add_argument("-s", "--suffix_index", type=int, default=-1)
    prs.add_argument("-n", "--number_of_data", type=int, default=1)
    '''
    [실행 예]
    python2 collect.py -p block1 -n 20
    => 현재 디렉토리에 "block1_0.jpg" ~ "block1_20.jpg" 사진을 저장함
    '''
    args = prs.parse_args()

    pygame.init()

    prefix = args.prefix_name
    if args.prefix_name == '':
        assert args.suffix_index >= 0

    dir_path = 'dataset'

    n = args.number_of_data
    #screen = pygame.display.set_mode((100, 100))

    # 카메라를 통해 비친 화면을 통해 계속해서 보여줌
    cam = piggyphoto.camera()
    cam.leave_locked()
    cam.capture_preview('preview.jpg')
    picture = pygame.image.load("preview.jpg")
    pygame.display.set_mode(picture.get_size())
    main_surface = pygame.display.get_surface()
    os.remove('preview.jpg')
    if n <= 1:
        file_name = osp.join(dir_path, args.prefix_name)
        while not quit_pressed():
            cam.capture_preview(file_name)
            show(main_surface, file_name)
            #pygame.display.flip()
            #print(file_name)
    else:
        i = 0
        done = False
        # n개의 이미지만큼 촬
        while i < n and not done:
            key_pressed = False
            # "."키가 눌렸으면 저장함
            file_name = osp.join(dir_path,
                                 '{}_{:04d}.jpg'.format(args.prefix_name, i))
            while not (key_pressed):
                cam.capture_preview(file_name)
                show(main_surface, file_name)
                #pygame.display.flip()
                #print(file_name)
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        done = True
                        key_pressed = True
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_q:
                            done = True
                            key_pressed = True
                        if event.key == pygame.K_PERIOD:
                            i += 1
                            key_pressed = True
            if done:
                os.remove(file_name)
parser.add_option("-v", "--verbose", dest="verbose", action='store_true',
                  help="Produce extra status and progress messages")

(options, args) = parser.parse_args()

# Save the motion threshold 
pointerFile = open('/var/www/threshold.txt', 'w')
pointerFile.write(str(options.threshold) + "\n")
pointerFile.close()
threshold = options.threshold

shutdown = False 

# Initialize the DSLR if so asked, otherwise, init the webcam
if options.dslr:
    DSLR = piggyphoto.camera()
    DSLR.capture_preview('stream.jpg')
    imgBase1 = cv.LoadImageM ('stream.jpg')
    shutil.copy("stream.jpg", "/var/www/camimages/base.jpg")
    imgBase = numpy.asarray(imgBase1)
else:
    # Initialize the webcam and take a series of images to stabalize exposure
    cam = ""
    cam = VideoCapture(-1)
    shots = 20
    while shots > 0:
        s, img = cam.read()
        shots += -1
    # Save the last image as the one we use as a baseline to check for motion
    imwrite("/var/www/camimages/base.jpg", img)
    imgBase = img
Пример #29
0
import piggyphoto, pygame
import os
import time


def quit_pressed():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            return True
    return False


def show(file):
    picture = pygame.image.load(file)
    main_surface.blit(picture, (0, 0))
    pygame.display.flip()


C = piggyphoto.camera()
C.leave_locked()
C.capture_preview('preview.jpg')

picture = pygame.image.load("preview.jpg")
pygame.display.set_mode(picture.get_size())
main_surface = pygame.display.get_surface()

while not quit_pressed():
    C.capture_preview('preview.jpg')
    show("preview.jpg")
    def main_loop(self):
        global button_pressed
        self.main_logger.info("Initializing")

        usb_drive_path = "/mnt/usb_drive"
        if (os.path.ismount(usb_drive_path) == False):
            self.main_logger.error("USB Drive not mounted - try mounting")
            os.system("mount /mnt/usb_drive")
            time.sleep(0.5)
            if (os.path.ismount(usb_drive_path) == False):
                self.main_logger.error("Unable to mount USB drive")
                sys.exit(0)
            else:
                self.main_logger.info("Successfully mounted USB Drive")

        self.storage_path = datetime.datetime.now().strftime(
            "/mnt/usb_drive/%I%M%p_%B_%d_%Y")

        image_index = 0

        self.main_logger.info("make directory for photos: %s" %
                              self.storage_path)
        if not os.path.exists(self.storage_path):
            os.makedirs(self.storage_path)

        log_file = "%s/log.txt" % self.storage_path

        root_usage = disk_usage("/")
        self.main_logger.info(root_usage)
        self.main_logger.info("Root Disk Free Space: %d MB" %
                              (int(root_usage.free) / (1024 * 1024)))
        if (root_usage.free < 10 * 1024 * 1024):
            self.main_logger.error("Low Disk Space: %d MB Free" %
                                   (int(usb_usage.free) / (1024 * 1024)))
        usb_usage = disk_usage(usb_drive_path)
        self.main_logger.info(usb_usage)
        self.main_logger.info("USB Disk Free Space: %d MB" %
                              (int(usb_usage.free) / (1024 * 1024)))
        if (usb_usage.free < 10 * 1024 * 1024):
            self.main_logger.error(
                "Low Disk Space: Change USB Drive - %d MB Free" %
                (int(usb_usage.free) / (1024 * 1024)))

        #Button was pressed
        while (True):
            self.lighting.setLightingIdle()
            button_pressed = False
            self.photosRemaining = 3
            self.display_image_files = sorted(os.listdir(self.storage_path),
                                              reverse=True)

            all_files = ''
            for fn in self.display_image_files:
                all_files += " %s/%s" % (self.storage_path, fn)
            if len(self.display_image_files):
                _cmd = "sudo /usr/bin/nice -n 18 fbi -a --noverbose -T 2 -t 5 %s &" % all_files
                print _cmd
                os.system("sudo pkill fbi")
                os.system(_cmd)
            else:
                _cmd = "sudo /usr/bin/nice -n 18 fbi -a --noverbose -T 2 /home/pi/git/raspberrypi_photobooth/logo.jpg"
                print _cmd
                os.system("sudo pkill fbi")
                os.system(_cmd)

            self.display_image_index = 0
            GPIO.setup(self.shutter_switch_pin,
                       GPIO.IN,
                       pull_up_down=GPIO.PUD_UP)
            GPIO.remove_event_detect(self.shutter_switch_pin)
            GPIO.add_event_detect(self.shutter_switch_pin,
                                  GPIO.FALLING,
                                  callback=self.shutter_switch_callback)

            self.main_logger.info("Waiting for button press")
            while not (button_pressed):
                time.sleep(1)
            os.system("sudo pkill fbi")
            _cmd = "sudo /usr/bin/nice -n 18 fbi -a --noverbose -T 2 /home/pi/git/raspberrypi_photobooth/logo.jpg"
            os.system("sudo pkill fbi")
            os.system(_cmd)

            self.main_logger.info("got button press")

            while (self.photosRemaining):
                self.main_logger.info("Countdown")
                #3
                self.lighting.setLightingThree()
                pygame.mixer.music.load("countdown_tick.wav")
                pygame.mixer.music.play()
                time.sleep(1.5)

                #2
                self.lighting.setLightingTwo()
                pygame.mixer.music.load("countdown_tick.wav")
                pygame.mixer.music.play()
                time.sleep(1.5)

                #1
                self.lighting.setLightingOne()
                pygame.mixer.music.load("countdown_tick.wav")
                pygame.mixer.music.play()
                time.sleep(1.5)

                self.lighting.setLightingFlash()
                self.main_logger.info("Take Photo")
                try:
                    if self.cameraError == False:
                        self.camera_logger.info(
                            "capturing %s/%05d.jpg" %
                            (self.storage_path, image_index))
                        self.camera.capture_image(
                            "%s/%04d.jpg" % (self.storage_path, image_index))
                    else:
                        self.camera_logger.error(
                            "Camera Error 1 - can't run capture_image")
                        self.cameraError = True
                        self.lighting.flash_light.brightness = 10
                        self.lighting.setLighting()
                except:
                    self.camera_logger.error(
                        "Camera Error 2 - can't run capture_image")
                    self.cameraError = True
                    self.lighting.flash_light.brightness = 10
                    self.lighting.setLighting()

                image_index += 1

                if self.cameraError == True:
                    self.camera_logger.error("Starting Camera Error Recovery")
                    self.lighting.setLightingError()
                    while self.cameraError == True:
                        self.powerDownCamera()
                        time.sleep(1)
                        self.powerUpCamera()
                        time.sleep(5)
                        os.system(
                            "sudo lsusb | grep Canon | sed 's/Bus\ /sudo\ \/home\/pi\/usbreset\ \/dev\/bus\/usb\//' | sed 's/\ Device\ /\//' | sed 's/:.*//' > /home/pi/resetcmd"
                        )
                        os.system("sh /home/pi/resetcmd")
                        time.sleep(1)
                        try:
                            self.camera = piggyphoto.camera()
                            self.cfile = piggyphoto.cameraFile()
                            self.cameraError = False
                            self.camera_logger.error("Camera Recovered")
                        except:
                            self.camera_logger.error("Camera Recovery Failed")
                            self.cameraError = True

                self.main_logger.info("Photo Complete %d" %
                                      self.photosRemaining)
                print "---- PHOTO COMPLETE ----"
                self.photosRemaining -= 1
                self.lighting.setLightingIdle()
Пример #31
0
 def reset(self):
     if not self._test:
         self.camera = piggyphoto.camera()
         self.camera.leave_locked()
         time.sleep(.5)
Пример #32
0
from pprint import pprint
import piggyphoto as pp
import os
import time

# doesn't work...

C = pp.camera()
C.leave_locked()

#print C.abilities
#C.list_config()

C.config.main.imgsettings.iso.value = 3
print C.config.main.imgsettings.iso

C.config.main.actions.bulb.value = 1
print C.config.main.actions.bulb
time.sleep(1)
print C.config.main.actions.bulb.value
print C.config.main.actions.bulb

#print dir(C.config.main.actions)
#print dir(cfg.main)
#for i in range(10):
#C.capture_preview('preview.jpg')

print "done"

Пример #33
0
    finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)


def runProgram(command):
    print 'RUNNING: ' + command
    os.system(command)


cameras = []
pil = pp.portInfoList()
for name, path in pp.cameraList(autodetect=True).toList():
    pi = pil.get_info(pil.lookup_path(path))
    print "Connecting to camera {} at {}".format(name, path)
    cam = pp.camera(autoInit=False)
    cam.port_info = pi
    cam.init()
    cameras.append(cam)

if len(cameras) != 1:
    print "Required 1 camera. Not enough or too many."
    exit(1)

cam = cameras[0]
#print cam.config.main.capturesettings.shutterspeed2
config = cam.config
config['capturesettings']['shutterspeed2'].value = '1/5'
config['capturesettings']['f-number'].value = 'f/11'
config['capturesettings']['imagequality'].value = 'JPEG Fine'
config['imgsettings']['iso'].value = '100'
class Camera_Driver_Node:
    ##PUBLIC:
    name = ""
    temp_folder = current_folder
    preview_data_name = "preview.jpg"
    image_data_name = "image.jpg"

    ##PRIVATE:
    camera_handler = pphoto.camera(autoInit=False)
    is_init = False
    image_folder = ""
    image_name = ""

    def abilities(self):
        return self.camera_handler.abilities

    def download(self,
                 dst_path=current_folder,
                 src_folder=None,
                 src_name=None):
        src_folder = self.image_folder if src_folder is None else src_folder
        src_name = self.image_name if src_folder is None else src_name

        OUT.INFO(
            self.name, "Downloading images : {} ...".format(
                os.path.join(src_folder, self.src_name)))
        self.camera_handler.download_file(srcfolder, srcfilename, dst_path)

    def preview(self, dst_path=None):
        if not self.is_init:
            self.init()
        path = os.path.join(
            self.temp_folder,
            self.preview_data_name) if dst_path is None else dst_path
        self.camera_handler.capture_preview(path)
        return path

    def capture(self, download_path=None):
        path = download_path
        OUT.INFO(self.name, "Capturing image ...")
        if download_path is None:
            self.image_folder, self.image_name = self.camera_handler.capture_image(
            )
            path = os.path.join(self.image_folder, self.image_name)
        else:
            self.camera_handler.capture_image(destpath=download_path)
        OUT.INFO(self.name,
                 "Capturing image ok ! Saving data in : {}".format(path))

    def exit(self):
        self.camera_handler.exit()

    def init(self):
        if self.is_init:
            OUT.INFO(self.name, "Reinitializing camera handler ...")
            self.camera_handler.reinit()
        else:
            OUT.INFO(self.name, "Initializing camera handler ...")
            self.camera_handler.init()

        self.is_init = self.camera_handler.initialized
        if self.is_init:
            OUT.INFO(self.name, "Initializing camera handler ok !")
            print(self.abilities())
        else:
            OUT.WARN(self.name, "Initializing camera handler fail !")

    def __init__(self, name=None):
        full_path = os.path.realpath(__file__)
        folder, file_name = os.path.split(full_path)
        self.name = file_name if name is None else name
Пример #35
0
 def reset(self):
     self.camera = piggyphoto.camera()
     self.camera.leave_locked()
Пример #36
0
 def __init__(self):
     self.camera = piggyphoto.camera()
     self.reset_settings()
    def __init__(self, config_file):
        self.storage_path = []
        self.display_image_files = []
        self.display_image_index = 0
        main_log_file = datetime.datetime.now().strftime(
            "logs/%I%M%p_%B_%d_%Y.log")
        logging.basicConfig(
            level=logging.DEBUG,
            format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
            datefmt='%m-%d %H:%M',
            filename='logs/photo_booth.log',
            filemode='w')

        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        # set a format which is simpler for console use
        formatter = logging.Formatter(
            '%(name)-12s: %(levelname)-8s %(message)s')
        # tell the handler to use this format
        console.setFormatter(formatter)
        # add the handler to the root logger
        logging.getLogger('').addHandler(console)

        self.main_logger = logging.getLogger("Main")
        self.maintenance_logger = logging.getLogger("Maintenance")
        self.lighting_logger = logging.getLogger("Lighting")
        self.camera_logger = logging.getLogger("Camera")
        self.lighting_logger.info("Setup Lighting")
        self.pwm = PWM(0x40, debug=True)
        self.pwm.setPWMFreq(1000)  # Set frequency to 60 Hz
        self.lighting_config = LightingConfig()
        self.parseConfigFile(config_file)
        self.lighting = Lighting(self.lighting_config, self.pwm)
        self.lighting_logger.debug(self.lighting)
        self.lighting_logger.info("Setup Lighting - OK")
        GPIO.setmode(GPIO.BOARD)
        pygame.mixer.init()
        self.lighting_logger.info("Setup Lighting - OK")
        self.camera_logger.info("Setup Camera")
        self.cameraError = True
        while self.cameraError == True:
            self.powerDownCamera()
            time.sleep(1)
            self.powerUpCamera()
            time.sleep(5)
            os.system(
                "sudo lsusb | grep Canon | sed 's/Bus\ /sudo\ \/home\/pi\/usbreset\ \/dev\/bus\/usb\//' | sed 's/\ Device\ /\//' | sed 's/:.*//' > /home/pi/resetcmd"
            )
            os.system("sh /home/pi/resetcmd")
            time.sleep(1)
            try:
                self.camera = piggyphoto.camera()
                self.cfile = piggyphoto.cameraFile()
                self.cameraError = False
                self.camera_logger.info("Setup Camera - OK")
            except:
                self.camera_logger.error("Setup Camera - Error")
                self.cameraError = True

        self.photosRemaining = 3
        self.main_logger.info("Setup Button Input")
        self.verbose = False
        GPIO.setup(self.shutter_switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.add_event_detect(self.shutter_switch_pin,
                              GPIO.FALLING,
                              callback=self.shutter_switch_callback)
        self.main_logger.info("Setup Button Input - OK")
        self.main_logger.info("Setup Video Display")
        #        pygame.mixer.music.set_volume(1)
        #        pygame.mixer.music.load("startup.wav")
        #        pygame.mixer.music.play()
        #        pygame.init()
        #        self.screen = pygame.display.set_mode((0, 0))
        #        self.clock = pygame.time.Clock()
        self.main_logger.info("Setup Video Display - OK")
Пример #38
0
def MOTION(PIR_PIN):
	epoch_timestamp = str(int(time.time()))
	C = piggyphoto.camera()
	C.capture_image('photos/' + epoch_timestamp + '.jpg')
	print "Motion Detected!"
Пример #39
0
    def __init__(self, host="localhost", port=8010, nowindow=False):
        self.nowindow = nowindow
        self.host = host
        self.port = port
        self.settings = DotMap(pyStandardSettings.getSettings())
        self.snap_path = str(self.settings.folder.output)
        self.stream_path = str(self.settings.folder.stream)
        self.isStreaming = self.settings.streamAtStartup

        # osc
        self.oscServer = OSCServer((host, int(port)))
        self.oscServer.addDefaultHandlers()
        self.oscServer.addMsgHandler("/pyying/stream", self.stream_handler)
        self.oscServer.addMsgHandler("/pyying/shoot", self.shoot_handler)
        self.oscThread = Thread(target=self.oscServer.serve_forever)
        self.oscThread.start()
        print("Starting OSCServer. Use ctrl-C to quit.")

        # static file server
        self.staticFileServerThread = Thread(target=self.startStaticFileServer)
        self.staticFileServerThread.start()

        # TERM
        signal.signal(signal.SIGTERM, self.sigclose)


        try:
          # MAC Address
          try:
            self.macAddress = netifaces.ifaddresses('eth0')[netifaces.AF_LINK][0]['addr']
          except ValueError as e:
            print(e)
          print('mac address: ' + self.macAddress)

          # check folders exist
          if not os.path.exists(self.stream_path):
                os.makedirs(self.stream_path)
          if not os.path.exists(self.snap_path):
                os.makedirs(self.snap_path)
          self.find_last_number_in_directory()

          # camera
          self.camera = piggyphoto.camera(False)
          if settings.camera.port:
              settings.camera.port = str(settings.camera.port)
          elif settings.camera.devpath:
              try:
                  import pyudev
                  context = pyudev.Context()
                  device = pyudev.Devices.from_path(context, str(settings.camera.devpath))
                  settings.camera.port = 'usb:{0},{1}'.format(device['BUSNUM'], device['DEVNUM'])
              except pyudev.device._errors.DeviceNotFoundAtPathError as e:
                  print('devpath not found', settings.camera.devpath)
                  self.close()
                  return
          print 'init camera'
          self.camera.init(settings.camera.port)
          self.camera.leave_locked()
          fullpath = self.getStreamPath()
          self.camera.capture_image(fullpath, delete=True)
          
          # spacebro
          if settings.service.spacebro.enabled:
              self.spacebroThread = Thread(target=self.startSpacebroClient)
              self.spacebroThread.start()
              # self.sendStatus()

          # lightningbro
          if settings.service.lightningbro.enabled:
              self.lightningbroThread = Thread(target=self.startLightningbroClient)
              self.lightningbroThread.start()

          # create window from first preview
          if (not self.nowindow):
            picture = pygame.image.load(fullpath)
            pygame.display.set_mode(picture.get_size())
            self.main_surface = pygame.display.get_surface()
        except KeyboardInterrupt:
          self.close()
        except Exception as e:
          print(str(e))
          self.close()
Пример #40
0
import piggyphoto, pygame
import os
import time

def quit_pressed():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            return True
    return False

def show(file):
    picture = pygame.image.load(file)
    main_surface.blit(picture, (0, 0))
    pygame.display.flip()

C = piggyphoto.camera()
C.leave_locked()
C.capture_preview('preview.jpg')

picture = pygame.image.load("preview.jpg")
pygame.display.set_mode(picture.get_size())
main_surface = pygame.display.get_surface()

while not quit_pressed():
        C.capture_preview('preview.jpg')
        show("preview.jpg")

Пример #41
0
 def reset(self):
     if not self._test:
         self.camera = piggyphoto.camera()
         self.camera.leave_locked()
         time.sleep(.5)
Пример #42
0
class Camera_Driver:
    ##PUBLIC:
    node_name = "Camera_Controler"
    topic_image_pub = node_name + "/image_pub"
    topic_control_data_sub = node_name + "/control_data_sub"
    temp_folder = os.path.join(current_folder, "DCIM")
    preview_data_name = "preview.jpg"
    image_data_name = "image"
    image_data_idx = 1
    image_data_name_postifx = ".jpg"
    time_shoot_pic = 3

    flag_window = False

    ##PRIVATE:
    camera_handler = pphoto.camera(autoInit=False)
    is_init = False
    is_capture = False
    image = None
    control_data = ""
    image_folder = ""
    image_name = ""

    queue_size = 4
    bridge = CvBridge()
    image_pub_ = None
    control_data_sub_ = None

    def run(self):
        if not self.is_capture:
            self.preview()
            self.image_publish()

    def abilities(self):
        return self.camera_handler.abilities

    def download(self,
                 dst_path=current_folder,
                 src_folder=None,
                 src_name=None):
        src_folder = self.image_folder if src_folder is None else src_folder
        src_name = self.image_name if src_folder is None else src_name

        OUT.INFO(
            self.node_name, "Downloading images : {} ...".format(
                os.path.join(src_folder, self.src_name)))
        self.camera_handler.download_file(srcfolder, srcfilename, dst_path)

    def preview(self, dst_path=None):
        if not self.is_init:
            self.init()
        path = os.path.join(
            self.temp_folder,
            self.preview_data_name) if dst_path is None else dst_path
        self.camera_handler.capture_preview(path)
        self.image = cv2.imread(path, cv2.IMREAD_COLOR)
        return path

    def capture(self, download_path=None):
        path = os.path.join(
            self.temp_folder,
            "{}_{}{}".format(self.image_data_name, self.image_data_idx,
                             self.image_data_name_postifx)
        ) if download_path is None else download_path
        OUT.INFO(self.node_name, "Capturing image ...")
        if download_path is None:
            '''
            self.image_folder, self.image_name = self.camera_handler.capture_image()
            path = os.path.join(self.image_folder, self.image_name)
            '''
            self.camera_handler.capture_image(destpath=path)
        else:
            self.camera_handler.capture_image(destpath=path)
        OUT.INFO(self.node_name,
                 "Capturing image ok ! Saving data in : {}".format(path))
        self.image_data_idx += 1

    def exit(self):
        self.camera_handler.exit()

    def image_publish(self):
        self.image_pub_.publish(self.bridge.cv2_to_imgmsg(self.image, "bgr8"))
        if self.flag_window:
            cv2.imshow(self.node_name, self.image)
            cv2.waitKey(1)

    def control_data_callback(self, msg):
        self.control_data = msg.data

        if self.control_data == "preview":
            self.preview()
            self.image_publish()
        if self.control_data == "capture":
            if self.is_capture:
                return
            self.is_capture = True
            self.capture()
            time.sleep(self.time_shoot_pic)
            self.is_capture = False

    def pub_init(self):
        OUT.INFO(self.node_name,
                 "Publisher {} initiating !".format(self.topic_image_pub))
        self.image_pub_ = rospy.Publisher(self.topic_image_pub,
                                          Image,
                                          queue_size=self.queue_size)

    def sub_init(self):
        OUT.INFO(
            self.node_name,
            "Subscriber {} initiating !".format(self.topic_control_data_sub))
        self.control_data_sub = rospy.Subscriber(self.topic_control_data_sub,
                                                 String,
                                                 self.control_data_callback)

    def init(self):
        if not os.path.exists(self.temp_folder):
            os.makedirs(self.temp_folder)
        if self.is_init:
            OUT.INFO(self.node_name, "Reinitializing camera handler ...")
            self.camera_handler.reinit()
        else:
            OUT.INFO(self.node_name, "Initializing camera handler ...")
            self.camera_handler.init()

        self.is_init = self.camera_handler.initialized
        if self.is_init:
            OUT.INFO(self.node_name, "Initializing camera handler ok !")
            print(self.abilities())
        else:
            OUT.WARN(self.node_name, "Initializing camera handler fail !")

    def __init__(self, name=None):
        self.node_name = self.node_name if name is None else name
        self.pub_init()
        self.sub_init()
        self.init()
Пример #43
0
 def capture_preview(self):
     if not self.camera:
         self.camera = piggyphoto.camera()
         logger.debug("Created new camera")
     return pygame.image.load(
         StringIO.StringIO(self.camera.capture_preview().get_data()))