コード例 #1
0
def trigger_capture(camera, context, dstpath='image.jpg'):
	""" Trigger capture must be used instead of capture if you want to shoot while the mirror is locked up
	and you do not want to re-focus - set capture format on camera"""
        timeout = 20
        starttime = time.time()

        gp.check_result(gp.gp_camera_trigger_capture(camera, context))
        filefound = [False, False]

        while filefound[1] != gp.GP_EVENT_FILE_ADDED:
                filefound = gp.gp_camera_wait_for_event(camera, 10000, context)
                if time.time() - starttime > timeout:
                        print ('operation timed out')
                        return False
	
	campath = '/'
        filelist = list_files(camera, context, campath)

        for f in filelist:
                filename = f.strip(campath)
                camfile = gp.check_result(gp.gp_file_new())
                gp.gp_camera_file_get(camera, campath, filename, gp.GP_FILE_TYPE_NORMAL, camfile, context)
                gp.gp_file_save(camfile, dstpath)
                gp.gp_file_unref(camfile)
                gp.gp_camera_file_delete(camera, campath, filename, context)
                
        endtime = round(time.time() - starttime, 2)
        print ('capture complete in {}s'.format(endtime))	        
コード例 #2
0
def one_photo(camera, context, value, filename):
    # get configuration tree
    config = gp.check_result(gp.gp_camera_get_config(camera, context))
    # find the capture target config item
    shutterspeed = gp.check_result(
        gp.gp_widget_get_child_by_name(config, 'shutterspeed'))
    # check value in range
    count = gp.check_result(gp.gp_widget_count_choices(shutterspeed))
    if value < 0 or value >= count:
        print('Parameter out of range')
        return 1
    # set value
    speedvalue = gp.check_result(gp.gp_widget_get_choice(shutterspeed, value))

    gp.check_result(gp.gp_widget_set_value(shutterspeed, speedvalue)) # set config gp.check_result(gp.gp_camera_set_config(camera, config, context))
    print('Capturing image (shutterspeed=%d)' % value)
    file_path = gp.check_result(gp.gp_camera_capture(
        camera, gp.GP_CAPTURE_IMAGE, context))

    target = filename+".jpg"

    camera_file = gp.check_result(gp.gp_camera_file_get(
            camera, file_path.folder, file_path.name,
            gp.GP_FILE_TYPE_NORMAL, context))
    gp.check_result(gp.gp_file_save(camera_file, target))
コード例 #3
0
def main():
    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    callback_obj = gp.check_result(gp.use_python_logging())
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    print('Getting list of files')
    files = list_files(camera)
    if not files:
        print('No files found')
        return 1
    path = files[0]
    print('Copying %s to memory' % path)
    folder, name = os.path.split(path)
    camera_file = gp.check_result(gp.gp_camera_file_get(
        camera, folder, name, gp.GP_FILE_TYPE_NORMAL))
##    # read file data using 'slurp' and a buffer allocated in Python
##    info = gp.check_result(
##        gp.gp_camera_file_get_info(camera, folder, name))
##    file_data = bytearray(info.file.size)
##    count = gp.check_result(gp.gp_file_slurp(camera_file, file_data))
##    print(count, 'bytes read')
    # or read data using 'get_data_and_size' which allocates its own buffer
    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    data = memoryview(file_data)
    print(type(data), len(data))
    print(data[:10].tolist())
    image = Image.open(io.BytesIO(file_data))
    image.show()
    print('After deleting camera_file and file_data')
    del camera_file, file_data
    print(type(data), len(data))
    print(data[:10].tolist())
    gp.check_result(gp.gp_camera_exit(camera))
    return 0
コード例 #4
0
    def capture_image(self, method):
        """
        Capture image
        :param method:
        :return:
        """

        try:
            file_path = gp.check_result(gp.gp_camera_capture(self.camera, gp.GP_CAPTURE_IMAGE, self.context))
            if method == 'single':
                path = self.path_single

            elif method == 'hdr3':
                path = self.path_hdr3

            elif method == 'hdr5':
                path = self.path_hdr5

            target = os.path.join(path, file_path.name)
            camera_file = gp.check_result(gp.gp_camera_file_get(self.camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL, self.context))
            gp.check_result(gp.gp_file_save(camera_file, target))
            # Count shutter count from image
            count = self.get_image_shutter(path + file_path.name)
            update_camera(str(count))

        except Exception as e:
            logger.error(e.message)
コード例 #5
0
def main():
    logging.basicConfig(format="%(levelname)s: %(name)s: %(message)s", level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    camera = gp.check_result(gp.gp_camera_new())
    context = gp.gp_context_new()
    gp.check_result(gp.gp_camera_init(camera, context))
    print("Getting list of files")
    files = list_files(camera, context)
    if not files:
        print("No files found")
        return 1
    path = files[0]
    print("Copying %s to memory" % path)
    folder, name = os.path.split(path)
    camera_file = gp.check_result(gp.gp_camera_file_get(camera, folder, name, gp.GP_FILE_TYPE_NORMAL, context))
    # read file data using 'slurp' and a buffer allocated in Python
    info = gp.check_result(gp.gp_camera_file_get_info(camera, folder, name, context))
    file_data = bytearray(info.file.size)
    count = gp.check_result(gp.gp_file_slurp(camera_file, file_data))
    print(count, "bytes read")
    # or read data using 'get_data_and_size' which allocates its own buffer
    ##    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    data = memoryview(file_data)
    print(type(data), len(data))
    print(data[:10].tolist())
    image = Image.open(io.BytesIO(file_data))
    image.show()
    print("After deleting camera_file and file_data")
    del camera_file, file_data
    print(type(data), len(data))
    print(data[:10].tolist())
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
コード例 #6
0
ファイル: copy-files.py プロジェクト: mdifonzo/python-gphoto2
def main():
    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    computer_files = list_computer_files()
    camera = gp.check_result(gp.gp_camera_new())
    context = gp.gp_context_new()
    gp.check_result(gp.gp_camera_init(camera, context))
    print('Getting list of files from camera...')
    camera_files = list_camera_files(camera, context)
    if not camera_files:
        print('No files found')
        return 1
    print('Copying files...')
    for path in camera_files:
        info = get_camera_file_info(camera, context, path)
        timestamp = datetime.fromtimestamp(info.file.mtime)
        folder, name = os.path.split(path)
        dest_dir = get_target_dir(timestamp)
        dest = os.path.join(dest_dir, name)
        if dest in computer_files:
            continue
        print('%s -> %s' % (path, dest_dir))
        if not os.path.isdir(dest_dir):
            os.makedirs(dest_dir)
        camera_file = gp.check_result(gp.gp_file_new())
        gp.check_result(gp.gp_camera_file_get(
            camera, folder, name, gp.GP_FILE_TYPE_NORMAL, camera_file, context))
        gp.check_result(gp.gp_file_save(camera_file, dest))
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
コード例 #7
0
def capture(camera, context, dstpath='image.jpg'):
        """ Capture an image - verify file capture format on camera before setting dstpath """
        camfile = gp.check_result(gp.gp_file_new())
        campath = gp.CameraFilePath()
        
        starttime = time.time()

        gp.check_result(gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE, campath, context))
        
        gp.gp_camera_file_get(camera, campath.folder, campath.name, gp.GP_FILE_TYPE_NORMAL, camfile, context)
        gp.gp_file_save(camfile, dstpath)
        gp.gp_file_unref(camfile)
        gp.check_result(gp.gp_camera_file_delete(camera, campath.folder, campath.name, context))

        endtime = round(time.time() - starttime, 2)
        print ('capture complete in {}s'.format(endtime))	        
コード例 #8
0
ファイル: camera.py プロジェクト: Tetrabude/photobooth
    def takePhoto(self):

        context = gp.gp_context_new()
        camera = gp.check_result(gp.gp_camera_new())
        gp.check_result(gp.gp_camera_init(camera, context))

        print("Capturing image")

        file_path = gp.check_result(gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE, context))

        print("Camera file path: {0}/{1}".format(file_path.folder, file_path.name))

        target = os.path.join("/tmp", file_path.name)

        print("Copying image to", target)

        camera_file = gp.check_result(
            gp.gp_camera_file_get(camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL, context)
        )

        gp.check_result(gp.gp_file_save(camera_file, target))

        gp.check_result(gp.gp_camera_exit(camera, context))

        return target
コード例 #9
0
ファイル: copy-data.py プロジェクト: Postcard/python-gphoto2
def main():
    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    camera = gp.check_result(gp.gp_camera_new())
    context = gp.gp_context_new()
    gp.check_result(gp.gp_camera_init(camera, context))
    print('Getting list of files')
    files = list_files(camera, context)
    if not files:
        print('No files found')
        return 1
    path = files[0]
    print('Copying %s to memory' % path)
    folder, name = os.path.split(path)
    camera_file = gp.check_result(gp.gp_camera_file_get(
        camera, folder, name, gp.GP_FILE_TYPE_NORMAL, context))
    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    data = memoryview(file_data)
    print(type(data), len(data))
    print(data[:10].tolist())
    image = Image.open(io.BytesIO(file_data))
    image.show()
    print('After deleting camera_file and file_data')
    del camera_file, file_data
    print(type(data), len(data))
    print(data[:10].tolist())
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
コード例 #10
0
ファイル: gphoto2_camera.py プロジェクト: bitcraft/tailor
        def capture():
            path = gp.check_result(gp.gp_camera_capture(self._camera, gp.GP_CAPTURE_IMAGE, self._context))

            file = gp.check_result(gp.gp_camera_file_get(
                self._camera, path.folder, path.name,
                gp.GP_FILE_TYPE_NORMAL, self._context))

            data = gp.check_result(gp.gp_file_get_data_and_size(file))
            return bytes(data)
コード例 #11
0
ファイル: camera.py プロジェクト: jossef/selfie
 def _capture_attempt(self, output_directory):
     file_path = gp.check_result(gp.gp_camera_capture(self._camera, gp.GP_CAPTURE_IMAGE, self._context))
     logging.debug('camera file path: {0}{1}'.format(file_path.folder, file_path.name))
     destination_file_name = datetime.now().strftime('%d-%H-%M-%S.jpg')
     destination_file_path = os.path.join(output_directory, destination_file_name)
     logging.debug('downloading image to {0}'.format(destination_file_path))
     camera_file = gp.check_result(gp.gp_camera_file_get(self._camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL, self._context))
     gp.check_result(gp.gp_file_save(camera_file, destination_file_path))
     return destination_file_path
コード例 #12
0
ファイル: __init__.py プロジェクト: jdemaeyer/ice
 def get_filepath(self, camerafilepath):
     self.log("Downloading")
     camerafile = gp.CameraFile()
     camerafile = gp.check_result(gp.gp_camera_file_get(
             self.camera,
             camerafilepath.folder,
             camerafilepath.name,
             gp.GP_FILE_TYPE_NORMAL,
             self.context))
     return camerafile
コード例 #13
0
ファイル: camera.py プロジェクト: vishnubob/obscura
 def copy_file(self, file_path, prefix="", stubfn=""):
     (camera, context) = self.camera
     target_fn = file_path.name
     target_fn = os.path.splitext(target_fn)
     target_fn = target_fn[0] + stubfn + target_fn[1]
     target_fn = os.path.join(prefix, target_fn)
     print('Copying image to %s' % target_fn)
     res = gp.gp_camera_file_get(camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL, context)
     camera_file = gp.check_result(res)
     res = gp.gp_file_save(camera_file, target_fn)
     gp.check_result(res)
     self.last_image = target_fn
     return target_fn
コード例 #14
0
ファイル: DSLR_Example.py プロジェクト: kscottz/pycaribbean
def capture_image(camera, context, name):
    """
    Use gphoto to capture an image and retrieve it.
    Place the file in /tmp/name
    """
    file_path = gp.check_result(gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE, context))
    target = os.path.join("/tmp", name)
    print "Copying image to {0}".format(target)
    camera_file = gp.check_result(
        gp.gp_camera_file_get(camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL, context)
    )
    gp.check_result(gp.gp_file_save(camera_file, target))
    gp.check_result(gp.gp_camera_exit(camera, context))
コード例 #15
0
ファイル: dias.py プロジェクト: NoUsername/DiaCapture
def copyFromCam(toFolder, file_path):
	global context, camera
	file_name = file_path.name
	target = os.path.join(toFolder, file_name)
	if not isJpg(file_name):
		print("encountered RAW file, putting in 'raw' subdir")
		target = os.path.join(toFolder, "raw", file_name)
		mkdirP(os.path.join(toFolder, "raw"))
	print('Copying image to', target)
	camera_file = gp.check_result(gp.gp_camera_file_get(
			camera, file_path.folder, file_name,
			gp.GP_FILE_TYPE_NORMAL, context))
	gp.check_result(gp.gp_file_save(camera_file, target))
コード例 #16
0
ファイル: camera.py プロジェクト: vishnubob/obscura
 def download_all_files_on_camera(self, prefix='', stubfn=''):
     pics = self.get_files_on_camera()
     (camera, context) = self.camera
     files = []
     for (path, fn) in pics:
         if fn.lower().endswith("cr2"):
             _type = gp.GP_FILE_TYPE_RAW
         else:
             _type = gp.GP_FILE_TYPE_NORMAL
         target_fn = os.path.splitext(fn)
         target_fn = target_fn[0] + stubfn + target_fn[1]
         target_fn = os.path.join(prefix, target_fn)
         camera_file = gp.check_result(gp.gp_camera_file_get(camera, path, fn, _type, context))
         gp.check_result(gp.gp_file_save(camera_file, target_fn))
コード例 #17
0
ファイル: camera.py プロジェクト: Karijini/photobooth
 def __take_pic(self):
     print 'camera.__take_pic'
     target = './data/preview.jpg'
     if not self.use_real_camera:
         pass
         #self.pic_taken.emit('test.jpg')
     else:
         self.__apply_settings(self.__capture_settings)
         file_path = gp.check_result(gp.gp_camera_capture(self.__camera, gp.GP_CAPTURE_IMAGE, self.__context))
         camera_file = gp.check_result(gp.gp_camera_file_get(
             self.__camera, file_path.folder, file_path.name,
             gp.GP_FILE_TYPE_NORMAL, self.__context))
         print camera_file
         gp.check_result(gp.gp_file_save(camera_file, target))
     self.pic_taken.emit(target)
コード例 #18
0
 def take_picture_thread(self, stop):
    self.go_button.setEnabled(False)
    self.stop_button.setEnabled(True)
    if self.get_parameter('shutterspeed')[1] != 'bulb':
         self.text_line.setText('Capturing...')
         error, self.file_path = gphoto2.gp_camera_capture(self.camera, gphoto2.GP_CAPTURE_IMAGE, self.context)
         camera_file = gphoto2.check_result(gphoto2.gp_camera_file_get(self.camera, self.file_path.folder, self.file_path.name, gphoto2.GP_FILE_TYPE_NORMAL, self.context))
         error = gphoto2.gp_file_save(camera_file, self.file_path.name)
         img_num = 1
         while os.path.isfile(self.current_picture):
             self.current_picture = 'IMG_'+str(img_num).zfill(4)+'.CR2'
             img_num = img_num + 1
         if hasattr(self, 'file_path'):
             os.rename(self.file_path.name, self.current_picture)
         raw = rawpy.imread(self.current_picture)
         image = raw.postprocess(user_flip=False, output_bps=8)
         image = cv2.resize(image,(768, 512))
         self.myImage = QtGui.QImage(image.astype(numpy.uint8), 768, 512, QtGui.QImage.Format_RGB888)
         self.text_line.setText('Done')
         self.image_event = 1
         self.update()
    else:
        secs = int(self.bulb_time.text())
        i = 0
        while i < int(self.bulb_pics.text()) and not stop.isSet():
           self.file_path = self.get_bulb_picture(secs, stop)
           img_num = 1
           while os.path.isfile(self.current_picture):
               self.current_picture = 'IMG_'+str(img_num).zfill(4)+'.CR2'
               img_num = img_num + 1
           if hasattr(self, 'file_path'):
               os.rename(self.file_path.name, self.current_picture)
           raw = rawpy.imread(self.current_picture)
           image = raw.postprocess(user_flip=False, output_bps=8)
           image = cv2.resize(image,(768, 512))
           self.myImage = QtGui.QImage(image.astype(numpy.uint8), 768, 512, QtGui.QImage.Format_RGB888)
           self.text_line.setText('Image '+str(i+1)+" of "+self.bulb_pics.text()+' done')
           self.image_event = 1
           self.update()
           i = i + 1
        if stop.isSet():
           self.text_line.setText('Interruped by user!')
        stop.clear()
    if hasattr(self, 'file_path'):
        self.solve_button.setEnabled(True)
        self.solve_scale.setEnabled(True)
    self.go_button.setEnabled(True)
    self.stop_button.setEnabled(False)
コード例 #19
0
ファイル: bccpsa.py プロジェクト: meistermuka/bccpsa
def _capture_image(camera, context, settings):
    print "Capturing Image"
    if settings:
        set_iso(str(ISO_CONSTANTS[settings['iso']]), camera, context)
        set_aperture(APERTURE_CONSTANTS[settings['f-number']], camera, context)
        set_shutterspeed(SHUTTER_SPEED_CONSTANTS[settings["shutterspeed2"]], camera, context)
    # Image being captured and stored on camera
    image_path = gp.check_result(gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE, context))
    # Grabbing timestamp for unique file name
    timestamp = int(time.time())
    extension = image_path.name.split('.')[1]
    image_name = "TST_{}.".format(timestamp) + extension
    target_path = os.path.join(os.getcwd()+'/images', image_name)
    # "Grunt" work to move the file off camera
    image_file = gp.check_result(gp.gp_camera_file_get(camera, image_path.folder, image_path.name, gp.GP_FILE_TYPE_NORMAL, context))
    gp.check_result(gp.gp_file_save(image_file, target_path))
コード例 #20
0
def capture(downloadPath, resultFile, showImage):
    context = gp.gp_context_new()
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera, context))
    print('Capturing image')
    file_path = gp.check_result(gp.gp_camera_capture(
        camera, gp.GP_CAPTURE_IMAGE, context))
    print('Camera file path: {0}/{1}'.format(file_path.folder, file_path.name))
    target = downloadPath+"/"+resultFile
    print('Copying image to', target)
    camera_file = gp.check_result(gp.gp_camera_file_get(            
        camera, file_path.folder, file_path.name,
        gp.GP_FILE_TYPE_NORMAL, context))
    gp.check_result(gp.gp_file_save(camera_file, target))
    if (showImage):
        subprocess.call(['xdg-open', target])
    gp.check_result(gp.gp_camera_exit(camera, context))
    return True
コード例 #21
0
def main():
    # Init camera
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    timeout = 3000 # miliseconds
    while True:
        event_type, event_data = gp.check_result(
            gp.gp_camera_wait_for_event(camera, timeout))
        if event_type == gp.GP_EVENT_FILE_ADDED:
            # Get the image from the camera
            camera_file = gp.check_result(gp.gp_camera_file_get(
                camera, event_data.folder, event_data.name,
                gp.GP_FILE_TYPE_NORMAL))
            # Path where the image is to be saved
            target_path= os.path.join(os.getcwd(), event_data.name)
            print("Picture is saved to {}".format(target_path))
            gp.check_result(gp.gp_file_save(camera_file, target_path))
    return 0
コード例 #22
0
def main():
    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    callback_obj = gp.check_result(gp.use_python_logging())
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    print('Capturing image')
    file_path = gp.check_result(gp.gp_camera_capture(
        camera, gp.GP_CAPTURE_IMAGE))
    print('Camera file path: {0}/{1}'.format(file_path.folder, file_path.name))
    target = os.path.join('/tmp', file_path.name)
    print('Copying image to', target)
    camera_file = gp.check_result(gp.gp_camera_file_get(
            camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL))
    gp.check_result(gp.gp_file_save(camera_file, target))
    subprocess.call(['xdg-open', target])
    gp.check_result(gp.gp_camera_exit(camera))
    return 0
コード例 #23
0
ファイル: zerobox.py プロジェクト: volzotan/timebox
    def capture_and_download(self, filename):

        self.state = self.STATE_BUSY
        
        try:
            error, file_path = gp.gp_camera_capture(self.camera, gp.GP_CAPTURE_IMAGE)
            gp.check_result(error)

            # print('Camera file path: {0}/{1}'.format(file_path.folder, file_path.name))

            error, camera_file = gp.gp_camera_file_get(self.camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL)
            gp.check_result(error)

            error = gp.gp_file_save(camera_file, os.path.join(*filename))
            gp.check_result(error)
        except Exception as e:
            raise e
        finally:
            self.state = self.STATE_CONNECTED
コード例 #24
0
 def get_bulb_picture(self, secs, stop):
     self.set_parameter('bulb', 1)
     i = 0
     while i < secs and not stop.isSet():
         time.sleep(1)
         self.text_line.setText('Elapsed '+str(i+1)+' of '+str(secs)+' secs')
         i = i + 1
     self.set_parameter('bulb', 0)
     self.text_line.setText('Saving image...')
     time.sleep(2)
     status = 0
     i = 0
     while status != 2:
         error, status, self.file_path = gphoto2.gp_camera_wait_for_event(self.camera, i, self.context)
         i = i + 1
     camera_file = gphoto2.check_result(gphoto2.gp_camera_file_get(self.camera, self.file_path.folder, self.file_path.name, gphoto2.GP_FILE_TYPE_NORMAL, self.context))
     error = gphoto2.gp_file_save(camera_file, self.file_path.name)
     self.text_line.setText('Done')
     return self.file_path
コード例 #25
0
ファイル: photo.py プロジェクト: theletterd/remote_cam_pics
def take_photo():
    context = gp.Context()
    camera = gp.Camera()
    camera.init(context)

    file_path = gp.check_result(
        gp.gp_camera_capture(
            camera,
            gp.GP_CAPTURE_IMAGE,
            context
        )
    )

    # TODO - label the photos by date - YYYY-MM-DD-HH-MM-SS or something.
    datestr = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f ')
    target = os.path.join(settings.originals_dir, datestr + file_path.name)
    camera_file = gp.check_result(
        gp.gp_camera_file_get(
            camera,
            file_path.folder,
            file_path.name,
            gp.GP_FILE_TYPE_NORMAL, context
        )
    )
    gp.check_result(
        gp.gp_file_save(
            camera_file,
            target
        )
    )
    gp.check_result(
        gp.gp_camera_file_delete(
            camera,
            file_path.folder,
            file_path.name,
            context
        )
    )
    gp.gp_camera_exit(camera, context)

    return target
コード例 #26
0
def main():
    logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                        level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))

    configStartTime = time.time() * 1000
    # get configuration tree
    config = gp.check_result(gp.gp_camera_get_config(camera))
    # find the capture target config item
    capture_target = gp.check_result(
        gp.gp_widget_get_child_by_name(config, 'capturetarget'))

    value = gp.check_result(gp.gp_widget_get_choice(capture_target, 1))
    gp.check_result(gp.gp_widget_set_value(capture_target, value))
    # set config
    gp.check_result(gp.gp_camera_set_config(camera, config))
    endConfig = time.time() * 1000

    #print('Capturing image')
    imgTimeStart = time.time() * 1000
    file_path = gp.check_result(
        gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE))
    #print('Camera file path: {0}/{1}'.format(file_path.folder, file_path.name))
    target = os.path.join('RAW/', file_path.name)
    endImgCap = time.time() * 1000
    #print('Copying image to', target)
    saveImgStart = time.time() * 1000
    camera_file = gp.check_result(
        gp.gp_camera_file_get(camera, file_path.folder, file_path.name,
                              gp.GP_FILE_TYPE_RAW))
    gp.check_result(gp.gp_file_save(camera_file, target))
    saveImgEnd = time.time() * 1000
    subprocess.call(['xdg-open', target])
    gp.check_result(gp.gp_camera_exit(camera))
    #print("Config Time: %f" % (endConfig - configStartTime))
    #print("Img Capture Time: %f" % (endImgCap - imgTimeStart))
    #print("Img Save Time: %f" % (saveImgEnd - saveImgStart))
    return 0
コード例 #27
0
    def _get_picture(self):

        print('get picture')
        camera = gp.check_result(gp.gp_camera_new())
        gp.check_result(gp.gp_camera_init(camera))

        print('Capturing image')
        file_path = gp.check_result(
            gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE))

        print('Camera file path: {0}/{1}'.format(file_path.folder,
                                                 file_path.name))
        target = os.path.join(self._dir, file_path.name)
        self.pictures.append(target)

        print('Copying image to', target)
        camera_file = gp.check_result(
            gp.gp_camera_file_get(camera, file_path.folder, file_path.name,
                                  gp.GP_FILE_TYPE_NORMAL))

        gp.check_result(gp.gp_file_save(camera_file, target))
        gp.check_result(gp.gp_camera_exit(camera))
コード例 #28
0
ファイル: camera.py プロジェクト: nicog2/pibooth
    def _post_process_capture(self, capture_path):
        gp_path, effect = self._captures[capture_path]
        camera_file = gp.check_result(
            gp.gp_camera_file_get(self._gp_cam, gp_path.folder, gp_path.name,
                                  gp.GP_FILE_TYPE_NORMAL))

        image = Image.open(
            io.BytesIO(memoryview(camera_file.get_data_and_size())))
        image = image.resize(
            sizing.new_size_keep_aspect_ratio(image.size, self._cam.resolution,
                                              'outer'), Image.ANTIALIAS)
        image = image.crop(
            sizing.new_size_by_croping(image.size, self._cam.resolution))

        if self._cam.hflip:
            image = image.transpose(Image.FLIP_LEFT_RIGHT)

        if effect != 'none':
            image = image.filter(getattr(ImageFilter, effect.upper()))

        image.save(capture_path)
        return image
コード例 #29
0
    def rgb_camera_capture_function(self):
        try:
            time_now = datetime.datetime.now()
            print('Capturing image')
            file_path = gp.check_result(
                gp.gp_camera_capture(self.rgb_camera, gp.GP_CAPTURE_IMAGE))
            filename = 'image_{0}.jpg'.format(
                time_now.strftime("%Y-%m-%d %H:%M:%S"))
            target = os.path.join(self.rgb_images_dir, filename)
            print('Copying image to', target)
            camera_file = gp.check_result(
                gp.gp_camera_file_get(self.rgb_camera, file_path.folder,
                                      file_path.name, gp.GP_FILE_TYPE_NORMAL))
            gp.check_result(gp.gp_file_save(camera_file, target))

            rostime = Time()
            rostime.data = rospy.get_rostime()
            self.rgb_file_writer.writerow({
                'RGB Image': filename,
                'Time': rospy.get_rostime()
            })
        except:
            rospy.logerr("PAL: Error in connection with RGB camera")
コード例 #30
0
def take_a_photo(id, tries=1):
    try:
        logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                            level=logging.WARNING)
        gp.check_result(gp.use_python_logging())
        camera = gp.check_result(gp.gp_camera_new())
        gp.check_result(gp.gp_camera_init(camera))
        print('Capturing image')
        file_path = gp.check_result(
            gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE))
        print('Camera file path: {0}/{1}'.format(file_path.folder,
                                                 file_path.name))
        target = os.path.join('/home/ubuntu/lexlaps/tmp',
                              str(id) + '_' + file_path.name)
        print('Copying image to', target)
        camera_file = gp.check_result(
            gp.gp_camera_file_get(camera, file_path.folder, file_path.name,
                                  gp.GP_FILE_TYPE_NORMAL))
        gp.check_result(gp.gp_file_save(camera_file, target))
        gp.check_result(gp.gp_camera_exit(camera))
    except:
        if tries < 4:
            take_a_photo(id, tries + 1)
コード例 #31
0
ファイル: run_booth.py プロジェクト: larsbkrogvig/balubabooth
    def capture_and_save(self):
        """Capture an image, save it and return the local path"""
        print('Capturing image')
        file_path = gp.check_result(gp.gp_camera_capture(self.camera,
                                                         gp.GP_CAPTURE_IMAGE,
                                                         self.context))
        capture_time = datetime.now().strftime("%Y%m%d-%H:%M:%S.%f")[:-4]
        filename = capture_time+'.jpg'

        print('Camera file path: {0}/{1}'.format(file_path.folder, filename)) #file_path.name

        target = os.path.join(self.localpath, filename)

        print('Copying image to', target)
        camera_file = gp.check_result(gp.gp_camera_file_get(self.camera,
                                                            file_path.folder,
                                                            file_path.name,
                                                            gp.GP_FILE_TYPE_NORMAL,
                                                            self.context))

        gp.check_result(gp.gp_file_save(camera_file, target))

        return target
コード例 #32
0
ファイル: copy-data.py プロジェクト: thathert/python-gphoto2
def main():
    logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                        level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    camera = gp.check_result(gp.gp_camera_new())
    context = gp.gp_context_new()
    gp.check_result(gp.gp_camera_init(camera, context))
    print('Getting list of files')
    files = list_files(camera, context)
    if not files:
        print('No files found')
        return 1
    path = files[0]
    print('Copying %s to memory' % path)
    folder, name = os.path.split(path)
    camera_file = gp.check_result(
        gp.gp_camera_file_get(camera, folder, name, gp.GP_FILE_TYPE_NORMAL,
                              context))
    # read file data using 'slurp' and a buffer allocated in Python
    info = gp.check_result(
        gp.gp_camera_file_get_info(camera, folder, name, context))
    file_data = bytearray(info.file.size)
    count = gp.check_result(gp.gp_file_slurp(camera_file, file_data))
    print(count, 'bytes read')
    # or read data using 'get_data_and_size' which allocates its own buffer
    ##    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    data = memoryview(file_data)
    print(type(data), len(data))
    print(data[:10].tolist())
    image = Image.open(io.BytesIO(file_data))
    image.show()
    print('After deleting camera_file and file_data')
    del camera_file, file_data
    print(type(data), len(data))
    print(data[:10].tolist())
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
コード例 #33
0
ファイル: pb.py プロジェクト: wellenvogel/photobooth
def getPicture(camera,context):
  print('Capturing image')
  showCapture(getClockFile(),(400,400))
  pygame.display.flip()
  current=os.path.join(TMPPATH,getImageName())
  if os.path.exists(current):
    os.unlink(current)
  file_path = gp.check_result(gp.gp_camera_capture(
        camera, gp.GP_CAPTURE_IMAGE, context))
  print('Camera file path: {0}/{1}'.format(file_path.folder, file_path.name))
  if not os.path.exists(TMPPATH):
    os.makedirs(TMPPATH)
  target = os.path.join(TMPPATH, getImageName(False))
  print('Copying image to', target)
  try:
    camera_file = gp.check_result(gp.gp_camera_file_get(
            camera, file_path.folder, file_path.name,
            gp.GP_FILE_TYPE_NORMAL, context))
    gp.check_result(gp.gp_file_save(camera_file, target))
  except:
    pass
  rt=gp.gp_camera_file_delete(camera,file_path.folder,file_path.name,context)
  showCapture(target)
  return target
コード例 #34
0
    def slurpd(self, device):
        contents = b""
        try:
            context = gp.gp_context_new()
            camera = gp.Camera()

            cameras = gp.PortInfoList()
            cameras.load()
            camera_address = cameras.lookup_path(device["address"])
            camera.set_port_info(cameras[camera_address])
            gp.check_result(gp.gp_camera_init(camera, context))

            captured = gp.check_result(
                gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE, context))

            captured_file = gp.check_result(
                gp.gp_camera_file_get(
                    camera,
                    captured.folder,
                    captured.name,
                    gp.GP_FILE_TYPE_NORMAL,
                    context,
                ))

            captured_file_data = gp.check_result(
                gp.gp_file_get_data_and_size(captured_file))
            container = io.BytesIO(memoryview(captured_file_data))
            container.seek(0)
            contents = container.read()

            gp.check_result(gp.gp_camera_exit(camera, context))

        except Exception as ex:
            print(ex)

        return contents
コード例 #35
0
def capture_test():

    # initialize camera.
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    expset_t = read_exposure_settings(camera)

    print('Capturing image')
    print('Current settings:', expset_t)
    file_path = gp.check_result(gp.gp_camera_capture(
        camera, gp.GP_CAPTURE_IMAGE))

    target = os.path.join(desti_dir, file_path.name)
    print('Copying image to', target)
    camera_file = gp.check_result(gp.gp_camera_file_get(
            camera, file_path.folder, file_path.name,
            gp.GP_FILE_TYPE_NORMAL))
    gp.check_result(gp.gp_file_save(camera_file, target))

    print('Bracketing by speed')
    files = bracket_by_speed(camera, '1/100', None, '400', 3, 1, 1, 99)

    # close camera.
    gp.check_result(gp.gp_camera_exit(camera))
コード例 #36
0
    def capture(self, n=1, camera = None, exposition = None, iso = None, focus = None, Zoom = None, save = True, publish = False, name = None):
        T_start = time.time()
        try:
            if not name:
                name = self.getCaptureName(extension = '')
            filename = '/home/odroid/robozor/', name + '_'+time.strftime("%Y%m%d-%H%M%S", time.gmtime())+'.cr2'
            gp.check_result(gp.use_python_logging())
            self.context = gp.gp_context_new()
            self.camera = gp.check_result(gp.gp_camera_new())
            gp.check_result(gp.gp_camera_init(self.camera, self.context))
            print'Capturing image', self.context, self.camera

            file_path = gp.check_result(gp.gp_camera_capture(self.camera, gp.GP_CAPTURE_IMAGE, self.context))
            print('Camera file path: {0}/{1}'.format(file_path.folder, file_path.name))
            target = os.path.join(filename)
            self.publishCR2(file = filename)
            print('Copying image to', target)
            camera_file = gp.check_result(gp.gp_camera_file_get(self.camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL, self.context))
            gp.check_result(gp.gp_file_save(camera_file, target))
            gp.check_result(gp.gp_camera_exit(self.camera, self.context))
            return True 
        except Exception, e:
            rospy.logerr(e)
            return False
コード例 #37
0
 def capture(self, savepath):
     #savedir = './picture/'+timestr+'.JPG'
     savedir = savepath
     logging.basicConfig(format='%(levelname)s: %(name)s: %(massage)s',
                         level=logging.WARNING)
     gp.check_result(gp.use_python_logging())
     camera = gp.check_result(gp.gp_camera_new())
     gp.check_result(gp.gp_camera_init(camera))
     print('Capturing image')
     file_path = gp.check_result(
         gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE))
     #print('Camera file path: {0}/{1}'.format(file_path.folder, file_path.name))
     #target = os.path.join(savedir, imagename)
     #print('Copying image to', target)
     camera_file = gp.check_result(
         gp.gp_camera_file_get(camera, file_path.folder, file_path.name,
                               gp.GP_FILE_TYPE_NORMAL))
     #gp.check_result(gp.gp_file_save(camera_file, target))
     #timestr = time.strftime('%Y%m%d_%H.%M.%S', time.strptime(time.ctime()))
     gp.check_result(gp.gp_file_save(camera_file, savedir))
     #gp.check_result(gp.gp_file_save(camera_file, './picture/'+timestr+'.jpg'))
     #subprocess.call(['xdg-open', target])
     gp.check_result(gp.gp_camera_exit(camera))
     return 'Shooting completed'
コード例 #38
0
    def _get_file(
        self,
        dir_name: str,
        file_name: str,
        dest_full_filename: Optional[str] = None,
        file_type: int = gp.GP_FILE_TYPE_NORMAL,
    ) -> gp.CameraFile:

        try:
            camera_file = gp.check_result(
                gp.gp_camera_file_get(self.camera, dir_name, file_name,
                                      file_type, self.context))
        except gp.GPhoto2Error as ex:
            logging.error(
                "Error reading %s from camera %s: %s",
                os.path.join(dir_name, file_name),
                self.display_name,
                gphoto2_named_error(ex.code),
            )
            raise CameraProblemEx(code=CameraErrorCode.read, gp_exception=ex)

        if dest_full_filename is not None:
            try:
                gp.check_result(
                    gp.gp_file_save(camera_file, dest_full_filename))
            except gp.GPhoto2Error as ex:
                logging.error(
                    "Error saving %s from camera %s: %s",
                    os.path.join(dir_name, file_name),
                    self.display_name,
                    gphoto2_named_error(ex.code),
                )
                raise CameraProblemEx(code=CameraErrorCode.write,
                                      gp_exception=ex)

        return camera_file
コード例 #39
0
def demo(photo_count, countdown_from):

    # create matrix device
    serial = spi(port=0, device=0, gpio=noop())
    device = max7219(serial, cascaded=4, block_orientation=-90, rotate=0)
    print("Created device")

    # setup button on Raspberry Pi Pin 18

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    while True:
        print("PUSH THE BUTTON!")
        with canvas(device) as draw:
            text(draw, (1, 0),
                 "Ready",
                 fill="white",
                 font=proportional(LCD_FONT))

        GPIO.wait_for_edge(18, GPIO.FALLING)

        print('Button Pressed')

        # Start by creating a folder for all the photos, with a folder inside called minis for gif-based

        time_now = time.strftime("%Y-%m-%d_%H-%M-%S", time.gmtime())
        pi_folder = os.path.join('/home/pi/wedding_photos/', time_now)
        minis_folder = os.path.join(pi_folder, 'minis')
        os.makedirs(minis_folder)

        gif_folder = os.path.join('/home/pi/wedding_photos/gifs/')
        # os.makedirs(gif_folder)

        # Start looping and taking photos!

        for index in range(photo_count):
            msg = ""
            for i in range(countdown_from):

                msg += "%s... " % (countdown_from - i)

            show_message(device,
                         msg,
                         fill="white",
                         font=proportional(LCD_FONT),
                         scroll_delay=0.05)

            with canvas(device) as draw:
                text(draw, (2, 0),
                     "Smile!",
                     fill="white",
                     font=proportional(LCD_FONT))

        # GPHOTO

            logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                                level=logging.WARNING)
            gp.check_result(gp.use_python_logging())
            camera = gp.check_result(gp.gp_camera_new())
            gp.check_result(gp.gp_camera_init(camera))
            print('Capturing image')
            file_path = gp.check_result(
                gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE))
            print('Camera file path: {0}/{1}'.format(file_path.folder,
                                                     file_path.name))

            # save image to pi
            target = os.path.join(
                pi_folder,
                time.strftime("%Y%m%d%H%M%S", time.gmtime()) + file_path.name)

            print('Copying image to', target)
            camera_file = gp.check_result(
                gp.gp_camera_file_get(camera, file_path.folder, file_path.name,
                                      gp.GP_FILE_TYPE_NORMAL))
            gp.check_result(gp.gp_file_save(camera_file, target))

            # subprocess.call(['xdg-open', target]) # Commented out as no need to open

            gp.check_result(gp.gp_camera_exit(camera))

            ## GPHOTO END

            device.clear()

        # OK, let's create a gif! First, let's create some smaller images

        for filename in os.listdir(pi_folder):
            if filename.endswith(".jpg"):
                img = Image(filename=os.path.join(pi_folder, filename))
                img.sample(780, 540)
                img.save(filename=os.path.join(minis_folder, filename))
            else:
                continue

        # Create a gif from them smaller images

        with Image() as wand:
            for filename in os.listdir(minis_folder):
                if filename.endswith(".jpg"):
                    with Image(filename=os.path.join(minis_folder,
                                                     filename)) as photo:
                        wand.sequence.append(photo)
                else:
                    continue
            for cursor in range(len(wand.sequence)):
                with wand.sequence[cursor] as frame:
                    frame.delay = 50
            wand.type = 'optimize'
            wand.save(
                filename=os.path.join(gif_folder, "{0}.gif".format(time_now)))
コード例 #40
0
	for i in range(37):
		photoangles.append([i*10])
	print photoangles


	notest = [[0], [10]]

	for coords in photoangles:
		stage.move(coords, 0)

		print('Capturing image')
		file_path = gp.check_result(gp.gp_camera_capture(
			camera, gp.GP_CAPTURE_IMAGE, context))
		print('Camera file path: {0}/{1}'.format(file_path.folder, file_path.name))
		target = os.path.join('/tmp', file_path.name)
		print('Copying image to', target)
		camera_file = gp.check_result(gp.gp_camera_file_get(
			camera, file_path.folder, file_path.name,
			gp.GP_FILE_TYPE_NORMAL, context))
		gp.check_result(gp.gp_file_save(camera_file, target))
		subprocess.call(['xdg-open', target])

		status = stage.aAxisNode.spinStatusRequest()
		while status['stepsRemaining'] > 0:
			time.sleep(0.001)
			status = stage.aAxisNode.spinStatusRequest()	
	
	gp.check_result(gp.gp_camera_exit(camera, context))


コード例 #41
0
def main():
    delete_files()
    #capture_image()
    logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                        level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    ############################################
    #begin set camera
    #camera = gp.check_result(gp.gp_camera_new())

    # make a list of all available cameras
    camera_list = []
    #for name, addr in gp.check_result(gp.gp_camera_autodetect()):
    #camera_list.append((name, addr))
    #if not camera_list:
    #print('No camera detected')

    #camera_list.sort(key=lambda x: x[0])
    ## ask user to choose one
    #for index, (name, addr) in enumerate(camera_list):
    #print('{:d}:  {:s}  {:s}'.format(index, addr, name))
    #if name == 'Canon PowerShot A620 (PTP mode)':
    #print(addr)
    #set_camera(addr)

    # end set camera
    ############################################
    #gp.check_result(gp.gp_camera_init(camera))
    #Day or Night
    # test_capture()

    sunrise = ephem.localtime(o.next_rising(s))
    sunset = ephem.localtime(o.next_setting(s))
    if sunset < sunrise:
        print('Day')

        print('Capturing image')
        file_path = gp.check_result(
            gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE))
        print('Camera file path: {0}/{1}'.format(file_path.folder,
                                                 file_path.name))
        target = os.path.join(path_to_images, file_path.name)
        print('Copying image to', target)
        camera_file = gp.check_result(
            gp.gp_camera_file_get(camera, file_path.folder, file_path.name,
                                  gp.GP_FILE_TYPE_NORMAL))
        gp.check_result(gp.gp_file_save(camera_file, target))
        gp.check_result(gp.gp_camera_exit(camera))
        #end capture image

        print(glob.glob("./*.*"))
        file_to_rename = glob.glob("./*.*")
        fix_me = str(file_to_rename)
        fix_me = re.sub('[[/\]\'\"]', '', fix_me)
        fix_me = re.sub('.', '', fix_me, 1)
        #pass_me = '["mv" ' + ', "' + path_to_images + '/' + fix_me + '" , "' + path_to_images + '/' + 'webcam.jpg"]'
        #print pass_me
        #shutil.copy(target, path_for_movie)
        os.rename(fix_me, 'webcam.jpg')

        #add current file to movie source
        file_found = True
        i = 1
        while file_found:
            ####################
            #fix base_file
            ####################
            if i > 9:
                zeros = '0'
            else:
                zeros = '00'
            #print(zeros)
            #the_file = base_file + str(i) + '.jpg'
            the_file = base_file + zeros + str(i) + '.jpg'
            #used to create a bunch of files
            #open(the_file, 'a')
            #print('Looking for :', the_file)
            if os.path.isfile(the_file):
                print('Found :', the_file)
                i += 1
            else:
                print('Creating 1 File')
                file_found = False
                #break loop and...
        #create one from current image
        #if i > 9:
        #zeros = '0'
        #else: zeros = '00'
        #print(zeros)
        scr = '/Users/Neal/Documents/gphoto2_testing/captured_image/webcam.jpg'
        dst = '/Users/Neal/Documents/gphoto2_testing/ForMovie/IMG_' + zeros + str(
            i) + '.jpg'
        print('Copyied Current')
        shutil.copy(scr, dst)

        #when there are 30 images create a movie and delete files
        path, dirs, files = os.walk(
            "/Users/Neal/Documents/gphoto2_testing/ForMovie").next()
        file_count = len(files)
        if file_count > 29:
            print('Making New Movie')
            #write something to process a movie hourly(ish)
            #the_file = '/Users/Neal/Documents/gphoto2_testing/TheMovie/test.mp4'
            theFile = '/Users/Neal/Dropbox/WeatherMovie/test.mp4'
            if os.path.isfile(the_file):
                os.remove(the_file)
            #os.system('ffmpeg -f image2 -r 1 -i /Users/Neal/Documents/gphoto2_testing/ForMovie/IMG_%03d.jpg -vcodec mpeg4 -y /Users/Neal/Documents/gphoto2_testing/TheMovie/test.mp')
            os.system(
                'ffmpeg -f image2 -r 1 -s 2027x1520 -i /Users/Neal/Documents/gphoto2_testing/ForMovie/IMG_%03d.jpg -vcodec libx264 -crf 10 -pix_fmt yuv420p -y /Users/Neal/Dropbox/WeatherMovie/test.mp4'
            )
            #write something to delete movie source
            for fl in glob.glob(
                    '/Users/Neal/Documents/gphoto2_testing/ForMovie/*.jpg'):
                os.remove(fl)
            subprocess.call([
                'python',
                '/Users/Neal/Documents/gphoto2_testing/delete-video.py'
            ])
            subprocess.call([
                'python',
                '/Users/Neal/Documents/gphoto2_testing/upload-video.py',
                '--file', '/Users/Neal/Dropbox/WeatherMovie/test.mp4',
                '--title', 'Bayshore Weather Timelapse'
            ])
        print('Deleting: {0}/{1}'.format(file_path.folder, file_path.name))
        gp.check_result(
            gp.gp_camera_file_delete(camera, file_path.folder, file_path.name))
        #subprocess.call(pass_me)
    else:
        print('Night')
コード例 #42
0
def get_captures_list(loop):

    current_milli_time = int(round(time.time() * 1000))
    print("CAPTURE BEGIN")

    com.usb_off()
    com.focus_on()
    time.sleep(8)
    com.shot()
    com.focus_off()
    com.usb_on()
    time.sleep(3)

    env = lmdb.open('./cameras_SN.lmdb', max_dbs=10)
    serialNumber_db = env.open_db('serialNumber'.encode())

    logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s', level=logging.ERROR)
    gp.check_result(gp.use_python_logging())
    timestamp = datetime.now()
    dest_dir = get_target_dir(timestamp)
    for name, addr in gp.check_result(gp.gp_camera_autodetect()):
        time0 = int(round(time.time() * 1000))
        camera = gp.Camera()
        port_info_list = gp.PortInfoList()
        port_info_list.load()
        idx = port_info_list.lookup_path(addr)
        camera.set_port_info(port_info_list[idx])
        camera.init()
        computer_files = list_computer_files()
        serialStr = get_serialNumber(camera)
        with env.begin(db=serialNumber_db) as txn:

            cameraName = txn.get(serialStr.encode()).decode("utf-8")
            print('Capturing image', cameraName)
            camera_files = list_camera_files(camera)
            if not camera_files:
                print('No files found')
                return 1
            print('Copying files...')
            for path in camera_files:
                info = get_camera_file_info(camera, path)
#                timestamp = datetime.fromtimestamp(info.file.mtime)
                folder, name = os.path.split(path)
                dest = os.path.join(dest_dir, cameraName + '_' + name )
                if dest in computer_files:
                    continue
                print('%s -> %s' % (path, dest_dir + cameraName + '_' + name))
                if not os.path.isdir(dest_dir):
                    os.makedirs(dest_dir)
                camera_file = gp.check_result(gp.gp_camera_file_get(
                    camera, folder, name, gp.GP_FILE_TYPE_NORMAL))
                gp.check_result(gp.gp_file_save(camera_file, dest))
                gp.check_result(gp.gp_camera_file_delete(camera, folder, name))
                time1 = int(round(time.time() * 1000))
                time_f = time1 - time0
                print(cameraName,' cap time (mS): ', time_f)
#            env.close()
        gp.check_result(gp.gp_camera_exit(camera))
    com.usb_off()
    current_milli_time1 = int(round(time.time() * 1000))
    time_f = current_milli_time1-current_milli_time
    print('all time (mS): ',time_f)

        #    with env.begin() as txn:
#        for key, value in txn.cursor(db=serialNumber_db):
#            print('  ', key, value, "/n")
#            current_config.append({key,value})
#    print("C_C: ",current_config)



                                 #debug


    #
    # com.usb_on()                                    #debug
    # time.sleep(3)
    # com.usb_off()
    # camera_list.sort(key=lambda x: x[0])
    # print(camera_list)
    # com.usb_off()
    #
    # camera_list = []
    # for name, addr in gp.check_result(gp.gp_camera_autodetect()):
    #     camera_list.append((name, addr))
    # if not camera_list:
    #     print('No camera detected')
    #     return 1
    # camera_list.sort(key=lambda x: x[0])
    # # ask user to choose one
    # tasks = []
    # for camera_item in camera_list:
    #     name, addr = camera_item
    #     print(f"{name} {addr}")
    #     camera = gp.Camera()
    #
    #     # search ports for camera port name
    #     port_info_list = gp.PortInfoList()
    #     port_info_list.load()
    #     idx = port_info_list.lookup_path(addr)
    #     camera.set_port_info(port_info_list[idx])
    #     camera.init()
    #
    #     tasks.append(asyncio.ensure_future(set_capture(camera)))
    #
    # asyncio.gather(*tasks, loop=loop)
    cmds = ['/usr/local/bin/ffprobe', '-f image2', '-pattern_type glob','-framerate 6','-i ./photo/*.JPG',' -s 1920x1080', './photo/video.mp4']
    return dest_dir
コード例 #43
0
def bracket_by_speed(camera, speed, fnum, iso,
    plus_minus_steps, delta_step, images_per_step, i_event):

    '''
    HDR Bracketing by shutter speed.

    Parameters
    ----------
    plus_minus_steps : int
        How many exposure combinations to take below and above the exposure
        settings given above. Total number of combinations is
        (2 * plus_minus_steps + 1).

    delta_step : int
        Step size in shutter speed. For my camera, every step is 1/3 stops.

    images_per_step : int
        How many frames to take for each exposure combination.
        Total number of frames is (2 * plus_minus_steps + 1) * images_per_step.

    i_event : int
        Index within the entire script (no effect, just for logging).
    '''

    timestamp_i = int(time.time())
    print('Event:', i_event)
    print('Bracketing by speed...')
    print('Time stamp:', timestamp_i)
    print('')

    # set camera to base value.
    update_exposure_settings(camera, speed=None, fnum=fnum, iso=iso,)

    # get index of shutter speed,
    speed_id = speed_values.index(speed)

    # bracket
    output_files = list()
    for i_step in range(-plus_minus_steps, plus_minus_steps + 1):

        update_exposure_settings(camera, \
                speed=speed_values[speed_id + i_step * delta_step])
        print('Set to: ISO {:8} Speed {:8}'.format(iso,
                speed_values[speed_id + delta_step * i_step]))

        # capture and save
        for j_image in range(images_per_step):

            # capture
            file_path = gp.check_result( \
                    gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE))
            print('Captured: {:}'.format(file_path.name))

            # save
            fname_j = '{:d}-{:02d}-{:02d}'.format(timestamp_i,
                    i_step + plus_minus_steps, j_image) + '.arw'
            target = os.path.join(desti_dir, fname_j)
            print('Copying image to', target)
            camera_file = gp.check_result(gp.gp_camera_file_get(
                    camera, file_path.folder, file_path.name,
                    gp.GP_FILE_TYPE_NORMAL))
            gp.check_result(gp.gp_file_save(camera_file, target))
            print('')

            output_files.append((i_step, j_image, fname_j))

    print('')

    # update exposure settings
    '''
    update_exposure_settings(camera,
            speed=next_speed, fnum=next_fnum, iso=next_iso)
    #'''

    # return list of files.
    return output_files
コード例 #44
0
gp_abilities_list_lookup_model()

gp_abilities_list_get_abilities()

gp_camera_set_abilities()

or something

and then do ports.. :(

'''

error = gp.gp_camera_init(camera, context)
print('done with init')
print(gp.gp_result_as_string(error))
#so I'm gonna add in error checks and all that
#but for now assume that the camera is now correctly initialized

#so let's say I want to make it take a picture
capturetype = gp.GP_CAPTURE_IMAGE
error, path = gp.gp_camera_capture(camera, capturetype, context)
print('took image')
print(gp.gp_result_as_string(error))
filetype = gp.GP_FILE_TYPE_NORMAL  #http://www.gphoto.org/doc/api/gphoto2-file_8h.html#ab9f339bdf374343272c62d2352753d69
error, file = gp.gp_camera_file_get(camera, path.folder, path.name, filetype,
                                    context)
print(gp.gp_result_as_string(error))
error = gp.gp_file_save(file, path.name)
print(gp.gp_result_as_string(error))
error = gp.gp_camera_exit(camera, context)
print(gp.gp_result_as_string(error))
コード例 #45
0
ファイル: timelapse.py プロジェクト: erdemarslan/TimeLapse
def main():
    parser = argparse.ArgumentParser(description='Timelapse app')
    parser.add_argument('-n',
                        '--num_of_shots',
                        help='Number of shots to take',
                        required=False)
    parser.add_argument('-t',
                        '--sleep_time',
                        help='Time between shots',
                        required=False)
    parser.add_argument('-s',
                        '--send_to_server',
                        help='Whether use the server. Y or N',
                        required=False)
    args = vars(parser.parse_args())
    if args['num_of_shots']:
        num_of_shots = args['num_of_shots']
        print('The number of shots is: ' + str(num_of_shots))
    else:
        num_of_shots = 10
    if args['sleep_time']:
        sleep_time = args['sleep_time']
        print('The sleep time is: ' + str(sleep_time))
    else:
        sleep_time = 5
        print('The sleep time is: ' + str(sleep_time))
    if args['send_to_server']:
        send_to_server = args['send_to_server']
        if send_to_server == 'y':
            print('The files will be sent to the server')
        else:
            print('The files will not be sent to the server')
    else:
        send_to_server = 'n'
        print('The files will not be sent to the server')
    x = 1
    while x < num_of_shots:
        logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                            level=logging.WARNING)
        gp.check_result(gp.use_python_logging())
        context = gp.gp_context_new()
        camera = gp.check_result(gp.gp_camera_new())
        gp.check_result(gp.gp_camera_init(camera, context))
        print('Capturing image')
        file_path = gp.check_result(
            gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE, context))
        print('Camera file path: {0}/{1}'.format(file_path.folder,
                                                 file_path.name))
        local_pics_directory = 'pics'
        if not os.path.exists(os.path.join(os.getcwd(), local_pics_directory)):
            os.makedirs(local_pics_directory)
        local_file_path = 'pics/' + file_path.name
        target = os.path.join(os.getcwd(), local_file_path)
        print('Attempt number ' + str(x))
        print('Copying image to', target)
        camera_file = gp.check_result(
            gp.gp_camera_file_get(camera, file_path.folder, file_path.name,
                                  gp.GP_FILE_TYPE_NORMAL, context))
        gp.check_result(gp.gp_file_save(camera_file, target))
        gp.check_result(gp.gp_camera_exit(camera, context))
        # Send files to the server
        if send_to_server == 'y':
            try:
                ssh = copy_to_server(server='192.168.8.111')
                print('Copying image to the server')
                scp = SCPClient(ssh.get_transport())
                scp.put(files=local_file_path,
                        remote_path='/media/Kratos/Timelapse')
                os.remove(local_file_path)
            except:
                print('server not connected')
                pass
        else:
            print('Files are not being sent to the server')
            # Remove file from the app's temp torage
        x += 1
        time.sleep(float(sleep_time))
コード例 #46
0
def get_files(camera, PHOTO_DIR, PHOTO_SUB_DIR):
    """
		カメラからファイルをダウンロードして本体ストレージへ保存する。
		そして、カメラ側ストレージからこれを削除する。
		Parameters
		----------
		camera : gp.camera object

		Returns
		-------
		return code

	"""
    logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                        level=logging.WARNING)
    callback_obj = gp.check_result(gp.use_python_logging())

    # カメラ内のフォルダを走査しファイル一覧を取得
    computer_files = list_computer_files(PHOTO_DIR)

    print('カメラからのファイルリストの取得中...')
    camera_files = list_camera_files(camera)
    if not camera_files:
        print('ファイルが見つかりませんでした。')
        return 1
    print('ファイルのダウンロード開始...')
    for path in camera_files:
        #path に保存対象のファイルのフルパスが与えられる
        #info に保存対象のファイルの情報を格納したオブジェクトが与えられる
        info = get_camera_file_info(camera, path)

        #timestamp に保存対象のファイルの日付情報がdatatime形式で与えられる
        timestamp = datetime.fromtimestamp(info.file.mtime)

        #path をディレクトリ名:folderとファイル名:nameに分ける
        folder, name = os.path.split(path)

        #保存先ディレクトリを取得
        dest_dir = get_target_dir(timestamp, PHOTO_DIR, PHOTO_SUB_DIR)

        #保存先ディレクトリとファイル名:nameを合わせ、dest_dirを生成
        dest = os.path.join(dest_dir, name)

        if dest in computer_files:
            # すでにダウンロード済みだったものの場合これ以下が実行される。
            # 下の工程で本体へ保存したものは削除しているので、
            # このループに入ることは何らかの原因で削除失敗した場合に限る。
            # つまりこの部分は念押し用。
            print("[{}]はすでに存在します".format(name))

            #本体へ保存したのでカメラ側は削除
            delete_file(camera, path)

            # 以後の工程をパスします
            continue

        # 保存工程開始
        print('[{}] を [{}] へ保存'.format(path, dest_dir))

        # 保存先フォルダがないなら作る
        if not os.path.isdir(dest_dir):
            os.makedirs(dest_dir)
            print("[{}] は存在しないため作成".format(dest_dir))

        print("[{}]のダウンロード開始".format(name))
        # 保存対象を決定?
        camera_file = gp.check_result(
            gp.gp_camera_file_get(camera, folder, name,
                                  gp.GP_FILE_TYPE_NORMAL))

        # 保存の実体 そして保存できたかの確認?ここで成否分岐しなくていいのか?
        gp.check_result(gp.gp_file_save(camera_file, dest))

        print("[{}]のダウンロード完了".format(name))

        #本体へ保存したのでカメラ側は削除
        delete_file(camera, path)

    print("全保存工程完了")
    camera.exit()
    return 0
コード例 #47
0
ファイル: guiMain.py プロジェクト: tumi23/CameraMove
    def import_all_photos_from_cameras(self):
        global haveCamFolder
        computer_files = self.list_computer_files()
        cameraCounter = 1
        camera_list = []
        # Get list of all connected cameras
        for name, addr in gp.check_result(gp.gp_camera_autodetect()):
            camera_list.append((name, addr))
        if not camera_list:
            self.importPhotosLabel.setText('No camera detected')
            return 1
        # Sort the camera list
        camera_list.sort(key=lambda x: x[0])
        for item in camera_list:
            cameraPercentage = int((cameraCounter / len(camera_list)) * 100)
            self.cameraProgressBarImport.setValue(cameraPercentage)
            self.importPhotosLabel.setText('Copying from camera %i of %i' %
                                           (cameraCounter, len(camera_list)))
            # intialize cameraName
            cameraName = 'NoName'
            # initialise camera
            name, addr = item
            camera = gp.Camera()
            # search ports for camera port name
            port_info_list = gp.PortInfoList()
            port_info_list.load()
            idx = port_info_list.lookup_path(addr)
            camera.set_port_info(port_info_list[idx])
            camera.init()
            # Get list of all files from the camera
            camera_files = self.list_camera_files(camera)
            if not camera_files:
                self.importPhotosLabel.setText('No files found')
                return 1
            # Figure out the name of the camera
            for path in camera_files:
                # Find the name of the file from its original path
                folder, name = os.path.split(path)
                # Creating the destination folder for the temporary file
                dest = os.path.join(TEMPORARY_DIR, name)
                if not os.path.isdir(TEMPORARY_DIR):
                    os.makedirs(TEMPORARY_DIR)
                # Load in the file and copy it on to the host machine
                camera_file = gp.check_result(
                    gp.gp_camera_file_get(camera, folder, name,
                                          gp.GP_FILE_TYPE_NORMAL))
                gp.check_result(gp.gp_file_save(camera_file, dest))
                # See if the exif info includes any name to attach to this camera.
                exif_dict = piexif.load(dest)
                if len(exif_dict["0th"][piexif.ImageIFD.Artist]) != 0:
                    cameraName = exif_dict["0th"][piexif.ImageIFD.Artist]
                    os.remove(dest)
                    os.rmdir(TEMPORARY_DIR)
                    break
                os.remove(dest)
            counter = 1
            # Old Import Part
            for path in camera_files:
                filePercentage = int((counter / len(camera_files)) * 100)
                self.fileProgressBarImport.setValue(filePercentage)
                # Construct the path that the images will be copied into on the host machine
                timestamp = datetime.now()
                folder, name = os.path.split(path)
                dest_dir = self.get_target_dir(timestamp)
                dest_dir = os.path.join(dest_dir, projectName)
                if haveCamFolder:
                    dest_dir = os.path.join(dest_dir, str(cameraName, 'utf-8'))
                dest = os.path.join(dest_dir, name)
                if dest in computer_files:
                    continue
                if not os.path.isdir(dest_dir):
                    os.makedirs(dest_dir)

                # Save image from camera
                camera_file = gp.check_result(
                    gp.gp_camera_file_get(camera, folder, name,
                                          gp.GP_FILE_TYPE_NORMAL))
                gp.check_result(gp.gp_file_save(camera_file, dest))
                saveLocations.append(dest)
                # Delete image from camera
                if imageDelCam:
                    gp.check_result(
                        gp.gp_camera_file_delete(camera, folder, name))

                counter += 1
            gp.check_result(gp.gp_camera_exit(camera))
            cameraCounter += 1
            camera.exit()
        self.importPhotosLabel.setText('Import Complete!')
コード例 #48
0
ファイル: guiMain.py プロジェクト: tumi23/CameraMove
 def import_regex_photos_from_cameras(self):
     global haveCamFolder
     computer_files = self.list_computer_files()
     cameraCounter = 1
     camera_list = []
     regexProject = ''
     # Check if projects exist
     txt = self.regexEdit.toPlainText()
     if len(txt) != 0:
         if not self.check_if_projects_exist(txt):
             self.projectRegexErrorLabel.setText(
                 'Error: One of those projects exists!')
         else:
             regexProject = txt
     else:
         self.projectRegexErrorLabel.setText('Error: No Text In Text Box!')
         return 1
     # Get list of all connected cameras
     for name, addr in gp.check_result(gp.gp_camera_autodetect()):
         camera_list.append((name, addr))
     if not camera_list:
         self.importPhotosLabel.setText('Error: No camera detected')
         return 1
     # Sort the camera list
     camera_list.sort(key=lambda x: x[0])
     for item in camera_list:
         fileCounter = 1
         cameraPercentage = int((cameraCounter / len(camera_list)) * 100)
         self.cameraProgressBarRegex.setValue(cameraPercentage)
         self.projectRegexErrorLabel.setText(
             'Copying from camera %i of %i' %
             (cameraCounter, len(camera_list)))
         # intialize cameraName
         cameraName = 'NoName'
         # initialise camera
         name, addr = item
         camera = gp.Camera()
         # search ports for camera port name
         port_info_list = gp.PortInfoList()
         port_info_list.load()
         idx = port_info_list.lookup_path(addr)
         camera.set_port_info(port_info_list[idx])
         camera.init()
         # Get list of all files from the camera
         camera_files = self.list_camera_files(camera)
         if not camera_files:
             self.importPhotosLabel.setText('No files found')
             return 1
         # Figure out the name of the camera
         for path in camera_files:
             # Find the name of the file from its original path
             folder, name = os.path.split(path)
             # Creating the destination folder for the temporary file
             dest = os.path.join(TEMPORARY_DIR, name)
             if not os.path.isdir(TEMPORARY_DIR):
                 os.makedirs(TEMPORARY_DIR)
             # Load in the file and copy it on to the host machine
             camera_file = gp.check_result(
                 gp.gp_camera_file_get(camera, folder, name,
                                       gp.GP_FILE_TYPE_NORMAL))
             gp.check_result(gp.gp_file_save(camera_file, dest))
             # See if the exif info includes any name to attach to this camera.
             exif_dict = piexif.load(dest)
             if len(exif_dict["0th"][piexif.ImageIFD.Artist]) != 0:
                 cameraName = exif_dict["0th"][piexif.ImageIFD.Artist]
                 os.remove(dest)
                 os.rmdir(TEMPORARY_DIR)
                 break
             os.remove(dest)
         currIndex = 0
         timestamp = datetime.now()
         time_dir = self.get_target_dir(timestamp)
         matches = re.finditer(wordRegex, regexProject, re.MULTILINE)
         # Find All Scripts
         for matchNum, match in enumerate(matches):
             currWord = match.group()
             nameMatches = re.finditer(nameRegex, match.group(),
                                       re.MULTILINE)
             # Find Project Name
             for nameMatchNum, nameMatch in enumerate(nameMatches):
                 currName = nameMatch.group().replace('(', '')
                 project_dir = os.path.join(time_dir, currName)
                 numberMatches = re.finditer(numberRegex, currWord,
                                             re.MULTILINE)
                 # Figure out what to delete and import
                 for numberMatchNum, numberMatch in enumerate(
                         numberMatches):
                     currNumber = numberMatch.group()
                     # Needs to be imported
                     if currNumber[0] == '+':
                         currNumber = int(numberMatch.group().replace(
                             '+', ''))
                         for x in range(currNumber):
                             filePercentage = int(
                                 (fileCounter / len(camera_files)) * 100)
                             self.fileProgressBarRegex.setValue(
                                 filePercentage)
                             self.projectRegexErrorLabel.setText(
                                 'Copying from camera %i of %i' %
                                 (cameraCounter, len(camera_list)))
                             folder, name = os.path.split(
                                 camera_files[currIndex])
                             if haveCamFolder:
                                 dest_dir = os.path.join(
                                     project_dir, str(cameraName, 'utf-8'))
                             else:
                                 dest_dir = project_dir
                             # Create directory
                             dest = os.path.join(dest_dir, name)
                             if dest in computer_files:
                                 continue
                             if not os.path.isdir(dest_dir):
                                 os.makedirs(dest_dir)
                             # Import photo
                             camera_file = gp.check_result(
                                 gp.gp_camera_file_get(
                                     camera, folder, name,
                                     gp.GP_FILE_TYPE_NORMAL))
                             gp.check_result(
                                 gp.gp_file_save(camera_file, dest))
                             if imageDelCam:
                                 gp.check_result(
                                     gp.gp_camera_file_delete(
                                         camera, folder, name))
                             saveLocations.append(dest_dir)
                             currIndex += 1
                     # Needs to be deleted
                     elif currNumber[0] == '-':
                         currNumber = int(numberMatch.group().replace(
                             '-', ''))
                         for x in range(currNumber):
                             filePercentage = int(
                                 (fileCounter / len(camera_files)) * 100)
                             self.fileProgressBarRegex.setValue(
                                 filePercentage)
                             self.projectRegexErrorLabel.setText(
                                 'Copying from camera %i of %i' %
                                 (cameraCounter, len(camera_list)))
                             folder, name = os.path.split(
                                 camera_files[currIndex])
                             gp.check_result(
                                 gp.gp_camera_file_delete(
                                     camera, folder, name))
                             currIndex += 1
                     fileCounter += 1
         gp.check_result(gp.gp_camera_exit(camera))
         cameraCounter += 1
         camera.exit()
     self.projectRegexErrorLabel.setText('Import Complete!')
コード例 #49
0
def main():
    #sunrise = ephem.localtime(o.next_rising(s))
    #sunset = ephem.localtime(o.next_setting(s))
    #now = datetime.now()
    ##print('Next Sunrise ',sunrise)
    ##print('Next Sunset ', sunset)
    ##print(now)
    ##if now > sunset and now < sunrise:
    ## if sunset < sunrise:
    #print('Day')
    #####################################
    #setup location
    location = Location(info=('Tidewater', 'Oregon', 44.5, -123.9,
                              'America/Los_Angeles', 100))
    location.timezone = 'America/Los_Angeles'
    #parse month, day, year and time from now
    now = datetime.datetime.now()
    ntime = now.strftime('%H:%M:%S')
    year = int(now.strftime('%Y'))
    month = int(now.strftime('%m'))
    day = int(now.strftime('%d'))
    #print('It is %d/%d/%d' % (month, day, year))
    sun = location.sun(local=True, date=date(year, month, day))
    # parse time from sunrise, sunset
    sunrise = sun['sunrise']
    srtime = sunrise.strftime('%H:%M:%S')
    sunset = sun['sunset']
    sstime = sunset.strftime('%H:%M:%S')
    #daylength = sunset - sunrise
    now = datetime.datetime.now()
    thedate = now.strftime('%D')
    #print thedate
    ntime = now.strftime('%H:%M:%S')
    print('Time Now is:\t\t%s' % (ntime))
    print('Sunrise Time is:\t%s' % (srtime))
    print('Sunset Time is:\t\t%s' % (sstime))
    if ntime > srtime and ntime < sstime:
        print("Therefore ItIs Day")
        #else: print("Therefore It Is Night")
        #####################################
        logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                            level=logging.WARNING)
        gp.check_result(gp.use_python_logging())
        delete_files()
        #print('Entering delete_files')
        #folder = '/store_00010001/DCIM/100CANON'
        #camera = gp.Camera()
        ## camera.init()
        ## gp.gp_camera_folder_delete_all(camera, folder)
        #test = gp.check_result(gp.gp_camera_folder_delete_all(camera, folder))
        #print(test)
        #text = "Deleteing Camera Files..."
        #print(text)
        camera = gp.check_result(gp.gp_camera_new())
        gp.check_result(gp.gp_camera_init(camera))
        print('Capturing image')
        file_path = gp.check_result(
            gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE))
        print('Camera file path: {0}/{1}'.format(file_path.folder,
                                                 file_path.name))
        target = os.path.join('/Users/Neal/Documents/gphoto2_testing',
                              file_path.name)
        print('Copying image to', target)
        camera_file = gp.check_result(
            gp.gp_camera_file_get(camera, file_path.folder, file_path.name,
                                  gp.GP_FILE_TYPE_NORMAL))
        #gp.check_result(gp.gp_file_save(camera_file, 'webcam.jpg'))
        gp.check_result(gp.gp_file_save(camera_file, target))
        #subprocess.call(['open', target])
        gp.check_result(gp.gp_camera_exit(camera))
        copy_files()
        return 0
    else:
        print("Therefore It Is Night")
コード例 #50
0
    photoangles = []
    for i in range(37):
        photoangles.append([i * 10])
    print photoangles

    notest = [[0], [10]]

    for coords in photoangles:
        stage.move(coords, 0)

        print('Capturing image')
        file_path = gp.check_result(
            gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE, context))
        print('Camera file path: {0}/{1}'.format(file_path.folder,
                                                 file_path.name))
        target = os.path.join('/tmp', file_path.name)
        print('Copying image to', target)
        camera_file = gp.check_result(
            gp.gp_camera_file_get(camera, file_path.folder, file_path.name,
                                  gp.GP_FILE_TYPE_NORMAL, context))
        gp.check_result(gp.gp_file_save(camera_file, target))
        subprocess.call(['xdg-open', target])

        status = stage.aAxisNode.spinStatusRequest()
        while status['stepsRemaining'] > 0:
            time.sleep(0.001)
            status = stage.aAxisNode.spinStatusRequest()

    gp.check_result(gp.gp_camera_exit(camera, context))
コード例 #51
0
ファイル: camera_gphoto.py プロジェクト: nadvornik/astro
	def capture_bulb(self, test = False, callback = None):
		if test:
			sec = self.status['test-exp-sec']

			self.set_config_value_checked('iso', self.status['test-iso'])
			try:
				self.status['test-iso'] = int(self.get_config_value('iso'))
			except:
				pass
			self.set_config_choice('capturetarget', 0) #mem
			self.set_config_choice('imageformat', 1) #Large Normal JPEG
		else:
			sec = self.status['exp-sec']

			self.set_config_value_checked('iso', self.status['iso'])
			try:
				self.status['iso'] = int(self.get_config_value('iso'))
			except:
				pass
			self.set_config_choice('capturetarget', 1) #card
			#self.set_config_choice('imageformat', 24) #RAW 
			self.set_config_choice('imageformat', 7) #RAW + Large Normal JPEG 

		self.set_config_value('aperture', self.status['f-number'])
		self.status['f-number'] = self.get_config_value('aperture')

		if sec <= 30:
			bulbmode = None
			self.set_config_value_checked('autoexposuremode', 'Manual')
			self.set_config_value_checked('shutterspeed', sec)
			gp.check_result(gp.gp_camera_trigger_capture(self.camera, self.context))
			
		else:
			self.set_config_value_checked('autoexposuremode', 'Manual')
			if not self.set_config_value_checked('shutterspeed', 'Bulb'):
				self.set_config_value_checked('autoexposuremode', 'Bulb')
		
			bulbmode = 'eosremoterelease'
			if not self.set_config_value_checked('eosremoterelease', 'Immediate'):
				self.set_config_value('bulb', 1)
				bulbmode = 'bulb'
		self.t_start = time.time()
		t = 0
		self.status['exp_in_progress'] = True
		self.status['interrupt'] = False
		while True:
			if t < sec - 4 and not self.status['interrupt']:
				time.sleep(3)
			e, file_path =  gp.check_result(gp.gp_camera_wait_for_event(self.camera, 1000,self.context))
			t = time.time() - self.t_start
			print "camera event ", t, e, file_path
			
			if self.status['exp_in_progress']:
				self.status['cur_time'] = int(t)

			if self.status['exp_in_progress'] and (t > sec or self.status['interrupt']):
				if bulbmode == 'bulb':
					self.set_config_value('bulb', 0)
				elif  bulbmode == 'eosremoterelease':
					self.set_config_value_checked('eosremoterelease', 'Release Full')
				self.status['exp_in_progress'] = False

			
			if e == gp.GP_EVENT_FILE_ADDED:
				print >> sys.stderr, "filepath:", file_path.folder, file_path.name
				filename, file_extension = os.path.splitext(file_path.name)
				if file_extension == ".jpg" or file_extension == ".JPG":
					break
		
		self.status['exp_in_progress'] = False
		self.status['cur_time'] = 0
		self.status['interrupt'] = False
	
		target = os.path.join('/tmp', file_path.name)
		
		n = 20
		while True:
			n -= 1
			try:
				camera_file = gp.check_result(gp.gp_camera_file_get(self.camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL, self.context))
				file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
				if callback is not None:
					callback(file_data)
				break
			except gp.GPhoto2Error as ex:
				if ex.code == gp.GP_ERROR_CAMERA_BUSY:
					time.sleep(1)

					if (n > 0):
						continue
				raise

		#stop review on display
		self.set_config_value_checked('eosremoterelease', 'Press Half')
		self.set_config_value_checked('eosremoterelease', 'Release Half')
	
		self.do_fps_hack()
コード例 #52
0
    def run(self):
        print("Capturing Thread started")
        window.label_2.setText("Capturing Thread started!")
        #filename
        image = "image"
        logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                            level=logging.WARNING)

        #braker variable stops the capturing process.
        global breaker
        breaker = False

        #opening connection to the camera:
        try:
            callback_obj = gp.check_result(gp.use_python_logging())
            camera = gp.check_result(gp.gp_camera_new())
            gp.check_result(gp.gp_camera_init(camera))

        except gp.GPhoto2Error as ex:
            if ex.code == gp.GP_ERROR_MODEL_NOT_FOUND:
                print("Camera is not turned on!")
                window.label_2.setText("Camera is not turned on!")
                return 0
            elif ex.code == -53:
                print("Unmount the Camera!")
                window.label_2.setText("Unmount the Camera!")
                return 0
            else:
                print("b")

        ser = serial.Serial(arduino)  # open serial port

        #subfolder for capturing
        self.ordner = str(self.ordner)
        print(self.ordner)
        #list all items in current folder
        path, dirs, files = next(
            os.walk(
                os.path.join(os.path.expanduser('~'), cfd, self.ordner,
                             'images')))
        capcount = len(files)
        print(files)
        time.sleep(1)

        #initialize arduino
        ser.write(b'A')
        time.sleep(2)

        #transmit number of samples to be taken
        ser.write(b'C')
        time.sleep(1)
        ser.write(self.slider.to_bytes(1, byteorder='little'))
        testread = ser.read()
        print(str(testread))
        time.sleep(1)

        #namelist consists of file image names, is used for deleting the last batch button
        global namelist
        namelist = []

        #Loop Capturing preferred samplesize(slider) is reached.
        for x in range(0, self.slider):
            if breaker:
                ser.write(b'B')
                print("Stopping..")
                window.label_2.setText("Stopping Capturing")
                if x == 0:
                    #setting the correct capture count
                    global r
                    r -= 1
                    window.lcdNumber.display(r)
                break

            #define the names under which the captured images are stored.
            imagename = image + str(x + capcount) + ".jpg"
            rz_imagename = image + str(x + capcount) + "RZ" + ".jpg"

            #initiate capturing process
            ser.write(b'A')
            if x == 0:
                time.sleep(1)
            time.sleep(2)
            print('Capturing image')
            window.label_2.setText("Capturing Image " + str(x + 1))
            try:
                file_path = gp.check_result(
                    gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE))
            except gp.GPhoto2Error as ex:
                if ex.code == -110:
                    print("Focus error")
                    window.label_2.setText("Camera Focus Error")
                if x == 0:
                    r -= 1
                    window.lcdNumber.display(r)
                break
            file_path_jpg = file_path.name.replace("cr2", "jpg")

            print('Camera file path: {0}/{1}'.format(file_path.folder,
                                                     file_path_jpg))

            #image storing location:
            target = os.path.join(os.path.expanduser('~'), cfd, self.ordner,
                                  'images', imagename)
            rzdest = os.path.join(os.path.expanduser('~'), cfd, self.ordner,
                                  'preview', rz_imagename)

            #Gphoto check Result

            camera_file = gp.check_result(
                gp.gp_camera_file_get(camera, file_path.folder, file_path_jpg,
                                      gp.GP_FILE_TYPE_NORMAL))
            gp.check_result(gp.gp_file_save(camera_file, target))

            namelist.append(target)

            calcProgressbar(x)

            gp.check_result(gp.gp_camera_exit(camera))

            # displaying image previews in the GUI
            window.label_6.setPixmap(window.graph1.pixmap())
            resizeImageWithQT(target, rzdest)
            pixmap = QtGui.QPixmap(rzdest)
            window.graph1.setPixmap(pixmap)

        ser.close()
コード例 #53
0
 def get_camera_file(self, folder, name):
     return gp.gp_camera_file_get(self.camera, folder, name,
                                  gp.GP_FILE_TYPE_NORMAL, self.context)
 def run(self):
     while True:
         try:
             context = gphoto.Context()
             camera = gphoto.Camera()
             camera.init(context)
             result_dict = {self.RESULT_KEY_CAMERA_IS_CONNECTED: True,
                            self.RESULT_KEY_SOURCE_PATH: None,
                            self.RESULT_KEY_PICTUE: None}
             self._result_queue.put(result_dict)
             while True:
                 event_type, event_data = camera.wait_for_event(1000, context)
                 if event_type == gphoto.GP_EVENT_FILE_ADDED:
                     # Handle new picture
                     source_file_path = event_data
                     source_file_name, source_file_extension = os.path.splitext(source_file_path.name)
                     # Download and save the picture
                     if (source_file_extension == '.JPG') or (source_file_extension == '.jpg'):
                         # Hadle JPEG picture files
                         self._jpg_counter += 1
                         picture_name = '{0}-IMG_{1:04d}.jpg'.format(time.strftime('%Y-%m-%d-%H-%M-%S'),
                                                                     self._jpg_counter)
                         picture_path = os.path.join(self._photo_path, picture_name)
                         camera_file = gphoto.check_result(gphoto.gp_camera_file_get(camera,
                                                                                     source_file_path.folder,
                                                                                     source_file_path.name,
                                                                                     gphoto.GP_FILE_TYPE_NORMAL,
                                                                                     context))
                         camera_file.save(picture_path)
                         source_path = os.path.join(source_file_path.folder, source_file_name)
                         result_dict = {self.RESULT_KEY_CAMERA_IS_CONNECTED: True,
                                        self.RESULT_KEY_SOURCE_PATH: source_path,
                                        self.RESULT_KEY_PICTUE: picture_name}
                         self._result_queue.put(result_dict)
                     else:
                         # Handle RAW picture files
                         self._raw_counter += 1
                         picture_name = '{0}-IMG_{1:04d}{2}'.format(time.strftime('%Y-%m-%d-%H-%M-%S'),
                                                                    self._raw_counter,
                                                                    source_file_extension)
                         picture_path = os.path.join(self._photo_path, picture_name)
                         camera_file = gphoto.check_result(gphoto.gp_camera_file_get(camera,
                                                                                     source_file_path.folder,
                                                                                     source_file_path.name,
                                                                                     gphoto.GP_FILE_TYPE_NORMAL,
                                                                                     context))
                         camera_file.save(picture_path)
                         source_path = os.path.join(source_file_path.folder, source_file_name)
                         result_dict = {self.RESULT_KEY_CAMERA_IS_CONNECTED: True,
                                        self.RESULT_KEY_SOURCE_PATH: source_path,
                                        self.RESULT_KEY_PICTUE: None}
                         self._result_queue.put(result_dict)
             camera.exit(context)
             break
         except gphoto.GPhoto2Error:
             result_dict = {self.RESULT_KEY_CAMERA_IS_CONNECTED: False,
                            self.RESULT_KEY_SOURCE_PATH: None,
                            self.RESULT_KEY_PICTUE: None}
             self._result_queue.put(result_dict)
             time.sleep(5)
             continue
コード例 #55
0
def timelapse(camera, wheel, relay, config_dict):

    ch_idx = 0
    # TODO: detect pictures already present in work_dir and continue numbering
    capture_idx = -1
    work_dir = config_dict['work_dir']
    interval = config_dict['interval']
    out_fmt = config_dict['out_fmt']
    channels = config_dict['wheel']['filters']
    assert len(config_dict['camera']) == len(
        channels
    ), "ERROR: Different number of channels for camera and filter wheel"
    ch = channels[0]

    # INIT
    exp = str(config_dict['camera'][ch]['exp'])
    iso = str(config_dict['camera'][ch]['iso'])
    f_val = float(config_dict['camera'][ch]['f_val'])
    set_camera_config(camera, exp, iso, f_val)
    relay.write("reset\n\r".encode('utf-8'))
    wheel.write([1, 0])

    try:
        while True:
            if ch_idx == 0:
                capture_idx += 1

            if DEBUG:
                print("CHANNEL {} (ch) [IT {}]".format(ch_idx, capture_idx),
                      file=sys.stderr)

            # LIGHTS UP AND CAPTURE
            if DEBUG:
                print("Lights up...", file=sys.stderr)
            relay_cmd = "relay on {}\n\r".format(ch_idx).encode('utf-8')
            relay.write(relay_cmd)
            if DEBUG:
                print("Lights up! Relay status:", file=sys.stderr)
                relay_cmd = "relay readall\n\r".encode('utf-8')
                relay.write(relay_cmd)
                print(relay.readlines(), file=sys.stderr)
                print("Shoot...", file=sys.stderr)
            camera_fn = gp.check_result(
                gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE))
            if DEBUG:
                print("Shoot!", file=sys.stderr)
                print("Lights down...", file=sys.stderr)
            relay_cmd = "relay off {}\n\r".format(ch_idx).encode('utf-8')
            relay.write(relay_cmd)
            if DEBUG:
                print("Lights down! Relay status:", file=sys.stderr)
                relay_cmd = "relay readall\n\r".encode('utf-8')
                relay.write(relay_cmd)
                print(relay.readlines(), file=sys.stderr)

            # SAVE PICTURE
            # TODO: save all channels' pictures during sleep
            if DEBUG:
                print('Saving picture...', file=sys.stderr)
            camera_f = gp.check_result(
                gp.gp_camera_file_get(camera, camera_fn.folder, camera_fn.name,
                                      gp.GP_FILE_TYPE_NORMAL))
            out_fn = os.path.join(
                work_dir,
                "{}_{}.{}".format(str(capture_idx).zfill(10), ch, out_fmt))
            gp.check_result(gp.gp_file_save(camera_f, out_fn))
            if DEBUG:
                print('Picture saved', file=sys.stderr)

            if ch_idx == 0:
                time_first_shot = time.time()

            # GET READY FOR NEXT SHOT
            ch_idx = (ch_idx + 1) % len(channels)
            ch = channels[ch_idx]
            # TODO: multithreaded/asynchronous config
            exp = str(config_dict['camera'][ch]['exp'])
            iso = str(config_dict['camera'][ch]['iso'])
            f_val = float(config_dict['camera'][ch]['f_val'])
            set_camera_config(camera, exp, iso, f_val)
            # TODO: check that the wheel is on the right position
            if DEBUG:
                print('Rotating filter wheel...', file=sys.stderr)
            wheel.write([ch_idx + 1, 0])
            time.sleep(1)
            if DEBUG:
                print('Filter wheel rotated', file=sys.stderr)

            if ch_idx == 0:
                # just to be sure...if relay off command lost, screw up only one shot
                relay.write("reset\n\r".encode('utf-8'))
                if DEBUG:
                    print("Relay switch reset! Relay status:", file=sys.stderr)
                    relay_cmd = "relay readall\n\r".encode('utf-8')
                    relay.write(relay_cmd)
                    print(relay.readlines(), file=sys.stderr)
                # TODO: sleep the diff between time of first shot and now
                # (so that same channel has ~ interval)
                print("Going to sleep", file=sys.stderr)
                time.sleep(interval)

    except KeyboardInterrupt:
        clean_env(camera, wheel, relay)