def get_xtp_dev_list(): """ Make a list of connected xTP devices. xTP device is a general term for PTP and MTP devices. (I named it arbitrarily.) Returns ------- xtp_dev_lis : list List of connected xTP devices -------- Japanese -------- 接続されているxTPデバイスのリストを作成する。 xTPデバイスとは、PTP、MTPデバイスの総称である。(勝手に名付けた。) Returns ------- xtp_dev_lis : list 接続されているxTPデバイスのリスト """ xtp_dev_list = [] for name, addr in gp.check_result(gp.gp_camera_autodetect()): xtp_dev_list.append((name, addr)) if not xtp_dev_list: raise no_xtp_dev() return sorted(xtp_dev_list)
def detect_all_cameras(self): self.disconnect_all() with self._gp_lock: cameras_name_and_port = gp.check_result(gp.gp_camera_autodetect()) # Search ports for camera port name port_info_list = gp.PortInfoList() port_info_list.load() for name, port in cameras_name_and_port: gp_camera = gp.Camera() idx = port_info_list.lookup_path(port) port_info = port_info_list[idx] gp_camera.set_port_info(port_info) try: camera = GpCamera(name=name, port=port, gp_camera=gp_camera, lock=self.sync_lock) with self._cameras_dict_lock: self._cameras_dict[camera.id] = camera except Exception as e: print('Detect all: {0}'.format(e))
def camera_find_by_serialnumber(self, serialnumber): logging.info( 'camera_find_by_serialnumber: ++ sn = {}'.format(serialnumber)) found = False ret = None try: cnt, cameras = gp.gp_camera_autodetect() for i in range(cnt): if len(cameras[i]) == 2: addr = cameras[i][1] port_info_list = gp.PortInfoList() port_info_list.load() idx = port_info_list.lookup_path(addr) c = gp.Camera() c.set_port_info(port_info_list[idx]) c.init() config = c.get_config() OK, sn = gp.gp_widget_get_child_by_name( config, 'serialnumber') if OK >= gp.GP_OK: sn_text = sn.get_value() if serialnumber == sn_text[-len(serialnumber):]: found = True ret = c if not found: c.exit() if found: break except: pass logging.info('camera_find_by_serialnumber: -- ret={}'.format(ret)) return ret
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() if hasattr(gp, 'gp_camera_autodetect'): # gphoto2 version 2.5+ cameras = gp.check_result(gp.gp_camera_autodetect(context)) else: port_info_list = gp.check_result(gp.gp_port_info_list_new()) gp.check_result(gp.gp_port_info_list_load(port_info_list)) abilities_list = gp.check_result(gp.gp_abilities_list_new()) gp.check_result(gp.gp_abilities_list_load(abilities_list, context)) cameras = gp.check_result( gp.gp_abilities_list_detect(abilities_list, port_info_list, context)) n = 0 for name, value in cameras: print('camera number', n) print('===============') print(name) print(value) print() n += 1 return 0
def main(): # use Python logging logging.basicConfig(filename= logFile + '.log', format='%(asctime)s: %(levelname)s: %(name)s: %(message)s', level=logging.WARNING) gp.check_result(gp.use_python_logging()) # find cameras cameras = gp.check_result(gp.gp_camera_autodetect())
def start(self): right = True autodetected = gp.check_result(gp.gp_camera_autodetect()) for i, cam in enumerate(autodetected): name, addr = cam if i == 0: right = get_bool(name + " connect in " + addr + " is Right cam ? (show left page) ") else: right = not self.camera_list[i - 1]["right"] # camera_list.append((name, addr))camera = gp.Camera() # search ports for camera port name 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() self.camera_list.append({ "gp": camera, "name": name, "right": right }) if not self.camera_list: print('No camera detected') else: canvas = np.zeros((512, 512, 3), np.uint8) while self.scanning: cv2.imshow('canvas', canvas) self.key_event(cv2.waitKey(100))
def get_camera_list(): if not gp: return [] camera_list = [] for name, addr in gp.check_result(gp.gp_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 get_available_cameras() -> gp.CameraList: """ Statische Funktion zum Auslesen der angeschlossenen und verfügbaren Kameras am Gerät. :return: Verfügbare Kameras :rtype: gp.CameraList """ if hasattr(gp, 'gp_camera_autodetect'): Camera.available_cameras = gp.check_result(gp.gp_camera_autodetect()) return Camera.available_cameras
def displayCameras(): camera_list = [] for name, addr in gp.check_result(gp.gp_camera_autodetect()): camera_list.append((name, addr)) camera_list.sort(key=lambda x: x[0]) print("=============================================") print("Cameras:") for index, (name, addr) in enumerate(camera_list): print('{:d}: {:s} {:s}'.format(index, addr, name)) print("=============================================")
def camera_connected(): """Return the list of connected camera compatible with 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) return cameras
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)) # loop through camera list for index, (name, addr) in enumerate(camera_list): print('{:s} {:s}'.format(addr, name)) 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()) # make a list of all available cameras camera_list = [] for name, addr in gp.check_result(gp.gp_camera_autodetect()): camera_list.append((name, addr)) if not camera_list: print('No camera detected') 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() text = camera.get_summary() print('Summary') print('=======') print(str(text)) try: text = camera.get_manual() print('Manual') print('=======') print(str(text)) except Exception as ex: print(str(ex)) camera.exit() 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()) # make a list of all available cameras camera_list = [] for name, addr in gp.check_result(gp.gp_camera_autodetect()): camera_list.append((name, addr)) if not camera_list: print('No camera detected') 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() text = camera.get_summary() print('Summary') print('=======') print(str(text)) try: text = camera.get_manual() print('Manual') print('=======') print(str(text)) except Exception as ex: print(str(ex)) camera.exit() return 0
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 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 getCamera(cameraNumber=0): logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING) gp.check_result(gp.use_python_logging()) # make a list of all available cameras camera_list = [] for name, addr in gp.check_result(gp.gp_camera_autodetect()): camera_list.append((name, addr)) camera_list.sort(key=lambda x: x[0]) if len(camera_list) == 0: print("No cameras found") return None if cameraNumber < 0 or cameraNumber >= len(camera_list): print('Camera out of range') return None # initialise chosen camera name, addr = camera_list[cameraNumber] 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() 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)) 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)) return camera
def clear_photos_from_camera(self): cameraCounter = 1 camera_list = [] # Get list of all connected cameras for name, addr in gp.check_result(gp.gp_camera_autodetect()): camera_list.append((name, addr)) if not camera_list: self.deletePhotosLabel.setText('No camera detected') return 1 # Sort the camera list camera_list.sort(key=lambda x: x[0]) for item in camera_list: cameraPercentage = int((cameraCounter / len(camera_list)) * 100) self.cameraProgressBarDelete.setValue(cameraPercentage) self.deletePhotosLabel.setText('Deleting from camera %i of %i' % (cameraCounter, len(camera_list))) # initialise camera name, addr = item camera = gp.Camera() # search ports for camera port name port_info_list = gp.PortInfoList() port_info_list.load() idx = port_info_list.lookup_path(addr) camera.set_port_info(port_info_list[idx]) camera.init() # Get list of all files from the camera camera_files = self.list_camera_files(camera) if not camera_files: self.deletePhotosLabel.setText('No files found') # Deleting files counter = 1 for path in camera_files: filePercentage = int((counter / len(camera_files)) * 100) self.fileProgressBarDelete.setValue(filePercentage) # Get folder and name from path folder, name = os.path.split(path) # Delete image from camera gp.check_result(gp.gp_camera_file_delete(camera, folder, name)) counter += 1 gp.check_result(gp.gp_camera_exit(camera)) cameraCounter += 1 self.deletePhotosLabel.setText('Deletion Completed')
def get_all_cameras(): # Ugh, C libraries >.< # Get all available ports portinfolist = gp.check_result(gp.gp_port_info_list_new()) gp.check_result(gp.gp_port_info_list_load(portinfolist)) # Get all available cameras and a string of their port context = gp.gp_context_new() camlist = gp.check_result(gp.gp_camera_autodetect(context)) cameralist = [] for i in range(camlist.count()): camname = camlist.get_name(i) camport = camlist.get_value(i) # Find port info for this camera portindex = portinfolist.lookup_path(camport) portinfo = portinfolist.get_info(portindex) # Create camera object and associate with given port cam = gp.check_result(gp.gp_camera_new()) gp.check_result(gp.gp_camera_set_port_info(cam, portinfo)) myCamera = Camera("{} ({})".format(camname, camport), cam, context) cameralist.append(myCamera) return cameralist
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 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(): logging.basicConfig( format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING) callback_obj = gp.check_result(gp.use_python_logging()) 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) n = 0 for name, value in cameras: print('camera number', n) print('===============') print(name) print(value) print n += 1 return 0
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(): logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING) gp.check_result(gp.use_python_logging()) 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) n = 0 for name, value in cameras: print('camera number', n) print('===============') print(name) print(value) print n += 1 return 0
def get_camera_list(loop): com.usb_on() env = lmdb.open('./cameras_SN.lmdb', max_dbs=10) serialNumber_db = env.open_db('serialNumber'.encode()) logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s', level=logging.ERROR) gp.check_result(gp.use_python_logging()) camera_list = [] camerasName = "" for name, addr in gp.check_result(gp.gp_camera_autodetect()): 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() serialStr = get_serialNumber(camera) print(serialStr) with env.begin(db=serialNumber_db, write=True) as txn: if txn.get(serialStr.encode()): camerasName = (camerasName + "<p>camera " + txn.get(serialStr.encode()).decode("utf-8") + " dected</p>") else: if not txn.get('count'.encode()): txn.put('count'.encode(), '1'.encode()) cameraName = "CAM_" + str(int(txn.get('count'.encode()))) txn.put('count'.encode(), str(int(txn.get('count'.encode())) + 1).encode()) txn.put(serialStr.encode(), cameraName.encode()) camerasName = (camerasName +"<p>camera " + txn.get(serialStr.encode()).decode("utf-8") + " added</p>") print("new camera captured") # if not camera_list: # print('No camera detected') # return "none" print(camerasName) env.close() return camerasName
def main(): logging.basicConfig( format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING) gp.check_result(gp.use_python_logging()) cameras = gp.check_result(gp.gp_list_new()) context = gp.gp_context_new() if hasattr(gp, 'gp_camera_autodetect'): # gphoto2 version 2.5+ cam_count = gp.check_result(gp.gp_camera_autodetect(cameras, context)) assert cam_count == gp.gp_list_count(cameras) else: port_info_list = gp.check_result(gp.gp_port_info_list_new()) gp.check_result(gp.gp_port_info_list_load(port_info_list)) abilities_list = gp.check_result(gp.gp_abilities_list_new()) gp.check_result(gp.gp_abilities_list_load(abilities_list, context)) gp.check_result(gp.gp_abilities_list_detect( abilities_list, port_info_list, cameras, context)) for n in range(gp.gp_list_count(cameras)): print('camera number', n) print('===============') print(gp.check_result(gp.gp_list_get_name(cameras, n))) print(gp.check_result(gp.gp_list_get_value(cameras, n))) print 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() if hasattr(gp, 'gp_camera_autodetect'): # gphoto2 version 2.5+ cameras = gp.check_result(gp.gp_camera_autodetect(context)) else: port_info_list = gp.check_result(gp.gp_port_info_list_new()) gp.check_result(gp.gp_port_info_list_load(port_info_list)) abilities_list = gp.check_result(gp.gp_abilities_list_new()) gp.check_result(gp.gp_abilities_list_load(abilities_list, context)) cameras = gp.check_result(gp.gp_abilities_list_detect( abilities_list, port_info_list, context)) n = 0 for name, value in cameras: print('camera number', n) print('===============') print(name) print(value) print n += 1 return 0
def autodetect(): """Return a list of camera/port pairs.""" count, cameras = gp.gp_camera_autodetect() return ([tuple(camport) for camport in cameras])
# Use sms gateway provided by mobile carrier: # at&t: [email protected] # t-mobile: [email protected] # verizon: [email protected] # sprint: [email protected] # Establish a secure session with gmail's outgoing SMTP server using your gmail account server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() server.login('*****@*****.**', 'DuneGirl$4') camera_list = [] for name, addr in gp.check_result(gp.gp_camera_autodetect()): camera_list.append((name, addr)) if not camera_list: #print('No camera detected') theMsg = 'No camera detected' #print('The message is :', theMsg) #server.sendmail( 'gphoto2', '*****@*****.**', 'A620 Camera is not connected') camera_list.sort(key=lambda x: x[0]) # ask user to choose one for index, (name, addr) in enumerate(camera_list): print('{:d}: {:s} {:s}'.format(index, addr, name)) if name == 'Canon PowerShot A620 (PTP mode)': print(addr) #set_camera(addr)
def import_regex_photos_from_cameras(self): global haveCamFolder computer_files = self.list_computer_files() cameraCounter = 1 camera_list = [] regexProject = '' # Check if projects exist txt = self.regexEdit.toPlainText() if len(txt) != 0: if not self.check_if_projects_exist(txt): self.projectRegexErrorLabel.setText( 'Error: One of those projects exists!') else: regexProject = txt else: self.projectRegexErrorLabel.setText('Error: No Text In Text Box!') return 1 # Get list of all connected cameras for name, addr in gp.check_result(gp.gp_camera_autodetect()): camera_list.append((name, addr)) if not camera_list: self.importPhotosLabel.setText('Error: No camera detected') return 1 # Sort the camera list camera_list.sort(key=lambda x: x[0]) for item in camera_list: fileCounter = 1 cameraPercentage = int((cameraCounter / len(camera_list)) * 100) self.cameraProgressBarRegex.setValue(cameraPercentage) self.projectRegexErrorLabel.setText( 'Copying from camera %i of %i' % (cameraCounter, len(camera_list))) # intialize cameraName cameraName = 'NoName' # initialise camera name, addr = item camera = gp.Camera() # search ports for camera port name port_info_list = gp.PortInfoList() port_info_list.load() idx = port_info_list.lookup_path(addr) camera.set_port_info(port_info_list[idx]) camera.init() # Get list of all files from the camera camera_files = self.list_camera_files(camera) if not camera_files: self.importPhotosLabel.setText('No files found') return 1 # Figure out the name of the camera for path in camera_files: # Find the name of the file from its original path folder, name = os.path.split(path) # Creating the destination folder for the temporary file dest = os.path.join(TEMPORARY_DIR, name) if not os.path.isdir(TEMPORARY_DIR): os.makedirs(TEMPORARY_DIR) # Load in the file and copy it on to the host machine camera_file = gp.check_result( gp.gp_camera_file_get(camera, folder, name, gp.GP_FILE_TYPE_NORMAL)) gp.check_result(gp.gp_file_save(camera_file, dest)) # See if the exif info includes any name to attach to this camera. exif_dict = piexif.load(dest) if len(exif_dict["0th"][piexif.ImageIFD.Artist]) != 0: cameraName = exif_dict["0th"][piexif.ImageIFD.Artist] os.remove(dest) os.rmdir(TEMPORARY_DIR) break os.remove(dest) currIndex = 0 timestamp = datetime.now() time_dir = self.get_target_dir(timestamp) matches = re.finditer(wordRegex, regexProject, re.MULTILINE) # Find All Scripts for matchNum, match in enumerate(matches): currWord = match.group() nameMatches = re.finditer(nameRegex, match.group(), re.MULTILINE) # Find Project Name for nameMatchNum, nameMatch in enumerate(nameMatches): currName = nameMatch.group().replace('(', '') project_dir = os.path.join(time_dir, currName) numberMatches = re.finditer(numberRegex, currWord, re.MULTILINE) # Figure out what to delete and import for numberMatchNum, numberMatch in enumerate( numberMatches): currNumber = numberMatch.group() # Needs to be imported if currNumber[0] == '+': currNumber = int(numberMatch.group().replace( '+', '')) for x in range(currNumber): filePercentage = int( (fileCounter / len(camera_files)) * 100) self.fileProgressBarRegex.setValue( filePercentage) self.projectRegexErrorLabel.setText( 'Copying from camera %i of %i' % (cameraCounter, len(camera_list))) folder, name = os.path.split( camera_files[currIndex]) if haveCamFolder: dest_dir = os.path.join( project_dir, str(cameraName, 'utf-8')) else: dest_dir = project_dir # Create directory dest = os.path.join(dest_dir, name) if dest in computer_files: continue if not os.path.isdir(dest_dir): os.makedirs(dest_dir) # Import photo camera_file = gp.check_result( gp.gp_camera_file_get( camera, folder, name, gp.GP_FILE_TYPE_NORMAL)) gp.check_result( gp.gp_file_save(camera_file, dest)) if imageDelCam: gp.check_result( gp.gp_camera_file_delete( camera, folder, name)) saveLocations.append(dest_dir) currIndex += 1 # Needs to be deleted elif currNumber[0] == '-': currNumber = int(numberMatch.group().replace( '-', '')) for x in range(currNumber): filePercentage = int( (fileCounter / len(camera_files)) * 100) self.fileProgressBarRegex.setValue( filePercentage) self.projectRegexErrorLabel.setText( 'Copying from camera %i of %i' % (cameraCounter, len(camera_list))) folder, name = os.path.split( camera_files[currIndex]) gp.check_result( gp.gp_camera_file_delete( camera, folder, name)) currIndex += 1 fileCounter += 1 gp.check_result(gp.gp_camera_exit(camera)) cameraCounter += 1 camera.exit() self.projectRegexErrorLabel.setText('Import Complete!')
def get_captures_list(loop): current_milli_time = int(round(time.time() * 1000)) print("CAPTURE BEGIN") com.usb_off() com.focus_on() time.sleep(8) com.shot() com.focus_off() com.usb_on() time.sleep(3) env = lmdb.open('./cameras_SN.lmdb', max_dbs=10) serialNumber_db = env.open_db('serialNumber'.encode()) logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s', level=logging.ERROR) gp.check_result(gp.use_python_logging()) timestamp = datetime.now() dest_dir = get_target_dir(timestamp) for name, addr in gp.check_result(gp.gp_camera_autodetect()): time0 = int(round(time.time() * 1000)) camera = gp.Camera() port_info_list = gp.PortInfoList() port_info_list.load() idx = port_info_list.lookup_path(addr) camera.set_port_info(port_info_list[idx]) camera.init() computer_files = list_computer_files() serialStr = get_serialNumber(camera) with env.begin(db=serialNumber_db) as txn: cameraName = txn.get(serialStr.encode()).decode("utf-8") print('Capturing image', cameraName) camera_files = list_camera_files(camera) if not camera_files: print('No files found') return 1 print('Copying files...') for path in camera_files: info = get_camera_file_info(camera, path) # timestamp = datetime.fromtimestamp(info.file.mtime) folder, name = os.path.split(path) dest = os.path.join(dest_dir, cameraName + '_' + name ) if dest in computer_files: continue print('%s -> %s' % (path, dest_dir + cameraName + '_' + name)) if not os.path.isdir(dest_dir): os.makedirs(dest_dir) camera_file = gp.check_result(gp.gp_camera_file_get( camera, folder, name, gp.GP_FILE_TYPE_NORMAL)) gp.check_result(gp.gp_file_save(camera_file, dest)) gp.check_result(gp.gp_camera_file_delete(camera, folder, name)) time1 = int(round(time.time() * 1000)) time_f = time1 - time0 print(cameraName,' cap time (mS): ', time_f) # env.close() gp.check_result(gp.gp_camera_exit(camera)) com.usb_off() current_milli_time1 = int(round(time.time() * 1000)) time_f = current_milli_time1-current_milli_time print('all time (mS): ',time_f) # with env.begin() as txn: # for key, value in txn.cursor(db=serialNumber_db): # print(' ', key, value, "/n") # current_config.append({key,value}) # print("C_C: ",current_config) #debug # # com.usb_on() #debug # time.sleep(3) # com.usb_off() # camera_list.sort(key=lambda x: x[0]) # print(camera_list) # com.usb_off() # # camera_list = [] # for name, addr in gp.check_result(gp.gp_camera_autodetect()): # camera_list.append((name, addr)) # if not camera_list: # print('No camera detected') # return 1 # camera_list.sort(key=lambda x: x[0]) # # ask user to choose one # tasks = [] # for camera_item in camera_list: # name, addr = camera_item # print(f"{name} {addr}") # camera = gp.Camera() # # # search ports for camera port name # port_info_list = gp.PortInfoList() # port_info_list.load() # idx = port_info_list.lookup_path(addr) # camera.set_port_info(port_info_list[idx]) # camera.init() # # tasks.append(asyncio.ensure_future(set_capture(camera))) # # asyncio.gather(*tasks, loop=loop) cmds = ['/usr/local/bin/ffprobe', '-f image2', '-pattern_type glob','-framerate 6','-i ./photo/*.JPG',' -s 1920x1080', './photo/video.mp4'] return dest_dir
def main(): # use Python logging logging.basicConfig( filename=logFile + '.log', format='%(asctime)s: %(levelname)s: %(name)s: %(message)s', level=logging.WARNING) gp.check_result(gp.use_python_logging()) # choose camera camera_list = [] for name, addr in gp.check_result(gp.gp_camera_autodetect()): camera_list.append((name, addr)) if not camera_list: print('Err 1 : Pas d\'APN détecté !') return 1 choice = 0 # sort by first item camera_list.sort(key=lambda x: x[0]) # print list of camera for index, (name, addr) in enumerate(camera_list): print('{:d}: {:s} {:s}'.format(index, addr, name)) if len(camera_list) > 1: # ask user to choose one choice = input('Indiquez le n° d\'APN choisi : ') # test answer try: choice = int(choice) except ValueError: print('Err 2 : Veuillez saisir un nombre !') return 2 if choice < 0 or choice >= len(camera_list): print('Err 3 : Veuillez saisir une des valeurs proposée !') return 3 # initialise chosen camera name, addr = camera_list[choice] camera = gp.Camera() context = gp.Context() # 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]) # init connection try: camera.init(context) except: print('Err 4 : Erreur à l\'ouverture de la connexion') return 4 # get configuration tree config = camera.get_config(context) print(name) # find the capture target config item for i in dicoParameters.keys(): # find the capture target config item try: parameters = config.get_child_by_name(i) except: print('Le paramètre', i, 'est inconnu !') camera.exit(context) return 5 if check_parameters(parameters, dicoParameters.get(i)) == 1: parameters.set_value(dicoParameters.get(i)) print('> Paramètre {:15} = {:12} appliqué'.format( parameters.get_name(), parameters.get_value())) else: print('> Paramètre {:15} = {:12} non valide'.format( parameters.get_name(), dicoParameters.get(i))) # set config camera.set_config(config, context) # clean up camera.exit(context) return 0
def import_all_photos_from_cameras(self): global haveCamFolder computer_files = self.list_computer_files() cameraCounter = 1 camera_list = [] # Get list of all connected cameras for name, addr in gp.check_result(gp.gp_camera_autodetect()): camera_list.append((name, addr)) if not camera_list: self.importPhotosLabel.setText('No camera detected') return 1 # Sort the camera list camera_list.sort(key=lambda x: x[0]) for item in camera_list: cameraPercentage = int((cameraCounter / len(camera_list)) * 100) self.cameraProgressBarImport.setValue(cameraPercentage) self.importPhotosLabel.setText('Copying from camera %i of %i' % (cameraCounter, len(camera_list))) # intialize cameraName cameraName = 'NoName' # initialise camera name, addr = item camera = gp.Camera() # search ports for camera port name port_info_list = gp.PortInfoList() port_info_list.load() idx = port_info_list.lookup_path(addr) camera.set_port_info(port_info_list[idx]) camera.init() # Get list of all files from the camera camera_files = self.list_camera_files(camera) if not camera_files: self.importPhotosLabel.setText('No files found') return 1 # Figure out the name of the camera for path in camera_files: # Find the name of the file from its original path folder, name = os.path.split(path) # Creating the destination folder for the temporary file dest = os.path.join(TEMPORARY_DIR, name) if not os.path.isdir(TEMPORARY_DIR): os.makedirs(TEMPORARY_DIR) # Load in the file and copy it on to the host machine camera_file = gp.check_result( gp.gp_camera_file_get(camera, folder, name, gp.GP_FILE_TYPE_NORMAL)) gp.check_result(gp.gp_file_save(camera_file, dest)) # See if the exif info includes any name to attach to this camera. exif_dict = piexif.load(dest) if len(exif_dict["0th"][piexif.ImageIFD.Artist]) != 0: cameraName = exif_dict["0th"][piexif.ImageIFD.Artist] os.remove(dest) os.rmdir(TEMPORARY_DIR) break os.remove(dest) counter = 1 # Old Import Part for path in camera_files: filePercentage = int((counter / len(camera_files)) * 100) self.fileProgressBarImport.setValue(filePercentage) # Construct the path that the images will be copied into on the host machine timestamp = datetime.now() folder, name = os.path.split(path) dest_dir = self.get_target_dir(timestamp) dest_dir = os.path.join(dest_dir, projectName) if haveCamFolder: dest_dir = os.path.join(dest_dir, str(cameraName, 'utf-8')) dest = os.path.join(dest_dir, name) if dest in computer_files: continue if not os.path.isdir(dest_dir): os.makedirs(dest_dir) # Save image from camera camera_file = gp.check_result( gp.gp_camera_file_get(camera, folder, name, gp.GP_FILE_TYPE_NORMAL)) gp.check_result(gp.gp_file_save(camera_file, dest)) saveLocations.append(dest) # Delete image from camera if imageDelCam: gp.check_result( gp.gp_camera_file_delete(camera, folder, name)) counter += 1 gp.check_result(gp.gp_camera_exit(camera)) cameraCounter += 1 camera.exit() self.importPhotosLabel.setText('Import Complete!')