def __init__(self, config_changed, camera_config, parent=None): QtGui.QWidget.__init__(self, parent) self.setLayout(QtGui.QFormLayout()) if gp.check_result(gp.gp_widget_get_readonly(camera_config)): self.setDisabled(True) child_count = gp.check_result(gp.gp_widget_count_children(camera_config)) if child_count < 1: return tabs = None for n in range(child_count): child = gp.check_result(gp.gp_widget_get_child(camera_config, n)) label = gp.check_result(gp.gp_widget_get_label(child)) child_type = gp.check_result(gp.gp_widget_get_type(child)) if child_type == gp.GP_WIDGET_SECTION: if not tabs: tabs = QtGui.QTabWidget() self.layout().insertRow(0, tabs) tabs.addTab(SectionWidget(config_changed, child), label) elif child_type == gp.GP_WIDGET_TEXT: self.layout().addRow(label, TextWidget(config_changed, child)) elif child_type == gp.GP_WIDGET_RANGE: self.layout().addRow(label, RangeWidget(config_changed, child)) elif child_type == gp.GP_WIDGET_TOGGLE: self.layout().addRow(label, ToggleWidget(config_changed, child)) elif child_type == gp.GP_WIDGET_RADIO: self.layout().addRow(label, RadioWidget(config_changed, child)) elif child_type == gp.GP_WIDGET_MENU: self.layout().addRow(label, MenuWidget(config_changed, child)) elif child_type == gp.GP_WIDGET_DATE: self.layout().addRow(label, DateWidget(config_changed, child)) else: print('Cannot make widget type %d for %s' % (child_type, label))
def close(self): """ Close camera connection :return: """ # clean up gp.check_result(gp.gp_camera_exit(self.camera, self.context))
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)
def timelapse(frames, inter): # Params frames = frames inter = inter # Open Camera context = gp.Context() camera = gp.Camera() camera.init(context) # Capture Image for i in range(0, frames): print i file_path = gp.check_result(camera.capture(gp.GP_CAPTURE_IMAGE, context)) print ("Camera file path: " + file_path.folder + file_path.name) target = os.path.join("/home/pi/timelapse/", file_path.name + str(i)) camera_file = gp.check_result( camera.file_get(file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL, context) ) gp.check_result(gp.gp_file_save(camera_file, target)) # Show the Image sub = subprocess.Popen(["fim", target], preexec_fn=os.setsid) time.sleep(10) os.killpg(sub.pid, signal.SIGTERM) time.sleep(inter - 10) # Exit session camera.exit(context)
def new_value(self): if sys.version_info[0] < 3: value = unicode(self.text()).encode('utf-8') else: value = str(self.text()) gp.check_result(gp.gp_widget_set_value(self.config, value)) self.config_changed()
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))
def main(): logging.basicConfig(format="%(levelname)s: %(name)s: %(message)s", level=logging.WARNING) gp.check_result(gp.use_python_logging()) context = gp.Context() camera = gp.Camera() camera.init(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(" ")) camera.exit(context) return 0
def __init__(self): print "init AstroCamCanon" gp.check_result(gp.use_python_logging()) self.context = gp.gp_context_new() self.camera = gp.check_result(gp.gp_camera_new()) print "config" camera_config = gp.check_result(gp.gp_camera_get_config(self.camera, self.context)) child_count = gp.check_result(gp.gp_widget_count_children(camera_config)) print child_count for n in range(child_count): try: print "============" child = gp.check_result(gp.gp_widget_get_child(camera_config, n)) name = gp.check_result(gp.gp_widget_get_name(child)) print name chtype = gp.check_result(gp.gp_widget_get_type(child)) print chtype ro = gp.check_result(gp.gp_widget_get_readonly(child)) print ro cdildcen = gp.check_result(gp.gp_widget_count_children(child)) print cdildcen except Exception, e: print e
async def capture_preview(self): """ Capture preview image (doesn't engage curtain) """ with (await self._lock): file = gp.check_result(gp.gp_camera_capture_preview(self._camera, self._context)) data = gp.check_result(gp.gp_file_get_data_and_size(file)) return bytes(data)
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_camera_file_get( camera, folder, name, gp.GP_FILE_TYPE_NORMAL, context)) gp.check_result(gp.gp_file_save(camera_file, dest)) gp.check_result(gp.gp_camera_exit(camera, context)) return 0
def main(): def callback(level, domain, string, data=None): print('Callback: level =', level, ', domain =', domain, ', string =', string) if data: print('Callback data:', data) camera = gp.Camera() # add our own callback print('Using Python callback') print('=====================') callback_obj = gp.check_result( gp.gp_log_add_func(gp.GP_LOG_VERBOSE, callback)) print('callback_obj', callback_obj) # create an error gp.gp_camera_init(camera) # uninstall callback del callback_obj # add our own callback, with data print('Using Python callback, with data') print('================================') callback_obj = gp.check_result( gp.gp_log_add_func(gp.GP_LOG_VERBOSE, callback, 'some data')) print('callback_obj', callback_obj) # create an error gp.gp_camera_init(camera) # uninstall callback del callback_obj # set gphoto2 to use Python's logging directly print('Using Python logging') print('====================') logging.basicConfig( format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING) callback_obj = gp.check_result(gp.use_python_logging()) # create an error gp.gp_camera_init(camera) return 0
def __take_preview_pic(self): print 'camera.__take_preview_pic' image = QtGui.QImage() if not self.use_real_camera: image.load('./data/preview.jpg') else: camera_file = gp.check_result(gp.gp_camera_capture_preview(self.__camera, self.__context)) file_data = gp.check_result(gp.gp_file_get_data_and_size(camera_file)) image_data = io.BytesIO(file_data) self.__pub_image(image_data.getvalue()) image.loadFromData(image_data.getvalue()) if self.__count_down_start!=None and self.draw_countdown: p = QtGui.QPainter(image) p.setPen(Camera.countdown_pen) size = 180 p.setFont(QtGui.QFont("Arial",size)) p.drawText((image.width()+size)/2, (image.height()+size)/2, '%i'%(self.__count_down_n)) p.end() image = image.scaledToHeight(self.__preview_height, transformMode=QtCore.Qt.SmoothTransformation) self.new_preview_image.emit(image.transformed(self.__preview_transform))
def main(): logging.basicConfig( format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING) gp.check_result(gp.use_python_logging()) context = gp.Context() camera = gp.Camera() camera.init(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) print() print('Exif data') print('=========') for path in files: if os.path.splitext(path)[1].lower() != '.jpg': continue exif = get_file_exif(camera, context, path) for key in ('EXIF DateTimeOriginal', 'EXIF LensModel', 'Image Copyright'): if key in exif: print(key, ':', exif[key]) break print() camera.exit(context) return 0
def main(): # set up our camera. camera, context = setup() # grab a single test image. capture_image(camera, context, "crap.jpg") # Get the configuration of the camera config = gp.check_result(gp.gp_camera_get_config(camera, context)) # Pythonify and print the configuration of the camera so # we can see what parameters we can play with. pconfig = recurse_config(config) print_config_dict(pconfig) # Put the camera in AV mode, or aperture priority. # Camera needs this to fiddle with aperture. set_config(camera, context, config, ["capturesettings", "autoexposuremode"], "AV") count = 0 # for all of the available aperture settings... for param in pconfig["capturesettings"]["aperture"]: # get the camera configuration config = gp.check_result(gp.gp_camera_get_config(camera, context)) # set the new configuration set_config(camera, context, config, ["capturesettings", "aperture"], param) # and capture an image. fname = "Capture{:0>5}.jpg".format(count) capture_image(camera, context, fname) count += 1
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
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))
def set_config(self, config_name, value): self.log("Setting '{}' to '{}'".format(config_name, value)) config, widget = self._get_widget(config_name) gp.check_result(gp.gp_widget_set_value(widget, value)) gp.check_result( gp.gp_camera_set_config(self.camera, config, self.context)) self.log("Set '{}' to '{}'".format(config_name, value))
def initCam(): global context, 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 = gp.check_result(gp.gp_camera_new()) gp.check_result(gp.gp_camera_init(camera, context))
def get_config_value(self, name): config = gp.check_result(gp.gp_camera_get_config(self.camera, self.context)) OK, widget = gp.gp_widget_get_child_by_name(config, name) if OK >= gp.GP_OK: # set value value = gp.check_result(gp.gp_widget_get_value(widget)) print "get %s => %s" % (name, value) return value
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)
def set_config_value (camera, config, context, config_name, value): OK, config_child = gp.gp_widget_get_child_by_name(config,config_name) if OK >= gp.GP_OK: gp.check_result(gp.gp_widget_set_value(config_child, value)) gp.check_result(gp.gp_camera_set_config(camera, config, context)) return True else: return False
def _get_config_value(self, config, name): error, conf_result = gp.gp_widget_get_child_by_name(config, name) gp.check_result(error) error, result = gp.gp_widget_get_value(conf_result) gp.check_result(error) return result
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
def walk(self, root=None): (camera, context) = self.camera root = root if root != None else "/" dirs = [name[0] for name in gp.check_result(gp.gp_camera_folder_list_folders(camera, root, context))] files = [name[0] for name in gp.check_result(gp.gp_camera_folder_list_files(camera, root, context))] yield (files, dirs, root) for directory in dirs: new_root = os.path.join(root, directory) for result in self.walk(root=new_root): yield result
def run_autofocus(self, active): value = 0 if active: value = 1 error, config = gp.gp_camera_get_config(self.camera) gp.check_result(error) self._set_config_value(self.camera, config, "autofocus", value)
def __init__(self, config_changed, config, parent=None): QtGui.QCheckBox.__init__(self, parent) self.config_changed = config_changed self.config = config if gp.check_result(gp.gp_widget_get_readonly(config)): self.setDisabled(True) assert gp.check_result(gp.gp_widget_count_children(config)) == 0 value = gp.check_result(gp.gp_widget_get_value(config)) self.setChecked(value != 0) self.clicked.connect(self.new_value)
def set_autofocus(self, enabled): value = "Manual" if enabled: value = "Automatic" error, config = gp.gp_camera_get_config(self.camera) gp.check_result(error) self._set_config_value(config, "focusmode", value)
def __walk_config(self, widget, cfg, pname=''): child_count = gp.check_result(gp.gp_widget_count_children(widget)) for n in range(child_count): child = gp.check_result(gp.gp_widget_get_child(widget, n)) label = gp.check_result(gp.gp_widget_get_label(child)) name = gp.check_result(gp.gp_widget_get_name(child)) child_type = gp.check_result(gp.gp_widget_get_type(child)) _name = pname + '/' +name _cfg = {'_type':child_type,'_widget':child,'_label':label} if child_type != gp.GP_WIDGET_SECTION: value = gp.check_result(gp.gp_widget_get_value(child)) print label, name, value _cfg['_value'] = value if child_type == gp.GP_WIDGET_RADIO: _cfg['_choice'] = [] choice_count = gp.check_result(gp.gp_widget_count_choices(child)) for n in range(choice_count): choice = gp.check_result(gp.gp_widget_get_choice(child, n)) if choice: _cfg['_choice'].append(choice) if child_type == gp.GP_WIDGET_RANGE: lo, hi, inc = gp.check_result(gp.gp_widget_get_range(child)) _cfg['_lo'] = lo _cfg['_hi'] = hi _cfg['_inc'] = inc cfg[_name]=_cfg self.__walk_config(child,cfg,pname=_name)
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
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 _post_process_capture(self, capture_path): gp_path = self._captures[capture_path] camera_file = gp.check_result( gp.gp_camera_file_get(self._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.resolution, 'outer'), Image.ANTIALIAS) image = image.crop( sizing.new_size_by_croping(image.size, self.resolution)) if self._capture_hflip: image = image.transpose(Image.FLIP_LEFT_RIGHT) image.save(capture_path) return image
def gp_camera_connected(): """Return True if a camera compatible with gPhoto2 is found. """ if not gp: return False # gPhoto2 is not installed if hasattr(gp, 'gp_camera_autodetect'): # gPhoto2 version 2.5+ cameras = gp.check_result(gp.gp_camera_autodetect()) else: port_info_list = gp.PortInfoList() port_info_list.load() abilities_list = gp.CameraAbilitiesList() abilities_list.load() cameras = abilities_list.detect(port_info_list) if cameras: return True return False
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.Camera() camera.init() # get configuration tree config = camera.get_config() # 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 = datetime_config.get_type() raw_value = datetime_config.get_value() if widget_type == gp.GP_WIDGET_DATE: camera_time = datetime.fromtimestamp(raw_value) else: 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 camera.exit() return 0
def setup(): """ Attempt to attach to a gphoto device and grab the camera and context. Return the results. """ 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 text.text return camera, context
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))
def detect_cameras(self): """ Detects the connected cameras and if the ownername matches with `LEFTNAME` or `RIGHTNAME`, it will be stored under the variable `cameras` """ _cameras = self.context.camera_autodetect() msg = [(False, "None"), (False, "None")] if len(_cameras) == 0: raise Exception("Unable to find any camera") # Stores the left and right camera ports = gp.PortInfoList() ports.load() for index, (name, addr) in enumerate(_cameras): logger.debug("Count: {}, Name: {}, Addr: {}".format( index, name, addr)) # Get the ports and search for the camera idx = ports.lookup_path(addr) try: camera = gp.Camera() camera.set_port_info(ports[idx]) camera.init(self.context) # Check if the ownername matches to given values ownername = self._get_config("ownername", camera) abilities = gp.check_result(gp.gp_camera_get_abilities(camera)) except gp.GPhoto2Error as error: logger.error(str(error)) else: if ownername == self.LEFTNAME: camera._camera_name = self.LEFTNAME camera._camera_id = CameraID.LEFT self.cameras[CameraID.LEFT] = camera msg[CameraID.LEFT] = True, str(abilities.model) logger.info("Connected: " + str(abilities.model)) elif ownername == self.RIGHTNAME: camera._camera_name = self.RIGHTNAME camera._camera_id = CameraID.RIGHT self.cameras[CameraID.RIGHT] = camera msg[CameraID.RIGHT] = True, str(abilities.model) logger.info("Connected: " + str(abilities.model)) return self.connected, msg
def __init__(self, iso=200, resolution=(1920, 1080), rotation=0, flip=False, delete_internal_memory=False, init=True): BaseCamera.__init__(self, resolution, delete_internal_memory) self._gp_logcb = gp.check_result( gp.gp_log_add_func(gp.GP_LOG_VERBOSE, gp_log_callback)) self._preview_compatible = True self._preview_viewfinder = False self._preview_hflip = False self._capture_hflip = flip self._rotation = rotation self._iso = iso if init: self._initialize()
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
def autodetect_cameras( context: gp.Context, suppress_errors: bool = True) -> Union[gp.CameraList, List]: """ Do camera auto detection for multiple versions of gphoto2-python Version 2.2.0 of gphoto2 introduces a COMPATIBILITY CHANGE: Removed Context.camera_autodetect method. Was quickly reintroduced in 2.2.1, but is due for removal. :return: CameraList of model and port """ try: return gp.check_result(gp.gp_camera_autodetect(context)) except Exception: if not suppress_errors: raise return []
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
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
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.Camera() camera.init() 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) print() print('Exif data via GP_FILE_TYPE_NORMAL') print('=================================') for path in files: if os.path.splitext(path)[1].lower() != '.jpg': continue md = get_file_exif_normal(camera, path) for key in ('Exif.Photo.DateTimeOriginal', 'Exif.Image.Model', 'Exif.Image.Copyright'): if key in md.get_exif_tags(): print(key, ':', md.get_tag_string(key)) break print() print('Exif data via GP_FILE_TYPE_EXIF') print('===============================') for path in files: if os.path.splitext(path)[1].lower() != '.jpg': continue md = get_file_exif_metadata(camera, path) for key in ('Exif.Photo.DateTimeOriginal', 'Exif.Image.Model', 'Exif.Image.Copyright'): if key in md.get_exif_tags(): print(key, ':', md.get_tag_string(key)) break print() camera.exit() return 0
def _specific_initialization(self): """Camera initialization. """ self._gp_logcb = gp.check_result( gp.gp_log_add_func(gp.GP_LOG_VERBOSE, gp_log_callback)) abilities = self._cam.get_abilities() self._preview_compatible = gp.GP_OPERATION_CAPTURE_PREVIEW ==\ abilities.operations & gp.GP_OPERATION_CAPTURE_PREVIEW if not self._preview_compatible: LOGGER.warning( "The connected DSLR camera is not compatible with preview") else: try: self.get_config_value('actions', 'viewfinder') self._preview_viewfinder = True except ValueError: self._preview_viewfinder = False self.set_config_value('imgsettings', 'iso', self.preview_iso) self.set_config_value('settings', 'capturetarget', 'Memory card')
def get_thumbnail( self, dir_name: str, file_name: str, ignore_embedded_thumbnail=False, cache_full_filename: Optional[str] = None, ) -> Optional[bytes]: """ :param dir_name: directory on the camera :param file_name: the photo or video :param ignore_embedded_thumbnail: if True, do not retrieve the embedded thumbnail :param cache_full_filename: full path including filename where the thumbnail will be saved. If none, will not save it. :return: thumbnail in bytes format, which will be full resolution if the embedded thumbnail is not selected """ if self.can_fetch_thumbnails and not ignore_embedded_thumbnail: get_file_type = gp.GP_FILE_TYPE_PREVIEW else: get_file_type = gp.GP_FILE_TYPE_NORMAL camera_file = self._get_file(dir_name, file_name, cache_full_filename, get_file_type) try: thumbnail_data = gp.check_result( gp.gp_file_get_data_and_size(camera_file)) except gp.GPhoto2Error as ex: logging.error( "Error getting image %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 thumbnail_data: data = memoryview(thumbnail_data) return data.tobytes()
def __init__(self, config_changed, camera_config, parent=None): QtGui.QWidget.__init__(self, parent) self.setLayout(QtGui.QFormLayout()) if gp.check_result(gp.gp_widget_get_readonly(camera_config)): self.setDisabled(True) child_count = gp.check_result( gp.gp_widget_count_children(camera_config)) if child_count < 1: return tabs = None for n in range(child_count): child = gp.check_result(gp.gp_widget_get_child(camera_config, n)) label = gp.check_result(gp.gp_widget_get_label(child)) name = gp.check_result(gp.gp_widget_get_name(child)) label = '{} ({})'.format(label, name) child_type = gp.check_result(gp.gp_widget_get_type(child)) if child_type == gp.GP_WIDGET_SECTION: if not tabs: tabs = QtGui.QTabWidget() self.layout().insertRow(0, tabs) tabs.addTab(SectionWidget(config_changed, child), label) elif child_type == gp.GP_WIDGET_TEXT: self.layout().addRow(label, TextWidget(config_changed, child)) elif child_type == gp.GP_WIDGET_RANGE: self.layout().addRow(label, RangeWidget(config_changed, child)) elif child_type == gp.GP_WIDGET_TOGGLE: self.layout().addRow(label, ToggleWidget(config_changed, child)) elif child_type == gp.GP_WIDGET_RADIO: choice_count = gp.check_result( gp.gp_widget_count_choices(child)) if choice_count > 3: widget = MenuWidget(config_changed, child) else: widget = RadioWidget(config_changed, child) self.layout().addRow(label, widget) elif child_type == gp.GP_WIDGET_MENU: self.layout().addRow(label, MenuWidget(config_changed, child)) elif child_type == gp.GP_WIDGET_DATE: self.layout().addRow(label, DateWidget(config_changed, child)) else: print('Cannot make widget type %d for %s' % (child_type, label))
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)) # required configuration will depend on camera type! print('Checking camera config') # get configuration tree config = gp.check_result(gp.gp_camera_get_config(camera)) # 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
def waitForCamera(context): showText(AREA_PREVIEW, "Warte auf Kamera ") pygame.display.flip() camera = gp.check_result(gp.gp_camera_new()) err = gp.gp_camera_init(camera, context) if (err < gp.GP_OK): if err != gp.GP_ERROR_MODEL_NOT_FOUND: # some other error we can't handle here raise gp.GPhoto2Error(err) return # 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(): raise gp.GPhoto2Error('Cannot preview raw images') # 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)) OK, txt = gp.gp_camera_get_summary(camera, context) infod = txToDict(txt.text) showText(AREA_PREVIEW, infod.get('Model')) info.camera = infod.get('Model') pygame.display.flip() return camera
def get_THM_file(self, full_THM_name: str) -> Optional[bytes]: """ Get THM thumbnail from camera :param full_THM_name: path and file name of the THM file :return: THM in raw bytes """ dir_name, file_name = os.path.split(full_THM_name) camera_file = self._get_file(dir_name, file_name) try: thumbnail_data = gp.check_result( gp.gp_file_get_data_and_size(camera_file)) except gp.GPhoto2Error as ex: logging.error('Error getting THM file %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 thumbnail_data: data = memoryview(thumbnail_data) return data.tobytes()
def main(): def callback(level, domain, string, data=None): print('Callback: level =', level, ', domain =', domain, ', string =', string) if data: print('Callback data:', data) context = gp.Context() camera = gp.Camera() # add our own callback print('Using Python callback') print('=====================') callback_id = gp.check_result( gp.gp_log_add_func(gp.GP_LOG_VERBOSE, callback)) print('callback_id', callback_id) # create an error gp.gp_camera_init(camera, context) # uninstall callback gp.check_result(gp.gp_log_remove_func(callback_id)) # add our own callback, with data print('Using Python callback, with data') print('================================') callback_id = gp.check_result( gp.gp_log_add_func(gp.GP_LOG_VERBOSE, callback, 'some data')) print('callback_id', callback_id) # create an error gp.gp_camera_init(camera, context) # uninstall callback gp.check_result(gp.gp_log_remove_func(callback_id)) # set gphoto2 to use Python's logging directly print('Using Python logging') print('====================') logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING) gp.check_result(gp.use_python_logging()) # create an error gp.gp_camera_init(camera, context) return 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 _setupCamera(self): self._ctxt = gp.Context() self._cap = gp.Camera() self._cap.init(self._ctxt) logging.info('Camera summary: %s', str(self._cap.get_summary(self._ctxt))) try: # get configuration tree config = self._cap.get_config() # make sure camera format is not set to raw imageformat = config.get_child_by_name('imageformat') self._imageformat = imageformat.get_value() if 'raw' in self._imageformat.lower(): imageformat.set_value('Large Fine JPEG') imageformatsd = config.get_child_by_name('imageformatsd') self._imageformatsd = imageformatsd.get_value() if 'raw' in self._imageformatsd.lower(): imageformatsd.set_value('Large Fine JPEG') # make sure autopoweroff is disabled # this doesn't seem to work # autopoweroff = config.get_child_by_name('autopoweroff') # self._autopoweroff = autopoweroff.get_value() # logging.info('autopoweroff: {}'.format(self._autopoweroff)) # if int(self._autopoweroff) > 0: # autopoweroff.set_value('0') # apply configuration and print current config self._cap.set_config(config) shutterspeed = gp.check_result( gp.gp_widget_get_child_by_name(config, 'shutterspeed')) self._shutter = shutterspeed.get_value() except BaseException as e: logging.warn('Error while changing camera settings: {}.'.format(e)) self._printConfig(self._cap.get_config())
def get_gp_camera_proxy(port=None): """Return camera proxy if a gPhoto2 compatible camera is found else return None. .. note:: try to kill any process using gPhoto2 as it may block camera access. :param port: look on given port number :type port: str """ if not gp: return None # gPhoto2 is not installed pkill('*gphoto2*') if hasattr(gp, 'gp_camera_autodetect'): # gPhoto2 version 2.5+ cameras = gp.check_result(gp.gp_camera_autodetect()) else: port_info_list = gp.PortInfoList() port_info_list.load() abilities_list = gp.CameraAbilitiesList() abilities_list.load() cameras = abilities_list.detect(port_info_list) if cameras: LOGGER.debug("Found gPhoto2 cameras on ports: '%s'", "' / '".join([p for _, p in cameras])) # Initialize first camera proxy and return it camera = gp.Camera() if port is not None: port_info_list = gp.PortInfoList() port_info_list.load() idx = port_info_list.lookup_path(port) camera.set_port_info(port_info_list[idx]) try: camera.init() return camera except gp.GPhoto2Error as ex: LOGGER.warning("Could not connect gPhoto2 camera: %s", ex) return None
def capture(self, req): rospy.loginfo('Capturing panorama') if not self.single_capture(): rospy.logerr('Could not trigger Richo Theta, retrying in 1s') rospy.sleep(1) while not self.single_capture(): rospy.logerr( 'Could not trigger Richo Theta, resetting the usb driver. Is the camera switched on and set to still image capture mode?' ) reset_usb_driver() self.init_camera() rospy.sleep(2) # Construct image file_data = gp.check_result( gp.gp_file_get_data_and_size(self.camera_file)) img = Img.open(io.BytesIO(file_data)) rospy.loginfo('Panorama captured!') image = Image(height=img.height, width=img.width, encoding="rgb8", is_bigendian=False, step=img.width * 3, data=img.tobytes()) image.header.stamp = self.stamp image.header.frame_id = 'map' #TODO maybe add something sensible here self.pub_image.publish(image) rospy.loginfo('Panorama published!') # Avoid running out of space. Update: No need: Device holds approx 4,800 photos #try: # self.camera.file_delete(self.file_path.folder, self.file_path.name) #except: # rospy.logwarn('Delete photo on the Ricoh Theta failed. Camera may eventually run out of storage.') return TriggerResponse(success=True, message=self.file_path.folder + '/' + self.file_path.name)
def rsync_all_cameras(target_dir): target_path = pathlib.Path(target_dir) cameras = gp.check_result(gp.gp_camera_autodetect()) n = 0 number_of_copies = 0 for name, addr in cameras: log.info("Camera[{index}] = {name}, {address}".format(index=n, name=name, address=addr)) n += 1 log.info("Starting backup for %s to %s", name, target_path) target_camera_path = target_path.joinpath(_get_unique_id(name)) camera = _get_camera(addr) copies_for_camera = rsync_camera(camera, target_camera_path) camera.exit() log.info("Finished backup for %s, %s files copied", name, number_of_copies) number_of_copies += copies_for_camera return number_of_copies
def main(): """ main function interface :return: nothing """ parser = argparse.ArgumentParser(description='parse the path and filename') parser.add_argument('--DSLRPICDIR', help="DSLR PIC DIR", required=True) parser.add_argument('--FILENAME', help="FILE NAME", required=True) args = parser.parse_args() # initialize DSLR_pics logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING) callback_obj = gp.check_result(gp.use_python_logging()) DSLR = gp.Camera() DSLR.init() print('RPi Bird Feeder -> DSLR Ready') DSLR_path = DSLR.capture(gp.GP_CAPTURE_IMAGE) target = os.path.join(args.DSLRPICDIR, args.FILENAME) DSLR_file = DSLR.file_get(DSLR_path.folder, DSLR_path.name, gp.GP_FILE_TYPE_NORMAL) DSLR_file.save(target) DSLR.exit()
def preview(): 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)) # capture preview image (not saved to camera memory card) print('Capturing preview image') camera_file = gp.check_result(gp.gp_camera_capture_preview(camera)) 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() return 0
def slurpd(self, device, apply_state=True): if apply_state: self.apply_state(device) try: logger.info(device) 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: logger.warn(ex) self.broadcast(channel=self.channels['exception'], message=str(ex), subs=[{ "function": sys._getframe().f_code.co_name }]) return contents
def set_iso(self,choice): count = gp.check_result(gp.gp_widget_count_choices(self.iso)) if choice < 0 or choice > count-1: print('choice max is:',count) print('set_iso: choice out of range!') return error, value = gp.gp_widget_get_choice(self.iso, choice) error = gp.gp_widget_set_value(self.iso,value) if error !=0: print('set_iso: cannot set value!') error = gp.gp_camera_set_config(self.camera, self.config, self.context) if error !=0: print('set_iso: cannot push config!') return value
def capture_image(): # 拍照 file_path = gp.check_result( gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE)) print('file_path==', file_path) # 存照片路径 global imgPath target = os.path.join('imgs', file_path.name) imgPath = target # 相机文件 camera_file = gp.check_result( gp.gp_camera_file_get(camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL)) print('camera_file==', camera_file) # 保存 gp.check_result(gp.gp_file_save(camera_file, target)) gp.check_result(gp.gp_camera_exit(camera)) capture_and_resize_image()