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 getPicture(camera, context): print('Capturing image') showCapture(getClockFile(), (400, 400)) pygame.display.flip() current = os.path.join(TMPPATH, getImageName()) if os.path.exists(current): os.unlink(current) file_path = gp.check_result( gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE, context)) print('Camera file path: {0}/{1}'.format(file_path.folder, file_path.name)) if not os.path.exists(TMPPATH): os.makedirs(TMPPATH) target = os.path.join(TMPPATH, getImageName(False)) print('Copying image to', target) try: camera_file = gp.check_result( gp.gp_camera_file_get(camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL, context)) gp.check_result(gp.gp_file_save(camera_file, target)) except: pass rt = gp.gp_camera_file_delete(camera, file_path.folder, file_path.name, context) showCapture(target) return target
def dismiss_last(self): if self.last_image: if debug: self.log.debug("Dismiss last image") else: self.check_success( gp.gp_camera_file_delete(self.cam, self.file_path.folder, self.file_path.name), "camera_file_delete") self.last_image = False
def captureandsave(camera, context): #Capture Action cameraCapturePath = gp.check_result( gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE, context)) #Making Target Save photo_local_root Dir target = os.path.join(tl.getConfig('photo_local_root'), cameraCapturePath.name) #Grab Captured Image Extension captureFileExtension = pathlib.Path(cameraCapturePath.name).suffix #GP_FILE_TYPE_NORMAL for JPEG; GP_FILE_TYPE_RAW for RAW if (tl.getConfig('FILE_TYPE') == 'RAW'): camera_file = gp.check_result( gp.gp_camera_file_get(camera, cameraCapturePath.folder, cameraCapturePath.name, gp.GP_FILE_TYPE_RAW, context)) elif (tl.getConfig('FILE_TYPE') == 'JPEG'): camera_file = gp.check_result( gp.gp_camera_file_get(camera, cameraCapturePath.folder, cameraCapturePath.name, gp.GP_FILE_TYPE_NORMAL, context)) gp.check_result(gp.gp_file_save(camera_file, target)) gp.check_result( gp.gp_camera_file_delete(camera, cameraCapturePath.folder, cameraCapturePath.name, context)) #Rename Based on EXIF Data target_open = open(target, 'rb') exif_tags = exifread.process_file(target_open, \ stop_tag='EXIF DateTimeOriginal') for tag in exif_tags.keys(): #Only Perform Following if tag is Date/Time #Change file extension here for RAW/JPEG if tag in ('EXIF DateTimeOriginal'): file_name = exif_todatetimestr( exif_tags[tag]) + captureFileExtension file_dir = os.path.join(tl.getConfig('photo_local_root'), exif_todatestr(exif_tags[tag])) #Check existence of file_dir, the create it if false if not os.path.exists(file_dir): os.makedirs(file_dir) #Rename and move the captured image then sleep shutil.move(target, os.path.join(file_dir, file_name)) time.sleep(3)
def capture(camera, context, dstpath='image.jpg'): """ Capture an image - verify file capture format on camera before setting dstpath """ camfile = gp.check_result(gp.gp_file_new()) campath = gp.CameraFilePath() starttime = time.time() gp.check_result(gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE, campath, context)) gp.gp_camera_file_get(camera, campath.folder, campath.name, gp.GP_FILE_TYPE_NORMAL, camfile, context) gp.gp_file_save(camfile, dstpath) gp.gp_file_unref(camfile) gp.check_result(gp.gp_camera_file_delete(camera, campath.folder, campath.name, context)) endtime = round(time.time() - starttime, 2) print ('capture complete in {}s'.format(endtime))
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 take_photo(): context = gp.Context() camera = gp.Camera() camera.init(context) file_path = gp.check_result( gp.gp_camera_capture( camera, gp.GP_CAPTURE_IMAGE, context ) ) # TODO - label the photos by date - YYYY-MM-DD-HH-MM-SS or something. datestr = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S:%f ') target = os.path.join(settings.originals_dir, datestr + file_path.name) camera_file = gp.check_result( gp.gp_camera_file_get( camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL, context ) ) gp.check_result( gp.gp_file_save( camera_file, target ) ) gp.check_result( gp.gp_camera_file_delete( camera, file_path.folder, file_path.name, context ) ) gp.gp_camera_exit(camera, context) return target
def getPicture(camera,context): print('Capturing image') showCapture(getClockFile(),(400,400)) pygame.display.flip() current=os.path.join(TMPPATH,getImageName()) if os.path.exists(current): os.unlink(current) file_path = gp.check_result(gp.gp_camera_capture( camera, gp.GP_CAPTURE_IMAGE, context)) print('Camera file path: {0}/{1}'.format(file_path.folder, file_path.name)) if not os.path.exists(TMPPATH): os.makedirs(TMPPATH) target = os.path.join(TMPPATH, getImageName(False)) print('Copying image to', target) try: camera_file = gp.check_result(gp.gp_camera_file_get( camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL, context)) gp.check_result(gp.gp_file_save(camera_file, target)) except: pass rt=gp.gp_camera_file_delete(camera,file_path.folder,file_path.name,context) showCapture(target) return target
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 delete_file(camera, path): folder, name = os.path.split(path) gp.check_result(gp.gp_camera_file_delete(camera, folder, name))
def delete_file(camera, context, path): folder, name = os.path.split(path) gp.check_result(gp.gp_camera_file_delete(camera, folder, name, context))
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!')
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 main(): delete_files() #capture_image() logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING) gp.check_result(gp.use_python_logging()) ############################################ #begin set camera #camera = gp.check_result(gp.gp_camera_new()) # make a list of all available cameras camera_list = [] #for name, addr in gp.check_result(gp.gp_camera_autodetect()): #camera_list.append((name, addr)) #if not camera_list: #print('No camera detected') #camera_list.sort(key=lambda x: x[0]) ## ask user to choose one #for index, (name, addr) in enumerate(camera_list): #print('{:d}: {:s} {:s}'.format(index, addr, name)) #if name == 'Canon PowerShot A620 (PTP mode)': #print(addr) #set_camera(addr) # end set camera ############################################ #gp.check_result(gp.gp_camera_init(camera)) #Day or Night # test_capture() sunrise = ephem.localtime(o.next_rising(s)) sunset = ephem.localtime(o.next_setting(s)) if sunset < sunrise: print('Day') print('Capturing image') file_path = gp.check_result( gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE)) print('Camera file path: {0}/{1}'.format(file_path.folder, file_path.name)) target = os.path.join(path_to_images, file_path.name) print('Copying image to', target) camera_file = gp.check_result( gp.gp_camera_file_get(camera, file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL)) gp.check_result(gp.gp_file_save(camera_file, target)) gp.check_result(gp.gp_camera_exit(camera)) #end capture image print(glob.glob("./*.*")) file_to_rename = glob.glob("./*.*") fix_me = str(file_to_rename) fix_me = re.sub('[[/\]\'\"]', '', fix_me) fix_me = re.sub('.', '', fix_me, 1) #pass_me = '["mv" ' + ', "' + path_to_images + '/' + fix_me + '" , "' + path_to_images + '/' + 'webcam.jpg"]' #print pass_me #shutil.copy(target, path_for_movie) os.rename(fix_me, 'webcam.jpg') #add current file to movie source file_found = True i = 1 while file_found: #################### #fix base_file #################### if i > 9: zeros = '0' else: zeros = '00' #print(zeros) #the_file = base_file + str(i) + '.jpg' the_file = base_file + zeros + str(i) + '.jpg' #used to create a bunch of files #open(the_file, 'a') #print('Looking for :', the_file) if os.path.isfile(the_file): print('Found :', the_file) i += 1 else: print('Creating 1 File') file_found = False #break loop and... #create one from current image #if i > 9: #zeros = '0' #else: zeros = '00' #print(zeros) scr = '/Users/Neal/Documents/gphoto2_testing/captured_image/webcam.jpg' dst = '/Users/Neal/Documents/gphoto2_testing/ForMovie/IMG_' + zeros + str( i) + '.jpg' print('Copyied Current') shutil.copy(scr, dst) #when there are 30 images create a movie and delete files path, dirs, files = os.walk( "/Users/Neal/Documents/gphoto2_testing/ForMovie").next() file_count = len(files) if file_count > 29: print('Making New Movie') #write something to process a movie hourly(ish) #the_file = '/Users/Neal/Documents/gphoto2_testing/TheMovie/test.mp4' theFile = '/Users/Neal/Dropbox/WeatherMovie/test.mp4' if os.path.isfile(the_file): os.remove(the_file) #os.system('ffmpeg -f image2 -r 1 -i /Users/Neal/Documents/gphoto2_testing/ForMovie/IMG_%03d.jpg -vcodec mpeg4 -y /Users/Neal/Documents/gphoto2_testing/TheMovie/test.mp') os.system( 'ffmpeg -f image2 -r 1 -s 2027x1520 -i /Users/Neal/Documents/gphoto2_testing/ForMovie/IMG_%03d.jpg -vcodec libx264 -crf 10 -pix_fmt yuv420p -y /Users/Neal/Dropbox/WeatherMovie/test.mp4' ) #write something to delete movie source for fl in glob.glob( '/Users/Neal/Documents/gphoto2_testing/ForMovie/*.jpg'): os.remove(fl) subprocess.call([ 'python', '/Users/Neal/Documents/gphoto2_testing/delete-video.py' ]) subprocess.call([ 'python', '/Users/Neal/Documents/gphoto2_testing/upload-video.py', '--file', '/Users/Neal/Dropbox/WeatherMovie/test.mp4', '--title', 'Bayshore Weather Timelapse' ]) print('Deleting: {0}/{1}'.format(file_path.folder, file_path.name)) gp.check_result( gp.gp_camera_file_delete(camera, file_path.folder, file_path.name)) #subprocess.call(pass_me) else: print('Night')
def _delete_file(self, camera, context, path): folder, name = os.path.split(path) gp.check_result(gp.gp_camera_file_delete(camera, folder, name, context))