def capture(save_path, filename):
    #log to be used by gphoto
    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))

    config = camera.get_config(context)
    target = config.get_child_by_name('viewfinder')
    target.set_value(1)
    camera.set_config(config, context)
    target.set_value(0)
    camera.set_config(config, context)

    time.sleep(2)

    #capture the image (to camera's internal SD card)
    file_path = gp.check_result(gp.gp_camera_capture(
        camera, gp.GP_CAPTURE_IMAGE))

    #Copy the image over usb to the local filesystem
    target = os.path.join(save_path, filename)
    camera_file = gp.check_result(gp.gp_camera_file_get(
            camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL))

    gp.gp_file_save(camera_file, target)

    #exit the camera to complete the process
    gp.gp_camera_exit(camera)
    return 0
Exemple #2
0
def start_photobooth():
    ##for the first PIC
    preview(3,'r',1)
    if play_shutter_sound == 1:
        shutter_sound.play()

    #take the photos
    file_name=time.strftime("%d%m%Y_%H%M%S")
    for i, filename in enumerate(camera.capture_continuous(file_path + file_name + '-' + '{counter:02d}.jpg',use_video_port=False)):
        print(filename)

        if use_external_camera == 1:
            context = gp.gp_context_new()
            camera_ext = gp.check_result(gp.gp_camera_new())
            error = gp.gp_camera_init(camera_ext, context)
            if error != gp.GP_ERROR_MODEL_NOT_FOUND:
                gp.gp_camera_capture(camera_ext, gp.GP_CAPTURE_IMAGE)
            gp.gp_camera_exit(camera_ext)

        if i == total_pics-1:
            #GPIO.output(led1_pin,False);
            break
        preview(3,'r',i+2)
        if play_shutter_sound == 1:
            shutter_sound.play()

    #show photos
    for pNum in range (1,total_pics+1):
        displayImage(file_path + file_name + '-0' + str(pNum) + '.jpg')
        text = 'photo ' + str(pNum) + ' of ' + str(total_pics)
        drawText(small_font, text, clear_screen=False, color=(255,255,255), y=15)
        time.sleep(5)
Exemple #3
0
    def disconnect(self):
        logging.debug('trying to close an existing connection')

        if self._camera is not None and self._context is not None:
            gp.gp_camera_exit(self._camera, self._context)

        self._camera = None
        self._context = None
        self.close_other_gphoto_processes()
Exemple #4
0
def open_camera():
    """ context manager to control access to the camera resource """
    camera = gp.check_result(gp.gp_camera_new())
    context = gp.gp_context_new()
    gp.check_result(gp.gp_camera_init(camera, context))
    yield camera, context
    gp.check_result(gp.gp_camera_exit(camera, context))
def main():
    # use Python logging
    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    callback_obj = gp.check_result(gp.use_python_logging())
    # get user value
    if len(sys.argv) != 2:
        print('One command line parameter required')
        return 1
    try:
        value = int(sys.argv[1])
    except:
        print('Integer parameter required')
        return 1
    # open camera connection
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    # 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'))
    # check value in range
    count = gp.check_result(gp.gp_widget_count_choices(capture_target))
    if value < 0 or value >= count:
        print('Parameter out of range')
        return 1
    # set value
    value = gp.check_result(gp.gp_widget_get_choice(capture_target, value))
    gp.check_result(gp.gp_widget_set_value(capture_target, value))
    # set config
    gp.check_result(gp.gp_camera_set_config(camera, config))
    # clean up
    gp.check_result(gp.gp_camera_exit(camera))
    return 0
Exemple #6
0
    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
    def mavlink_packet(self, m):
        '''handle mavlink packets'''
        if m.get_type() == 'GLOBAL_POSITION_INT':
            if self.settings.target_system == 0 or self.settings.target_system == m.get_srcSystem():
                self.packets_mytarget += 1
            else:
                self.packets_othertarget += 1
	    (self.vehicleLat, self.vehicleLon, self.vehicleHdg, self.vehicleAMSL) = (m.lat*1.0e-7, m.lon*1.0e-7, m.hdg*0.01, m.alt*0.001)
	#if mtype == "ATTITUDE":
	    (self.vehicleRoll, self.vehiclePitch, self.vehicleYaw) = (math.degrees(m.roll), math.degrees(m.pitch), math.degrees(m.yaw))
	if m.get_type() == "CAMERA_STATUS":
		print ("Got Message camera_status")
	if m.get_type() == "CAMERA_FEEDBACK":
		print ("Got Message camera_feedback")
		'''self.__vCmdCamTrigger(m)'''	
		file_path = gp.check_result(gp.gp_camera_capture(self.camera, gp.GP_CAPTURE_IMAGE, self.context))

		geotagFile = open(self.imageLogFilePath, 'a')
		params = "%s\t%f\t%f\t%f\t%f\t%f\t%f\n" % (file_path.name, self.vehicleLat, self.vehicleLon, self.vehicleAMSL, self.vehicleRoll, self.vehiclePitch, self.vehicleYaw)
		geotagFile.write(params)
		geotagFile.close()
		print(params)
    		print('Camera file path: {0}/{1}'.format(file_path.folder, file_path.name))
		target = os.path.join(self.targetPath, file_path.name)
		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(camera, self.context))
		
	if m.get_type() == "COMMAND_LONG":
		if m.command == mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONFIGURE:
			print ("Got Message Digicam_configure")
		elif m.command == mavutil.mavlink.MAV_CMD_DO_DIGICAM_CONTROL:
			print ("Got Message Digicam_control")
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))
    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 in 100 kilobyte chunks' % path)
    folder, name = os.path.split(path)
    file_info = gp.check_result(gp.gp_camera_file_get_info(
        camera, folder, name))
    data = bytearray(file_info.file.size)
    view = memoryview(data)
    chunk_size = 100 * 1024
    offset = 0
    while offset < len(data):
        bytes_read = gp.check_result(gp.gp_camera_file_read(
            camera, folder, name, gp.GP_FILE_TYPE_NORMAL,
            offset, view[offset:offset + chunk_size]))
        offset += bytes_read
        print(bytes_read)
    print(' '.join(map(str, data[0:10])))
    image = Image.open(io.BytesIO(data))
    image.show()
    gp.check_result(gp.gp_camera_exit(camera))
    return 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))
    text = gp.check_result(gp.gp_camera_get_summary(camera))
    print('Summary')
    print('=======')
    print(text.text)
    print('Abilities')
    print('=========')
    abilities = gp.check_result(gp.gp_camera_get_abilities(camera))
    print('model:', abilities.model)
    print('status:', abilities.status)
    print('port:', abilities.port)
    print('speed:', abilities.speed)
    print('operations:', abilities.operations)
    print('file_operations:', abilities.file_operations)
    print('folder_operations:', abilities.folder_operations)
    print('usb_vendor:', abilities.usb_vendor)
    print('usb_product:', abilities.usb_product)
    print('usb_class:', abilities.usb_class)
    print('usb_subclass:', abilities.usb_subclass)
    print('usb_protocol:', abilities.usb_protocol)
    print('library:', abilities.library)
    print('id:', abilities.id)
    print('device_type:', abilities.device_type)
    gp.check_result(gp.gp_camera_exit(camera))
    return 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))
    files = list_files(camera)
    if not files:
        print('No files found')
        return 1
    print('File list')
    print('=========')
    for path in files[:10]:
        print(path)
    print('...')
    for path in files[-10:]:
        print(path)
    info = get_file_info(camera, files[-1])
    print
    print('File info')
    print('=========')
    print('image dimensions:', info.file.width, info.file.height)
    print('image type:', info.file.type)
    print('file mtime:', datetime.fromtimestamp(info.file.mtime).isoformat(' '))
    gp.check_result(gp.gp_camera_exit(camera))
    return 0
Exemple #11
0
def takeApicture():
    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))
    curFilePath = os.path.dirname(os.path.realpath(__file__))
    imgName = "Photomat_" + datetime.now().isoformat() + ".jpg"
    target = os.path.join(curFilePath, 'static/img', imgName)
    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))

    data = {"response": "OK"}

    js = json.dumps(data)
    resp = Response(js, status=200, mimetype='application/json')
    return resp
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
Exemple #13
0
def take_photo():

    # Get the directory containing this script
    photoDir = os.path.dirname(os.path.realpath(__file__))

    # Create capture directory
    photoDirName = "photos"
    photoDir = os.path.join(photoDir, photoDirName)
    if not os.path.exists(photoDir):
        print("Creating photo directory")
        os.makedirs(photoDir)

    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))
    photoFile = os.path.join(photoDir, file_path.name)
    print('Copying image to', photoFile)
    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, photoFile))
    #subprocess.call(['xdg-open', photoFile])
    gp.check_result(gp.gp_camera_exit(camera))

    return photoFile
Exemple #14
0
def main():
    # use Python logging
    logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                        level=logging.WARNING)
    callback_obj = gp.check_result(gp.use_python_logging())
    # get user value
    if len(sys.argv) != 2:
        print('One command line parameter required')
        return 1
    try:
        value = int(sys.argv[1])
    except:
        print('Integer parameter required')
        return 1
    # open camera connection
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    # 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'))
    # check value in range
    count = gp.check_result(gp.gp_widget_count_choices(capture_target))
    if value < 0 or value >= count:
        print('Parameter out of range')
        return 1
    # set value
    value = gp.check_result(gp.gp_widget_get_choice(capture_target, value))
    gp.check_result(gp.gp_widget_set_value(capture_target, value))
    # set config
    gp.check_result(gp.gp_camera_set_config(camera, config))
    # clean up
    gp.check_result(gp.gp_camera_exit(camera))
    return 0
Exemple #15
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))
    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
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())
    gp.check_result(gp.gp_camera_init(camera))
    print('Getting list of files from camera...')
    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_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_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_exit(camera))
    return 0
Exemple #17
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))
    files = list_files(camera, context)
    if not files:
        print('No files found')
        return 1
    print('File list')
    print('=========')
    for path in files[:10]:
        print(path)
    print('...')
    for path in files[-10:]:
        print(path)
    info = get_file_info(camera, context, files[-1])
    print
    print('File info')
    print('=========')
    print('image dimensions:', info.file.width, info.file.height)
    print('image type:', info.file.type)
    print('file mtime:',
          datetime.fromtimestamp(info.file.mtime).isoformat(' '))
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
Exemple #18
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))
    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
Exemple #19
0
    def take_photo(self):
        print('Capturing image')

        self.use_cached = True

        gp.check_result(gp.gp_camera_exit(self.camera))
        self.camera = gp.check_result(gp.gp_camera_new())
        gp.check_result(gp.gp_camera_init(self.camera))

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

        info = gp.check_result(
            gp.gp_camera_file_get_info(self.camera, file_path.folder,
                                       file_path.name))
        timestamp = info.file.mtime
        timestamp_str = 't' + str(timestamp)
        file_name_split = file_path.name.split('.')
        file_name_split.insert(1, timestamp_str)
        file_name = '.'.join(file_name_split)
        target = os.path.join(self.PHOTO_DIR, file_name)
        if not os.path.isdir(self.PHOTO_DIR):
            os.makedirs(self.PHOTO_DIR)
        camera_file = gp.check_result(
            gp.gp_camera_file_get(self.camera, file_path.folder,
                                  file_path.name, gp.GP_FILE_TYPE_NORMAL))
        gp.check_result(gp.gp_file_save(camera_file, target))
        send_file(target)

        self.use_cached = False
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))
    text = gp.check_result(gp.gp_camera_get_summary(camera))
    print('Summary')
    print('=======')
    print(text.text)
    print('Abilities')
    print('=========')
    abilities = gp.check_result(gp.gp_camera_get_abilities(camera))
    print('model:', abilities.model)
    print('status:', abilities.status)
    print('port:', abilities.port)
    print('speed:', abilities.speed)
    print('operations:', abilities.operations)
    print('file_operations:', abilities.file_operations)
    print('folder_operations:', abilities.folder_operations)
    print('usb_vendor:', abilities.usb_vendor)
    print('usb_product:', abilities.usb_product)
    print('usb_class:', abilities.usb_class)
    print('usb_subclass:', abilities.usb_subclass)
    print('usb_protocol:', abilities.usb_protocol)
    print('library:', abilities.library)
    print('id:', abilities.id)
    print('device_type:', abilities.device_type)
    gp.check_result(gp.gp_camera_exit(camera))
    return 0
Exemple #21
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))
    data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    print(type(data), len(data))
    if six.PY2:
        print(map(ord, data[0:10]))
        image = Image.open(StringIO.StringIO(data))
    else:
        print(data[0:10])
        image = Image.open(io.BytesIO(data))
    image.show()
    print('After deleting camera_file')
    del camera_file
    print(type(data), len(data))
    if six.PY2:
        print(map(ord, data[0:10]))
    else:
        print(data[0:10])
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 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
Exemple #23
0
 def close(self):
     """
     Close camera connection
     :return:
     """
     # clean up
     gp.check_result(gp.gp_camera_exit(self.camera, self.context))
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 in 100 kilobyte chunks' % path)
    folder, name = os.path.split(path)
    file_info = gp.check_result(gp.gp_camera_file_get_info(
        camera, folder, name, context))
    data = bytearray(file_info.file.size)
    view = memoryview(data)
    chunk_size = 100 * 1024
    offset = 0
    while offset < len(data):
        bytes_read = gp.check_result(gp.gp_camera_file_read(
            camera, folder, name, gp.GP_FILE_TYPE_NORMAL,
            offset, view[offset:offset + chunk_size], context))
        offset += bytes_read
        print(bytes_read)
    print(' '.join(map(str, data[0:10])))
    image = Image.open(io.BytesIO(data))
    image.show()
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
Exemple #25
0
def main():
    # use Python logging
    logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                        level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    # open camera connection
    camera = gp.check_result(gp.gp_camera_new())
    context = gp.gp_context_new()
    gp.check_result(gp.gp_camera_init(camera, context))
    # get configuration tree
    config = gp.check_result(gp.gp_camera_get_config(camera, context))
    # find the capture target config item
    capture_target = gp.check_result(
        gp.gp_widget_get_child_by_name(config, 'capturetarget'))
    # print current setting
    value = gp.check_result(gp.gp_widget_get_value(capture_target))
    print('Current setting:', value)
    # print possible settings
    for n in range(gp.check_result(
            gp.gp_widget_count_choices(capture_target))):
        choice = gp.check_result(gp.gp_widget_get_choice(capture_target, n))
        print('Choice:', n, choice)
    # clean up
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
    def takePhoto(self):
        return self.takePhoto2()

        logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                            level=logging.WARNING)
        self.bCameraBusy = True
        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)
        target = os.path.join(CURRENT_DIR, '..', 'LightPaintings',
                              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))
        if (self.completeRepeats == self.iRepeats):
            subprocess.call(['xdg-open', target])
        gp.check_result(gp.gp_camera_exit(camera))
        self.bCameraBusy = False
        return 0
Exemple #27
0
    def synchronize_camera_timestamp(self):
        def set_datetime(config):
            OK, date_config = gp.gp_widget_get_child_by_name(
                config, 'datetime')
            if OK >= gp.GP_OK:
                widget_type = gp.check_result(
                    gp.gp_widget_get_type(date_config))
                if widget_type == gp.GP_WIDGET_DATE:
                    now = int(time.time())
                    gp.check_result(gp.gp_widget_set_value(date_config, now))
                else:
                    now = time.strftime('%Y-%m-%d %H:%M:%S')
                    gp.check_result(gp.gp_widget_set_value(date_config, now))
                return True
            return False

        # get configuration tree
        config = gp.check_result(gp.gp_camera_get_config(
            self.camera))  #, self.context))
        # find the date/time setting config item and set it
        if set_datetime(config):
            # apply the changed config
            gp.check_result(gp.gp_camera_set_config(self.camera,
                                                    config))  #, self.context))
        else:
            print('Could not set date & time')
        # clean up
        gp.check_result(gp.gp_camera_exit(self.camera))  #, self.context))
        return 0
Exemple #28
0
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
Exemple #29
0
 def change_iso_setting(self):
     camera = gp.check_result(gp.gp_camera_new())
     gp.check_result(gp.gp_camera_init(camera))
     camera_config = gp.check_result(gp.gp_camera_get_config(camera))
     for child in gp.check_result(gp.gp_widget_get_children(camera_config)):
         print(gp.check_result(gp.gp_widget_get_label(child)))
     gp.check_result(gp.gp_camera_exit(camera))
 def close(self):
     """
     Close camera connection
     :return:
     """
     # clean up
     gp.check_result(gp.gp_camera_exit(self.camera, self.context))
Exemple #31
0
def camera_test():

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

    # test shutter speeds
    for speed_i in speed_values:
        update_exposure_settings(camera, speed=speed_i)
        time.sleep(1)
        expset = read_exposure_settings(camera)
        print('Shutter speed set to:', speed_i, ', Current settings', expset)
        assert expset['speed'] == speed_i

    # test ISO values.
    for iso_i in iso_values:
        update_exposure_settings(camera, iso=iso_i)
        time.sleep(1)
        expset = read_exposure_settings(camera)
        print('ISO set to:', iso_i, ', Current settings', expset)
        assert expset['iso'] == iso_i

    # test apertures
    for fnum_i in fnum_values_num:
        update_exposure_settings(camera, fnum=fnum_i)
        time.sleep(1)
        expset = read_exposure_settings(camera)
        print('Aperture set to:', fnum_i, ', Current settings', expset)
        assert expset['fnum'] == fnum_i

    # close camera.
    gp.check_result(gp.gp_camera_exit(camera))
Exemple #32
0
async def capture(websocket):
    # Capture Image
    try:
        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))
        filename = get_next_filename(image_dir)
        target = os.path.join(image_dir, filename)

        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))

        if os.path.isdir(usb_dir):
            shutil.copy(target, os.path.join(usb_dir, filename))

        print('Image Ready!')
        await send_message({
            'event': 'imageReady',
            'filename': filename,
            'name': filename.split('.')[0]
        })

    except Exception as e:
        print("Error while trying to take photo: " + str(e))
        await send_message({'event': 'captureError', 'error': str(e)})
Exemple #33
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    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))
    storage_info = gp.check_result(
        gp.gp_camera_get_storageinfo(camera, context))
    if len(storage_info) > 1:
        print('Unable to handle camera with multiple storage media')
        return 1
    if len(storage_info) == 0:
        print('No storage info available')
        return 2
    si = storage_info[0]
    if not (si.fields & gp.GP_STORAGEINFO_MAXCAPACITY
            and si.fields & gp.GP_STORAGEINFO_FREESPACEKBYTES):
        print('Cannot read storage capacity')
        return 3
    print('Camera has %.1f%% free space' %
          (100.0 * float(si.freekbytes) / float(si.capacitykbytes)))
    if len(argv) < 2:
        return 4
    if len(argv) > 2:
        print('usage: %s [percent_to_clear]' % argv[0])
        return 5
    target = float(argv[1]) / 100.0
    target = int(target * float(si.capacitykbytes))
    free_space = si.freekbytes
    if free_space >= target:
        print('Sufficient free space')
        return 0
    print('Getting file list...')
    files = list_files(camera, context)
    mtime = {}
    size = {}
    for path in files:
        info = get_file_info(camera, context, path)
        mtime[path] = info.file.mtime
        size[path] = info.file.size
    files.sort(key=lambda x: mtime[x], reverse=True)
    while True:
        while files and free_space < target:
            path = files.pop()
            print('Delete', path)
            delete_file(camera, context, path)
            free_space += size[path] // 1000
        storage_info = gp.check_result(
            gp.gp_camera_get_storageinfo(camera, context))
        si = storage_info[0]
        print('Camera has %.1f%% free space' %
              (100.0 * float(si.freekbytes) / float(si.capacitykbytes)))
        free_space = si.freekbytes
        if free_space >= target:
            break
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
def info():
    context = gp_context_new()
    error, camera = gp_camera_new()
    error = gp_camera_init(camera, context)
    error, text = gp_camera_get_summary(camera, context)
    error = gp_camera_exit(camera, context)
    return text.text
def main(argv=None):
    if argv is None:
        argv = sys.argv
    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))
    storage_info = gp.check_result(gp.gp_camera_get_storageinfo(camera, context))
    if len(storage_info) > 1:
        print('Unable to handle camera with multiple storage media')
        return 1
    if len(storage_info) == 0:
        print('No storage info available')
        return 2
    si = storage_info[0]
    if not (si.fields & gp.GP_STORAGEINFO_MAXCAPACITY and
            si.fields & gp.GP_STORAGEINFO_FREESPACEKBYTES):
        print('Cannot read storage capacity')
        return 3
    print('Camera has %.1f%% free space' % (
        100.0 * float(si.freekbytes) / float(si.capacitykbytes)))
    if len(argv) < 2:
        return 4
    if len(argv) > 2:
        print('usage: %s [percent_to_clear]' % argv[0])
        return 5
    target = float(argv[1]) / 100.0
    target = int(target * float(si.capacitykbytes))
    free_space = si.freekbytes
    if free_space >= target:
        print('Sufficient free space')
        return 0
    print('Getting file list...')
    files = list_files(camera, context)
    mtime = {}
    size = {}
    for path in files:
        info = get_file_info(camera, context, path)
        mtime[path] = info.file.mtime
        size[path] = info.file.size
    files.sort(key=lambda x: mtime[x], reverse=True)
    while True:
        while files and free_space < target:
            path = files.pop()
            print('Delete', path)
            delete_file(camera, context, path)
            free_space += size[path] // 1000
        storage_info = gp.check_result(
            gp.gp_camera_get_storageinfo(camera, context))
        si = storage_info[0]
        print('Camera has %.1f%% free space' % (
            100.0 * float(si.freekbytes) / float(si.capacitykbytes)))
        free_space = si.freekbytes
        if free_space >= target:
            break
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
Exemple #36
0
def signal_handler_quit(signal, frame):
    logging.info("Shutting down requested")

    webserver.shutdown()
    logging.debug("Webserver shutdown")

    gp.check_result(gp.gp_camera_exit(camera))
    logging.info("Releasing camera")

    logging.critical("Photob00th shutdown.\n")
    sys.exit(0)
Exemple #37
0
def test_camera():
    global camera, context, config, camera_config_name, camera_config
    print("Testing Camera")
    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_list = []
    for name, addr in context.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])
    name, addr = camera_list[0]
    camera = gp.Camera()
    #camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera, context))
    config = gp.check_result(gp.gp_camera_get_config(camera, context))
    text = gp.check_result(gp.gp_camera_get_summary(camera, context))
    print('Summary')
    print('=======')
    print(text.text)
    print('Abilities')
    print('=========')
    abilities = gp.check_result(gp.gp_camera_get_abilities(camera))
    print('model:', abilities.model)
    print('status:', abilities.status)
    print('port:', abilities.port)
    print('speed:', abilities.speed)
    print('operations:', abilities.operations)
    print('file_operations:', abilities.file_operations)
    print('folder_operations:', abilities.folder_operations)
    print('usb_vendor:', abilities.usb_vendor)
    print('usb_product:', abilities.usb_product)
    print('usb_class:', abilities.usb_class)
    print('usb_subclass:', abilities.usb_subclass)
    print('usb_protocol:', abilities.usb_protocol)
    print('library:', abilities.library)
    print('id:', abilities.id)
    print('device_type:', abilities.device_type)
    child_count = gp.check_result(gp.gp_widget_count_children(config))
    if child_count < 1:
        return
    tabs = None
    for n in range(child_count):
        child = gp.check_result(gp.gp_widget_get_child(config, n))
        camera_config.append(getConfig(child))
        label = gp.check_result(gp.gp_widget_get_label(child))
        camera_config_name.append(label)
        print('!!!!!!! CONFIG ', child, label)
    name = gp.check_result(gp.gp_widget_get_name(child))
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
Exemple #38
0
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
Exemple #39
0
 def set_capture_target(self, value):
     config = gp.check_result(gp.gp_camera_get_config(self.camera))
     capture_target = gp.check_result(
         gp.gp_widget_get_child_by_name(config, 'capturetarget'))
     count = gp.check_result(gp.gp_widget_count_choices(capture_target))
     if value < 0 or value >= count:
         print('Parameter out of range')
         value = 1
     value = gp.check_result(gp.gp_widget_get_choice(capture_target, value))
     gp.check_result(gp.gp_widget_set_value(capture_target, value))
     gp.check_result(gp.gp_camera_set_config(self.camera, config))
     gp.check_result(gp.gp_camera_exit(self.camera))
Exemple #40
0
    def connect(self):
        gp.gp_camera_exit(self.camera, self.context)

        logger.debug("Trying to connect to the camera...")
        for ic in range(1000):
            logger.debug("   Attempt %i/10" % (ic+1))
            time.sleep(0.2)
            error = gp.gp_camera_init(self.camera, self.context)
            if error == gp.GP_OK:
                # operation completed successfully so exit loop
                self.camera_description = str(gp.check_result(gp.gp_camera_get_summary(self.camera, self.context)))
                logger.debug("Camera connected")
                return True

            # no self.camera, try again in 2 seconds
            gp.gp_camera_exit(self.camera, self.context)

        # raise gp.GPhoto2Error(error)
        logger.debug("Failed to connect camera")
        time.sleep(0.5)
        return False
def main():
        logging.basicConfig(
                format='%(levelname)s: %(name)s: %(message)s', level=logging.CRITICAL)
        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))

        trigger_capture(camera, context, 'image.jpg')

        gp.check_result(gp.gp_camera_exit(camera, context))
        return 0
def main():
    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))
    text = gp.check_result(gp.gp_camera_get_summary(camera, context))
    print('Summary')
    print('=======')
    print(text.text)
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
def main():
    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))
    text = gp.check_result(gp.gp_camera_get_summary(camera, context))
    print('Summary')
    print('=======')
    print(text.text)
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
Exemple #44
0
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))
def capture():
    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
Exemple #46
0
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))
Exemple #47
0
def camera_capture_image(camera, path='/tmp'):
    # initialize camera
    gp.check_result(gp.gp_camera_init(camera))
    # capture a image
    file_path = gp.check_result(gp.gp_camera_capture(
            camera, gp.GP_CAPTURE_IMAGE))
    # store a image
    target = os.path.join(path, 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))
    gp.check_result(gp.gp_file_save(camera_file, target))
    # subprocess.call(['xdg-open', target])
    # exit camera
    gp.check_result(gp.gp_camera_exit(camera))
def main():
    # use Python logging
    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    # open camera connection
    camera = gp.check_result(gp.gp_camera_new())
    context = gp.gp_context_new()
    gp.check_result(gp.gp_camera_init(camera, context))
    # get configuration tree
    config = gp.check_result(gp.gp_camera_get_config(camera, context))
    # find the date/time setting config item and get it
    # name varies with camera driver
    #   Canon EOS350d - 'datetime'
    #   PTP - 'd034'
    for name, fmt in (('datetime', '%Y-%m-%d %H:%M:%S'),
                      ('d034',     None)):
        now = datetime.now()
        OK, datetime_config = gp.gp_widget_get_child_by_name(config, name)
        if OK >= gp.GP_OK:
            widget_type = gp.check_result(gp.gp_widget_get_type(datetime_config))
            if widget_type == gp.GP_WIDGET_DATE:
                raw_value = gp.check_result(
                    gp.gp_widget_get_value(datetime_config))
                camera_time = datetime.fromtimestamp(raw_value)
            else:
                raw_value = gp.check_result(
                    gp.gp_widget_get_value(datetime_config))
                if fmt:
                    camera_time = datetime.strptime(raw_value, fmt)
                else:
                    camera_time = datetime.utcfromtimestamp(float(raw_value))
            print('Camera clock:  ', camera_time.isoformat(' '))
            print('Computer clock:', now.isoformat(' '))
            err = now - camera_time
            if err.days < 0:
                err = -err
                lead_lag = 'ahead'
                print('Camera clock is ahead by',)
            else:
                lead_lag = 'behind'
            print('Camera clock is %s by %d days and %d seconds' % (
                lead_lag, err.days, err.seconds))
            break
    else:
        print('Unknown date/time config item')
    # clean up
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
Exemple #49
0
	def capture(self):

		while True:
			try:
				for i in range(0,20):
					try:
						camera_file = gp.check_result(gp.gp_camera_capture_preview(self.camera, self.context))
						break
					except gp.GPhoto2Error as ex:
						if i < 19:
							continue
					raise
						
				file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
	
				pil_image = Image.open(io.BytesIO(file_data))
				#pil_image.save("testimg2_" + str(i) + ".tif")
				im = np.array(pil_image)
				im = apply_gamma(im, 2.2)
				if self.fpshackiso > 0:
					self.set_config_value_checked('iso', 1600)
					self.set_config_value_checked('iso', 100)
					self.fpshackiso -= 1

				return im, None
	
			except KeyboardInterrupt:
				break
			except gp.GPhoto2Error as ex:
				print "Unexpected error: " + sys.exc_info().__str__()
				print "code:", ex.code
				stacktraces()
				time.sleep(1)
				if ex.code == -7 or ex.code == -1:
					gp.gp_camera_exit(self.camera, self.context)
					self.prepare()
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
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
def main():
    # use Python logging
    logging.basicConfig(format="%(levelname)s: %(name)s: %(message)s", level=logging.WARNING)
    gp.check_result(gp.use_python_logging())
    # open camera connection
    camera = gp.check_result(gp.gp_camera_new())
    context = gp.gp_context_new()
    gp.check_result(gp.gp_camera_init(camera, context))
    # get configuration tree
    config = gp.check_result(gp.gp_camera_get_config(camera, context))
    # find the date/time setting config item and set it
    if set_datetime(config):
        # apply the changed config
        gp.check_result(gp.gp_camera_set_config(camera, config, context))
    else:
        print("Could not set date & time")
    # clean up
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
def main():
    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))
    # required configuration will depend on camera type!
    print('Checking camera config')
    # get configuration tree
    config = gp.check_result(gp.gp_camera_get_config(camera, context))
    # find the image format config item
    OK, image_format = gp.gp_widget_get_child_by_name(config, 'imageformat')
    if OK >= gp.GP_OK:
        # get current setting
        value = gp.check_result(gp.gp_widget_get_value(image_format))
        # make sure it's not raw
        if 'raw' in value.lower():
            print('Cannot preview raw images')
            return 1
    # find the capture size class config item
    # need to set this on my Canon 350d to get preview to work at all
    OK, capture_size_class = gp.gp_widget_get_child_by_name(
        config, 'capturesizeclass')
    if OK >= gp.GP_OK:
        # set value
        value = gp.check_result(gp.gp_widget_get_choice(capture_size_class, 2))
        gp.check_result(gp.gp_widget_set_value(capture_size_class, value))
        # set config
        gp.check_result(gp.gp_camera_set_config(camera, config, context))
    # capture preview image (not saved to camera memory card)
    print('Capturing preview image')
    camera_file = gp.check_result(gp.gp_camera_capture_preview(camera, context))
    file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file))
    # display image
    data = memoryview(file_data)
    print(type(data), len(data))
    print(data[:10].tolist())
    image = Image.open(io.BytesIO(file_data))
    image.show()
    gp.check_result(gp.gp_camera_exit(camera, context))
    return 0
def main():
    # use Python logging
    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    callback_obj = gp.check_result(gp.use_python_logging())
    # open camera connection
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    # get camera details
    abilities = gp.check_result(gp.gp_camera_get_abilities(camera))
    # get configuration tree
    config = gp.check_result(gp.gp_camera_get_config(camera))
    # find the date/time setting config item and set it
    if set_datetime(config, abilities.model):
        # apply the changed config
        gp.check_result(gp.gp_camera_set_config(camera, config))
    else:
        print('Could not set date & time')
    # clean up
    gp.check_result(gp.gp_camera_exit(camera))
    return 0
def main():
    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_list = gp.check_result(gp.gp_camera_autodetect(context))
#    gp.check_result(gp.gp_camera_init(camera, context))
    
#    camera_list = GetCameraList(context)


    # loop through camera list
    for index, (name, addr) in enumerate(camera_list):
        print('Processing camera {:d}:  {:s}  {:s}'.format(index, addr, name))

    # search ports for camera port name and match to this iteration
        port_info_list = gp.check_result(gp.gp_port_info_list_new())
        gp.check_result(gp.gp_port_info_list_load(port_info_list))
        idx = gp.check_result(gp.gp_port_info_list_lookup_path(port_info_list, addr))

    # open this camera and associated context
        camera = gp.check_result(gp.gp_camera_new())
        gp.check_result(gp.gp_camera_set_port_info(camera,port_info_list[idx]))
        gp.check_result(gp.gp_camera_init(camera,context))

    # get camera configuration
        config = gp.check_result(gp.gp_camera_get_config(camera,context))

    # grab current value of imageformat and change to JPG
        image_format_old = get_config_value(config,'imageformat')
        set_config_value(camera,config,context,'imageformat',jpgFormat)
        image_format = get_config_value(config,'imageformat')

        print('Changed image format from {:s} to {:s}'.format(image_format_old,image_format))

    # close this camera
        gp.check_result(gp.gp_camera_exit(camera,context))
        
    return 0
def main():
    # use Python logging
    logging.basicConfig(
        format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
    callback_obj = gp.check_result(gp.use_python_logging())
    # open camera connection
    camera = gp.check_result(gp.gp_camera_new())
    gp.check_result(gp.gp_camera_init(camera))
    # 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'))
    # print current setting
    value = gp.check_result(gp.gp_widget_get_value(capture_target))
    print('Current setting:', value)
    # print possible settings
    for n in range(gp.check_result(gp.gp_widget_count_choices(capture_target))):
        choice = gp.check_result(gp.gp_widget_get_choice(capture_target, n))
        print('Choice:', n, choice)
    # clean up
    gp.check_result(gp.gp_camera_exit(camera))
    return 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
Exemple #58
0
 def release(self):
     self.log("Released")
     gp.check_result(gp.gp_camera_exit(self.camera, self.context))
Exemple #59
0
	def cmd(self, cmd, x = None, y = None):
		try:
			if cmd in ["f-3", "f-2", "f-1", "f+3", "f+2", "f+1"]:
				if self.focuser is not None:
					self.focuser.cmd(cmd)
				if self.focuser is None or self.focuser.testmode:
					if cmd == "f-3":
						self.set_config_choice('manualfocusdrive', 2)
					if cmd == "f-2":
						self.set_config_choice('manualfocusdrive', 1)
					if cmd == "f-1":
						self.set_config_choice('manualfocusdrive', 0)
					if cmd == "f+1":
						self.set_config_choice('manualfocusdrive', 4)
					if cmd == "f+2":
						self.set_config_choice('manualfocusdrive', 5)
					if cmd == "f+3":
						self.set_config_choice('manualfocusdrive', 6)
			
			if cmd == "z1":
        
				zoom = 5
							
				self.x = x * zoom - self.zoom_shape[1] / 2
				self.y = y * zoom - self.zoom_shape[0] / 2
				self.set_config_value('eoszoomposition', "%d,%d" % (self.x, self.y))
				self.set_config_value('eoszoom', '5')
				time.sleep(.2)
				self.do_fps_hack()
				im, t = self.capture()
				while im.shape[0] != self.zoom_shape[0] or im.shape[1] != self.zoom_shape[1]:
					print "zoom shape", im.shape, self.zoom_shape
					im, t = self.capture()
				
        
			if cmd == "z0":
				zoom = 1
				self.set_config_value('eoszoom', '1')
				time.sleep(.2)
				self.do_fps_hack()
				im, t = self.capture()
				while im.shape[0] != self.shape[0] or im.shape[1] != self.shape[1]:
					print "shape", im.shape, self.shape
					im, t = self.capture()
				
		
			if cmd == 'left':
				self.x = max(100, self.x - 100)
				self.set_config_value('eoszoomposition', "%d,%d" % (self.x, self.y))
			if cmd == 'right':
				self.x = self.x + 100
				self.set_config_value('eoszoomposition', "%d,%d" % (self.x, self.y))
			if cmd == 'up':
				self.y = max(100, self.y - 100)
				self.set_config_value('eoszoomposition', "%d,%d" % (self.x, self.y))
			if cmd == 'down':
				self.y = self.y + 100
				self.set_config_value('eoszoomposition', "%d,%d" % (self.x, self.y))
		
			if cmd.startswith('iso-'):
				self.status['iso'] = cmd[len('iso-'):]
        
			if cmd.startswith('test-iso-'):
				self.status['test-iso'] = cmd[len('test-iso-'):]
        
			if cmd.startswith('exp-sec-'):
				try:
					self.status['exp-sec'] = int(cmd[len('exp-sec-'):])
				except:
					pass
        
			if cmd.startswith('test-exp-sec-'):
				try:
					self.status['test-exp-sec'] = int(cmd[len('test-exp-sec-'):])
				except:
					pass
			
			if cmd.startswith('f-number-'):
				self.set_config_value('aperture', cmd[len('f-number-'):])
				self.status['f-number'] = self.get_config_value('aperture')
        
			
		except gp.GPhoto2Error as ex:
			print "Unexpected error: " + sys.exc_info().__str__()
			stacktraces()
			time.sleep(1)
			if ex.code == -7 or ex.code == -1:
				gp.gp_camera_exit(self.camera, self.context)
				self.prepare()
Exemple #60
0
	def shutdown(self):
		time.sleep(1)
		self.set_config_value_checked('eosremoterelease', 'Release Full')
		self.set_config_value('viewfinder', 0)
		gp.check_result(gp.gp_camera_exit(self.camera, self.context))