def discover(self): method = "gphoto2" discoverable = [] context = gp.Context() try: for name, addr in context.camera_autodetect(): now = str(datetime.datetime.now()) c = gp.Context() camera = gp.Camera() camera.init(c) camera_summary = camera.get_summary(c) serial = "" for t in str(camera_summary).split("\n"): if ("Serial Number:") in t: serial = t.partition(":")[-1].strip() # print(serial) break camera.exit(c) discoverable.append({ "name": name, "address": addr, "uid": serial, "discovery": method, "lastseen": now, }) except Exception as ex: print(ex) return discoverable
def detectCamera(): print("Camera::detectCamera()") try: cams = list() # Get the context of the camera. context = gp.Context() if hasattr(gp, 'gp_camera_autodetect'): # gphoto2 version 2.5+ cameras = context.camera_autodetect() else: port_info_list = gp.PortInfoList() port_info_list.load() abilities_list = gp.CameraAbilitiesList() abilities_list.load(context) cameras = abilities_list.detect(port_info_list, context) for name, port in cameras: cams.append({"name" : name, "port" : port}) return(cams) except Exception as e: print("Error occured in Camera::detectCamera()") print(str(e))
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))) # 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) self._printConfig(self._cap.get_config())
def __init__(self): self.context = gp.Context() self.pool = ThreadPool(2) self.cameras = [None, None] self.connected = (self.cameras[CameraID.LEFT] is not None) and (self.cameras[CameraID.RIGHT] is not None)
def __init__(self): # Initialise the camera self.context = gp.Context() self.camera = gp.Camera() self.camera.init(self.context) # Check image format and determine the correct file suffix self.file_suffix = self.get_file_suffix()
def open(self): context = gp.Context() camera = gp.Camera() camera.init(context) config = camera.get_config(context) # find and check the image format config item ok, image_format = gp.gp_widget_get_child_by_name( config, 'imageformat') if ok >= gp.GP_OK: value = gp.check_result(gp.gp_widget_get_value(image_format)) if value == 'raw': raise RuntimeError('Cannot preview raw images!') # find and set the capture size class config item # this is required for some canon cameras and does not hurt for others ok, capture_size_class = gp.gp_widget_get_child_by_name( config, 'capturesizeclass') if ok >= gp.GP_OK: 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)) gp.check_result(gp.gp_camera_set_config(camera, config, context)) self.context = context self.camera = camera self.config = config
def __init__(self): self.do_init = QtCore.QEvent.registerEventType() QtGui.QMainWindow.__init__(self) self.setWindowTitle("Camera config") self.setMinimumWidth(600) # quit shortcut quit_action = QtGui.QAction('Quit', self) quit_action.setShortcuts(['Ctrl+Q', 'Ctrl+W']) quit_action.triggered.connect(QtGui.qApp.closeAllWindows) self.addAction(quit_action) # main widget widget = QtGui.QWidget() widget.setLayout(QtGui.QGridLayout()) widget.layout().setColumnStretch(0, 1) self.setCentralWidget(widget) # 'apply' button self.apply_button = QtGui.QPushButton('apply changes') self.apply_button.setEnabled(False) self.apply_button.clicked.connect(self.apply_changes) widget.layout().addWidget(self.apply_button, 1, 1) # 'cancel' button quit_button = QtGui.QPushButton('cancel') quit_button.clicked.connect(QtGui.qApp.closeAllWindows) widget.layout().addWidget(quit_button, 1, 2) # defer full initialisation (slow operation) until gui is visible self.context = gp.Context() self.camera = gp.Camera() QtGui.QApplication.postEvent( self, QtCore.QEvent(self.do_init), Qt.LowEventPriority - 1)
def __init__(self): Gtk.Window.__init__(self, title='Preview') box = Gtk.Box() self.files = FileManager() box.add(self.files) self.event_box = Gtk.EventBox() self.image = Gtk.Image() self.event_box.add(self.image) box.add(self.event_box) self.connect('delete-event', Gtk.main_quit) self.camera = gp.Camera() self.context = gp.Context() self.camera.init(self.context) configs = [ (['settings', 'capture'], 1), (['imgsettings', 'iso'], '100') # 1 = ISO 100 ] set_config(self.camera, self.context, configs) time.sleep(1) GLib.idle_add(self.show_preview) self.event_box.connect('button_press_event', self.capture) self.add(box)
def get_camera(serial, serial_to_address=None, context=None): if context is None: context = gp.Context() if serial_to_address is None: serial_to_address = list_camera_serial_numbers(context) if len(serial_to_address) == 0: raise ValueError('No cameras!') if serial == '': print('Using first attached camera!') serial = serial_to_address.keys()[0] print('') print('===============') print('Selected camera:') print('===============') print('Serial Number: ' + serial) print('===============') print('') addr = serial_to_address[serial] camera = gp.Camera() port_info_list = gp.PortInfoList() port_info_list.load() idx = port_info_list.lookup_path(addr) camera.set_port_info(port_info_list[idx]) camera.init(context) return camera
def list_camera_serial_numbers(context=None): if context is None: context = gp.Context() camera_list = get_list_of_availale_cameras(context) if len(camera_list) == 0: return addresses = [camera_info[1] for camera_info in camera_list] camera_types = [camera_info[0] for camera_info in camera_list] serial_numbers = [] serial_to_address = {} for i, addr in enumerate(addresses): camera = gp.Camera() port_info_list = gp.PortInfoList() port_info_list.load() idx = port_info_list.lookup_path(addr) camera.set_port_info(port_info_list[idx]) camera.init(context) txt = str(camera.get_summary(context)) serial = txt.split('Serial Number: ')[1].split('\n')[0] serial_numbers.append(serial) serial_to_address[serial_numbers[i]] = addresses[i] print('Attached Cameras:') print('================') for i in range(len(addresses)): print('Camera ' + str(i + 1)) print(' Serial number: ' + serial_numbers[i]) print(' Make and Model: ' + camera_types[i]) print(' USB Address: ' + addresses[i]) return serial_to_address
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 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 configured_camera(): # Getting the camera context = gp.Context() cam = gp.Camera() cam.init(context) print(cam.get_summary(context)) return cam
def get_summary(self): context = gp.Context() camera = gp.Camera() camera.init(context) text = camera.get_summary(context) logging.debug(str(text)) camera.exit(context) return str(text)
def get_camera_list(): if not gp: return [] context = gp.Context() camera_list = [] for name, addr in context.camera_autodetect(): camera_list.append((name, addr)) camera_list.sort(key=lambda x: x[0]) return camera_list
def get_list_of_availale_cameras(context=None): print('================') if context is None: context = gp.Context() camera_list = [] for name, addr in gp.check_result(gp.gp_camera_autodetect(context)): camera_list.append((name, addr)) if not camera_list: print('No camera detected') return camera_list
def trigger_capture_and_save(camera, destination, context=None): if context is None: context = gp.Context() file_path = gp.check_result( gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE, context)) 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, destination)) return
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))) # get configuration tree config = self._cap.get_config()
def capture_from_camera(filename): camera = gp.Camera() context = gp.Context() context.camera_autodetect() camera.init(context) text = camera.get_summary(context) path = camera.capture(gp.GP_CAPTURE_IMAGE, context) file = camera.file_get(path.folder, path.name, gp.GP_FILE_TYPE_NORMAL, context) file.save(filename) buf = file.get_data_and_size() camera.exit()
def dump_camera_details() -> None: import itertools context = gp.Context() cameras = autodetect_cameras(context) for model, port in cameras: is_mtp_device = camera_is_mtp_device(camera_port=port) c = Camera( model=model, port=port, is_mtp_device=is_mtp_device, context=context, ) if not c.camera_initialized: logging.error("Camera %s could not be initialized", model) else: print() print(c.display_name) print("=" * len(c.display_name)) print(f"\nMTP: {is_mtp_device}") print() if not c.specific_folder_located: print("Specific folder was not located") else: print( "Specific folders:", ", ".join(itertools.chain.from_iterable( c.specific_folders)), ) print("Can fetch thumbnails:", c.can_fetch_thumbnails) sc = c.get_storage_media_capacity() if not sc: print("Unable to determine storage media capacity") else: title = "Storage capacity" print("\n{}\n{}".format(title, "-" * len(title))) for ss in sc: print("\nPath: {}\nCapacity: {}\nFree {}".format( ss.path, format_size_for_user(ss.bytes_total), format_size_for_user(ss.bytes_free), )) sd = c.get_storage_descriptions() if not sd: print("Unable to determine storage descriptions") else: title = "Storage description(s)" print("\n{}\n{}".format(title, "-" * len(title))) for ss in sd: print("\n{}".format(ss)) c.free_camera()
def captureImage(): updateWeb() context = gp.Context() gp.Camera() C = gp.Camera() filename = 'Photoboothphoto_' + str(curTime()) + '.jpg' cap = C.capture(gp.GP_CAPTURE_IMAGE, context) print("Captured " + cap.folder + "/" + cap.name) file = C.file_get(cap.folder, cap.name, gp.GP_FILE_TYPE_NORMAL) gp.gp_file_save(file, filename) return filename
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) text = camera.get_summary(context) print('Summary') print('=======') print(str(text)) camera.exit(context) return 0
def get_cameras(self): if self.cameras is None: self.cameras = {} has_attached_cameras = False for index, (name, addr) in enumerate( gp.check_result(gp.gp_camera_autodetect())): try: has_attached_cameras = True print('{:d}: {:s} {:s}'.format(index, addr, name)) context = gp.Context() camera = gp.Camera() port_info_list = gp.PortInfoList() port_info_list.load() idx = port_info_list.lookup_path(addr) camera.set_port_info(port_info_list[idx]) camera.init(context) config = camera.get_config(context) serial = config.get_child_by_name('eosserialnumber') self.cameras[serial.get_value()] = (camera, { 'port_index': idx }) try: output = config.get_child_by_name('output') output.set_value(output.get_choice(0)) vf = config.get_child_by_name('viewfinder') vf.set_value(0) camera.set_config(config) except Exception as e: print(e) except Exception as e: print(e) if has_attached_cameras == False: print('No Cameras Detected') Qtw.QMessageBox.critical( None, 'Error Detecting Cameras', 'No cameras were detected. Confirm that 4 cameras are attached via USB. Go into config and "Refresh Camera List"' ) else: Qtw.QMessageBox.about( None, 'Cameras Detected', '{} camera(s) attached. If that is not correct confirm they are connected to USB then go into config and "Refresh Camera List"' .format(len(self.cameras))) return self.cameras
def main(): logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING) gp.check_result(gp.use_python_logging()) context = gp.Context() # make a list of all available cameras 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]) # ask user to choose one for index, (name, addr) in enumerate(camera_list): print('{:d}: {:s} {:s}'.format(index, addr, name)) if six.PY3: choice = input('Please input number of chosen camera: ') else: choice = raw_input('Please input number of chosen camera: ') try: choice = int(choice) except ValueError: print('Integer values only!') return 2 if choice < 0 or choice >= len(camera_list): print('Number out of range') return 3 # initialise chosen camera name, addr = camera_list[choice] camera = gp.Camera() # search ports for camera port name port_info_list = gp.PortInfoList() port_info_list.load() idx = port_info_list.lookup_path(addr) camera.set_port_info(port_info_list[idx]) camera.init(context) text = camera.get_summary(context) print('Summary') print('=======') print(str(text)) try: text = camera.get_manual(context) print('Manual') print('=======') print(str(text)) except Exception as ex: print(str(ex)) camera.exit(context) return 0
def camera_init(): exposures = list(range(-4, 5, 2)) context = gp.Context() camera = gp.Camera() camera.exit() camera.init(context) cfg = camera.get_config() cfg.get_child_by_name('imageformat').set_value('Large Fine JPEG') cfg.get_child_by_name('iso').set_value('100') cfg.get_child_by_name('aperture').set_value('8') cfg.get_child_by_name('whitebalance').set_value('Daylight') cfg.get_child_by_name('capturetarget').set_value('Internal RAM') cfg.get_child_by_name('imageformat').set_value('Small Fine JPEG') camera.set_config(cfg) return camera
def discover(self): method = "gphoto2" discoverable = [] context = gp.Context() try: for name, addr in context.camera_autodetect(): now = str(datetime.datetime.now()) c = gp.Context() camera = gp.Camera() camera.init(c) camera_summary = camera.get_summary(c) serial = "" for t in str(camera_summary).split("\n"): if ("Serial Number:") in t: serial = t.partition(":")[-1].strip() logger.info(serial) break camera.exit(c) discoverable.append({ 'name': name, 'address': addr, 'uid': serial, 'discovery': method, 'lastseen': now }) except Exception as ex: logger.warn(ex) self.broadcast(channel=self.channels['exception'], message=ex, subs=[{ "function": sys._getframe().f_code.co_name }]) return discoverable
def __init__(self, model, port_name): self.model = model self.port_name = port_name self.context = gp.Context() # initialise camera self.camera = gp.Camera() # search ports for camera port name port_info_list = gp.PortInfoList() port_info_list.load() idx = port_info_list.lookup_path(self.port_name) self.camera.set_port_info(port_info_list[idx]) self.camera.init(self.context) # check camera is the right model if self.camera.get_abilities().model != self.model: raise RuntimeError('Camera model mismatch')
def __init__(self, port=None): """Create a new printer Keyword arguments: port -- optional string to define the serial port (default None). If no port is given, the first port with an Arduino connected will be selected during initialisation.""" self.port = port self.serial = None self.context = gp.Context() self.camera = gp.Camera() self.ocr = None self.currentPosition = (0, 0) self.convert = None self.tool = config.TOOL self.is_on = False self.safe = False
def context_with_callbacks(): context = gp.Context() callbacks = [] callbacks.append(context.set_idle_func(cb_idle, 'A')) callbacks.append(context.set_error_func(cb_error, 'B')) callbacks.append(context.set_status_func(cb_status, 'C')) callbacks.append(context.set_message_func(cb_message, 'D')) callbacks.append(context.set_question_func(cb_question, 'E')) callbacks.append(context.set_cancel_func(cb_cancel, 'F')) callbacks.append( context.set_progress_funcs(cb_progress_start, cb_progress_update, cb_progress_stop, 'G')) try: yield context finally: del callbacks
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 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, context, 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, context, 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(context) return 0