def segmented_action(self,sender): if c.textfield_active: c.textfield_active.end_editing() c.icon_origin_segmentedcontrol = sender icon_origin = sender.segments[sender.selected_index] sender.selected_index = -1 # reset for other image, if any c.container_view['icon url'].icon_origin = icon_origin if icon_origin == 'local': def picked_local(tf): self.disp_icon(c.container_view['icon url']) file_picker_dialog('Select icon', multiple=False, select_dirs=False,file_pattern=r'^.*\.(jpg$|png$)', from_dialog=[c,c.container_view['icon url']], root_dir=os.path.expanduser('~/Documents/'), icloud=False, only=True, callback=picked_local) # c.values and textfield.text filled in file_picker_dialog # cancel => callback not called elif icon_origin == 'photo': photo_asset = photos.pick_asset(assets=photos.get_assets(media_type='photo')) if not photo_asset: return c.values['icon url'] = photo_asset self.disp_icon(c.container_view['icon url']) elif icon_origin == 'icloud': def picked_icloud(param): if param == 'canceled': return c.values['icon url'] = str(param[7:]) # remove file:// self.disp_icon(c.container_view['icon url']) MyPickDocument(500,500,title='test',UTIarray=['public.image'], PickerMode=0, callback=picked_icloud) elif icon_origin == 'url': c.container_view['shield'].hidden = False c.container_view['icon url'].enabled = True c.container_view['icon url'].text = 'drag & drop image here' c.container_view['icon url'].hidden = False c.container_view['webview_view']['webview'].load_url('http://www.google.com') c.container_view['webview_view'].hidden = False
def pick_an_image(show_albums=False, include_metadata=False, original=True, raw_data=False, multi=False): assets = photos.get_assets() return photos.pick_asset(assets, multi=multi).get_image()
def pick_asset(): assets = photos.get_assets(media_type='video') asset = photos.pick_asset(assets) phasset=ObjCInstance(asset) asseturl=ObjCClass('AVURLAsset').alloc().initWithURL_options_(phasset.ALAssetURL(),None) return asseturl return asseturl, str(phasset.filename() )
def main(): global vn_model vn_model = load_model() all_assets = photos.get_assets() asset = photos.pick_asset(assets=all_assets) if asset is None: return classify_asset(asset)
def pickphoto2data(): all = photos.get_assets() asset = photos.pick_asset(all) if asset is not None: bobj = asset.get_image_data(original=True) rawdata = bobj.getvalue() return rawdata, bobj.uti return None, None
def fromLibrary_action(sender): ass = photos.pick_asset(assets=photos.get_assets(), title='Pick image to glitch') if ass is None: return if sender.superview.name == 'fuckupcolors': sender.superview['fuckUpSlider'].value = 0 sender.superview['imageview1'].image = ass.get_ui_image()
def assets_for_attachments(attachments): all_assets = photos.get_assets() matching_assets = [] for a in all_assets: path = str(ObjCInstance(a).pathForOriginalFile()) if path in attachments: matching_assets.append(a) return matching_assets
def assets_for_attachments(attachments): all_assets = photos.get_assets() matching_assets = [] for a in all_assets: objc_asset = ObjCInstance(a) path_orig = str(objc_asset.pathForOriginalFile()) path_edit = str(objc_asset.pathForFullsizeRenderImageFile()) if path_orig in attachments or path_edit in attachments: matching_assets.append(a) return matching_assets
def _get_latest_photo(self): all_assets = photos.get_assets() last_asset = all_assets[-1] img = last_asset.get_image() if img.width >= img.height: img = img.resize((100, round(img.height/img.width*100))) else: img = img.resize((round(img.width/img.height*100), 100)) return self._pil2ui(img)
def main(): media = 'image' all_assets = photos.get_assets(media_type=media) i = 1 for a in all_assets: l = a.local_id x = l.find('/') if x != -1: l = a.local_id[:x] print('{0:2}: l:{1} full:{2}'.format(i,l,a.local_id)) i+=1
def main(): c = photos.get_assets(media_type='image') ps = photos.pick_asset(assets=c, title='Pick photos', multi=True) for p in ps: print(p.location) if p.location: # Photo has GPS tags prev_location = p.location else: # Photos does not have GPS tags, use previous if any if prev_location: p.location = prev_location
def segmented_action(self, sender): if c.textfield_active: c.textfield_active.end_editing() c.icon_origin_segmentedcontrol = sender icon_origin = sender.segments[sender.selected_index] sender.selected_index = -1 # reset for other image, if any c.container_view['icon url'].icon_origin = icon_origin if icon_origin == 'local': def picked_local(tf): self.disp_icon(c.container_view['icon url']) file_picker_dialog('Select icon', multiple=False, select_dirs=False, file_pattern=r'^.*\.(jpg$|png$)', from_dialog=[c, c.container_view['icon url']], root_dir=os.path.expanduser('~/Documents/'), icloud=False, only=True, callback=picked_local) # c.values and textfield.text filled in file_picker_dialog # cancel => callback not called elif icon_origin == 'photo': photo_asset = photos.pick_asset(assets=photos.get_assets( media_type='photo')) if not photo_asset: return c.values['icon url'] = photo_asset self.disp_icon(c.container_view['icon url']) elif icon_origin == 'icloud': def picked_icloud(param): if param == 'canceled': return c.values['icon url'] = str(param[7:]) # remove file:// self.disp_icon(c.container_view['icon url']) MyPickDocument(500, 500, title='test', UTIarray=['public.image'], PickerMode=0, callback=picked_icloud) elif icon_origin == 'url': c.container_view['shield'].hidden = False c.container_view['icon url'].enabled = True c.container_view['icon url'].text = 'drag & drop image here' c.container_view['icon url'].hidden = False c.container_view['webview_view']['webview'].load_url( 'http://www.google.com') c.container_view['webview_view'].hidden = False
def __init__(self, **kwargs): super().__init__(**kwargs) UIPickerView = ObjCClass('UIPickerView') self._picker_view = UIPickerView.alloc().initWithFrame_(ObjCInstance(self).bounds()).autorelease() ObjCInstance(self).addSubview_(self._picker_view) self.delegate_and_datasource = UIPickerViewDataSourceAndDelegate.alloc().init().autorelease() self._picker_view.delegate = self.delegate_and_datasource self._picker_view.dataSource = self.delegate_and_datasource self._picker_view.assets = photos.get_assets() self._picker_view.myRowWidth = self.width self._picker_view.myRowHeight = int(self.height/5)
def pickImageButton(sender): global Hint global CurrentHintID global CurrentHint global photoImage global mustSave KillGPSView() listPhotos = photos.get_assets('image') imageAsset = photos.pick_asset(listPhotos, title='Pick some assets', multi=False) if not imageAsset: return if imageAsset.location != None: CurrentHint[HINT_LONGITUDE] = imageAsset.location['longitude'] CurrentHint[HINT_LATITUDE] = imageAsset.location['latitude'] else: console.alert( 'Warning', 'This photo has no location information, unable to set GPS coordinates.', 'OK', hide_cancel_button=True) wi = photoImage.width hi = (int)(wi * imageAsset.pixel_height / imageAsset.pixel_width) imgUI = imageAsset.get_ui_image((wi, hi)) pngdata = imgUI.to_png() image = Image.open(io.BytesIO(pngdata)) CreateGPSView() img2 = image.resize((wi, hi), Image.ANTIALIAS) img2.save(AdventureFolder + '/photo_hint_' + str(CurrentHintID) + '.jpg', 'jpeg') # convert the Image to PNG string img_buf = BytesIO() img2.save(img_buf, 'jpeg') img = img_buf.getvalue() sender.superview['photoview'].image = ui.Image.from_data(img) mustSave = True refreshEditorItems(True)
def save_assets_for_attachments(): ''' tricks from OMZ to link assets and attachements generates a dictionnary saved in a jason text file: dic[attachement]=asset.local_id ''' all_assets = photos.get_assets() asset_path = {} for a in all_assets: objc_asset = ObjCInstance(a) path_orig = str(objc_asset.pathForOriginalFile()) path_edit = str(objc_asset.pathForFullsizeRenderImageFile()) id = a.local_id asset_path[path_orig] = id asset_path[path_edit] = id f = open("exif.txt", "w", encoding="utf-8") json.dump(asset_path, f) f.close()
def btn_GetPic(self, sender): picked = photos.pick_asset( assets=photos.get_assets(media_type='image'), title='Select photo(s)', multi=True) if picked: for p in picked: data = p.get_image_data() ext = str(data.uti)[6:] for i in range(sys.maxsize): filename = 'image{}'.format(str(i).zfill(3)) + ext if not os.path.exists(filename): with open(filename, 'wb') as f: f.write(data.read()) break console.hud_alert('Saved ' + str(len(picked)) + ' files', duration=3.0) self.make_lst() self.view['tableview1'].reload_data()
def setup(self): all_assets = photos.get_assets()[-1] ui_image = all_assets.get_ui_image() self.background_color = 'lightgray' img = ui.Button(name='image') img.frame = (25,25,self.size.x-50,self.size.y-50) img.background_image = ui_image img.enable = False img.hidden = True self.view.add_subview(img) b = ui.Button() b.frame = (100,0,60,32) b.title = 'tap' b.action = self.disp_photo self.view.add_subview(b)
def process_images(thumbnail=True): all_assets = photos.get_assets() photo_count = len(all_assets) photo_index = 0 while photo_index<photo_count: ass = all_assets[photo_index] a=ObjCInstance(ass) if thumbnail: requested_size=CGSize(160,160) else: requested_size=a.imageSize() # for fullsize handleImage.filename=str(a.filename()) imageManager.requestImageForAsset(ass, targetSize=requested_size, contentMode=1, options=options, resultHandler=B) a._cached_methods.clear() a=[] ass=[] photo_index += 1
def copy_assets(ftp, media, tgt_dir): ''' Step through all of the iOS media assets filtering by media type. For each asset create a new filename based on the asset metadata and then copy the asset via ftp to a target directory ''' i = 1 all_assets = photos.get_assets(media_type=media) for a in all_assets: pool = ObjCClass('NSAutoreleasePool').new() try: buffer = a.get_image_data(original=False) tgt_filename = create_asset_name(a, buffer.uti) fullpath = os.path.join(tgt_dir, tgt_filename) ftp.storbinary("STOR " + fullpath, buffer) print('{0:4}: --> {1} - {2}'.format(i, tgt_dir, tgt_filename)) except SystemError as e: print('\t{0:4}: ERROR {1}'.format(i, e)) print('\t\t{1} - {2}'.format(tgt_dir, tgt_filename)) finally: i += 1 pool.drain()
def rename_all_assets(): i = 1 media = 'image' all_assets = photos.get_assets(media_type=media) ''' a = all_assets[-1] new_name = rename_asset(a) return new_name ''' unique_names = set() duplicate_names = [] none_names = 0 for a in all_assets: pool = ObjCClass('NSAutoreleasePool').new() try: new_name = rename_asset(a) if new_name == None: none_names += 1 else: if new_name in unique_names: duplicate_names.append(new_name) else: unique_names.add(new_name) print('{:4}: {}'.format(i, new_name)) except SystemError as e: print('\t{0:4}: ERROR {1}'.format(i, e)) finally: i += 1 pool.drain() print('Duplicates: {}'.format(len(duplicate_names))) for d in duplicate_names: print(d) print('Uniques: {}'.format(len(unique_names))) print('Nones: {}'.format(none_names)) print('Total files: {}'.format(i))
def tap_cell(self, sender): assets = photos.get_assets() asset = photos.pick_asset(assets=assets, title='Choisissez la photo', multi=None) if not asset: return if len(sender.subviews) == 0: img = ui.ImageView() img.name = 'photo' img.frame = (0, 0, sender.width, sender.height) img.content_mode = ui.CONTENT_SCALE_ASPECT_FILL img.flex = 'WH' sender.add_subview(img) else: img = sender['photo'] img.image = asset.get_ui_image() self.set_act(img, 'mémoriser photo') self.pil_store_params = img ui.delay(self.pil_store, 0.1) self.sender = sender # for build_thumb
#title(r'$\theta$={theta:.2f}$\omega$={omega}'.format(**gaborParams[i])) plt.axis('off'); plt.imshow(sinFilterBank[i]) plt.figure() for i in range(n): plt.subplot(4,4,i+1) # title(r'$\theta$={theta:.2f}$\omega$={omega}'.format(**gaborParams[i])) plt.axis('off'); plt.imshow(cosFilterBank[i]) plt.show() plt.close() age[i][j] = np.sum(image[i:i+m, j:j+m]*kernel) + bias return new_image all_assets = photos.get_assets() last_asset = all_assets[-1] img = last_asset.get_image() img = ImageOps.grayscale(img) import photos album = photos.get_recently_added_album() last = album.assets[-1] if last.can_edit_content: img = last.get_image() grayscale_img = img.convert('L') grayscale_img.save('.edit.jpg', quality=90) last.edit_content('.edit.jpg') else: print('The asset is not editable')
def main(): global all_points #----- Main process ----- console.clear() # Hide script back = MapView(frame=(0, 0, 540, 620)) back.background_color = 'white' back.name = 'Display route of selected localized photos' back.present('full_screen', hide_title_bar=False) # Get a list of all photos c = photos.get_assets(media_type='image') # Pick at least two photos from all photos ps = photos.pick_asset(assets=c, title='Pick begin/end or all photos of the route', multi=True) if ps == None or len(ps) < 2: # Pick has been canceled console.hud_alert('At least two photos are needed', 'error') back.close() return # Loop on all photos route_points = [] if len(ps) > 2: # more than 2 picked photos scan_ph = ps # use picked photos only else: # 2 photos picked scan_ph = c # scan all photos min_date = min(ps[0].creation_date, ps[1].creation_date).date() max_date = max(ps[0].creation_date, ps[1].creation_date).date() for p in scan_ph: p_date = p.creation_date.date() if (len(ps) > 2) or (len(ps) == 2 and p_date >= min_date and p_date <= max_date): # Photo belongs to the route period if p.location: # Photo has GPS tags lat = p.location['latitude'] lon = p.location['longitude'] # store latitude, longitude and taken date route_points.append((lat, lon, p_date)) if len(route_points) < 2: console.hud_alert('At least two localized photos neded', 'error') back.close() return # Sort points by ascending taken date route_points = sorted(route_points, key=lambda x: x[2]) # Compute min and max of latitude and longitude min_lat = min(route_points, key=lambda x: x[0])[0] max_lat = max(route_points, key=lambda x: x[0])[0] min_lon = min(route_points, key=lambda x: x[1])[1] max_lon = max(route_points, key=lambda x: x[1])[1] # Display map, center and zoom so all points are visible back.set_region((min_lat + max_lat) / 2, (min_lon + max_lon) / 2, 1.2 * (max_lat - min_lat), 1.2 * (max_lon - min_lon), animated=True) # Display pin's all_points = [] for point in route_points: back.add_pin(point[0], point[1], str(point[2])) # Display polygon line of sorted locations back.addPolyLineToMap()
def touch_began(self, touch): current = location.get_location() latLong = (round(current['latitude'], 4), round(current['longitude'], 4) ) #solved the close points problem using rounding picTaken = latLong in self.photoLocations x, y = touch.location if self.imageModeOpen == True: self.imageModeOpen = False self.img.hidden = True if self.loopPrompt == True: if x > 50 and x < self.size.x / 2 and y < self.size.y / 2 and y > self.size.y / 2 - 50: self.loopPrompt = False self.loopPromptState = 1 elif x > self.size.x / 2 and x < self.size.x - 50 and y < self.size.y / 2 and y > self.size.y / 2 - 50: self.loopPrompt = False self.loopPromptState = 2 elif self.MoreState == True: #SOS State if x < self.size.w / 2 + 30 and x > self.size.w / 2 - 30 and y > 50 and y < 100 and self.MoreState == True: webbrowser.open('tel:911') #MapView elif x < 100 and x > 50 and y < 220 and y > 160 and len( self.locations) >= 2: googleMapsMaxPoints = 20 mapLocations = copy.deepcopy(self.locations) if len(self.locations) > googleMapsMaxPoints: mapLocations = [] jump = math.ceil(len(self.locations) / googleMapsMaxPoints) for i in range(0, len(self.locations), jump): mapLocations += [self.locations[i]] self.query = 'safari-https://www.google.com/maps/dir/' for loc in mapLocations: self.query += str(loc[0]) self.query += "," self.query += str(loc[1]) self.query += "/" self.query = self.query[:-1] webbrowser.open(self.query) elif x < self.size.x / 2 + 40 and x > self.size.x / 2 - 40 and y < 220 and y > 160 and len( self.locations) >= 2: googleMapsMaxPoints = 20 mapLocations = copy.deepcopy(self.locations) if len(self.locations) > googleMapsMaxPoints: mapLocations = [] jump = math.ceil(len(self.locations) / googleMapsMaxPoints) for i in range(0, len(self.locations), jump): mapLocations += [self.locations[i]] self.query = 'safari-https://www.google.com/maps/dir/' for loc in mapLocations: self.query += str(loc[0]) self.query += "," self.query += str(loc[1]) self.query += "/" self.query = self.query[:-1] clipboard.set(self.query[7:]) self.clipState = True elif x < self.size.x - 50 and x > self.size.x - 100 and y < 220 and y > 160 and len( self.locations) > 2: self.pathState = True else: self.MoreState = False self.clipState = False self.pathState = False #open landmark elif y > 150 and y < 200 and self.imageMode == True: sound.play_effect('arcade:Laser_2') self.imageModeOpen = True self.imageMode = False self.heightFrame = (self.photoHeight / self.photoWidth) * (self.size.x) self.widthFrame = (self.photoWidth / self.photoWidth) * (self.size.x) self.heightPhoto = (self.photoHeight / self.photoWidth) * (self.size.x - 20) self.widthPhoto = (self.photoWidth / self.photoWidth) * (self.size.x - 20) self.halfScreenFrame = self.size.y / 2 - self.heightFrame / 2 self.halfScreen = self.size.y / 2 - self.heightPhoto / 2 self.img = ui.Button(name='image') self.img.frame = (10, self.halfScreen, self.widthPhoto, self.heightPhoto) self.img.background_image = self.ui_image self.img.enable = False self.img.hidden = False self.view.add_subview(self.img) elif y < 150 and y > 200 and self.imageMode == True: self.imageMode = False #reset button elif x < 100 and x > 50 and y < 100 and y > 50: self.measuringOn = False self.checkedOnce = 0 self.background_color = self.theme["backgroundColor"] self.locations = [] self.needMore = False self.photoCount = 0 self.photoLocations = [] self.locationsLeft = [] self.needMore = False self.timerCount = 0 #more button elif x < self.size.w / 2 + 25 and x > self.size.w / 2 - 25 and y < 30 and y > 0: self.MoreState = True #take photos and add to album elif x < self.size.w / 2 + 30 and x > self.size.w / 2 - 30 and y > 50 and y < 100 and self.MoreState == False and self.measuringOn == True and picTaken == False: imageree = photos.capture_image() if imageree != None: photos.save_image(imageree) time.sleep(1) self.photoCount += 1 allAssets = photos.get_assets() theImage = allAssets[-1] #print("Divider") # Find the album or create it: try: self.photoLibrary = [ a for a in photos.get_albums() if a.title == 'Thread' ][0] except IndexError: self.photoLibrary = photos.create_album('Thread') # Add the file as an asset to the library: # asset = photos.create_image_asset(theImage) # Add the asset to the album: theImage = allAssets[len(allAssets) - 1] self.photoLibrary.add_assets([theImage]) self.photoLocations += [latLong] #compass State: Letters (NWSE) or degrees elif x < 325 and x > 275 and y < 100 and y > 50: self.compassStat = not (self.compassStat) elif self.measuringOn == False and self.checkedOnce == 0: #sound.play_effect('arcade:Laser_2') self.measuringOn = True self.background_color = self.theme["backgroundColor"] self.checkedOnce += 1 elif self.measuringOn == True and self.checkedOnce == 1 and len( self.locations) < 4: #sound.play_effect('arcade:Laser_1') self.needMore = True elif self.measuringOn == True and self.checkedOnce == 1 and len( self.locations) > 3: #sound.play_effect('arcade:Laser_1') self.needMore = False self.measuringOn = False self.background_color = self.theme["backgroundColor"] self.checkedOnce += 1 elif self.measuringOn == False and self.checkedOnce == 3: #sound.play_effect('arcade:Laser_1') self.background_color = self.theme["backgroundColor"] self.checkedOnce += 1
def touch_began(self, touch): sound.play_effect('Footstep') #creates a query of the locations recorded and opens it on google maps #because the query accepts at most around 20 points, if you have more #than 20 points it will create a new list and get points evenly spaced #throughout the path to a total of less than 20. Looks representative #and accurate. def mapView(self): googleMapsMaxPoints = 20 mapLocations = copy.deepcopy(self.locations) if len(self.locations) > googleMapsMaxPoints: mapLocations = [] jump = math.ceil(len(self.locations) / googleMapsMaxPoints) for i in range(0, len(self.locations), jump): mapLocations += [self.locations[i]] self.query = 'safari-https://www.google.com/maps/dir/' for loc in mapLocations: self.query += str(loc[0]) self.query += "," self.query += str(loc[1]) self.query += "/" self.query = self.query[:-1] webbrowser.open(self.query) #when you run across a landmark (photo) you placed down, it will #notify you its present and you can tap to reveal the photo def openLandmark(self): sound.play_effect('Click_1') self.imageModeOpen = True self.imageMode = False self.heightPhoto = (self.photoHeight/self.photoWidth) * \ (self.size.x-20) self.widthPhoto = (self.photoWidth/self.photoWidth) * \ (self.size.x-20) self.heightFrame = self.heightPhoto + 10 self.widthFrame = self.widthPhoto + 10 self.halfScreenFrame = self.size.y / 2 - self.heightFrame / 2 self.halfScreen = self.size.y / 2 - self.heightPhoto / 2 #asked a question on the omz (Pythonista) forum and they answered! #'https://forum.omz-software.com/topic/5263/displaying-an-image- #from-album-in-photos-onto-screen-in-scene-module' #opens the image and has it hidden. self.img = ui.Button(name='image') self.img.frame = (10, self.halfScreen, self.widthPhoto, self.heightPhoto) self.img.background_image = self.ui_image self.img.enable = False self.img.hidden = False self.view.add_subview(self.img) #when you tap, get the current location to perform functions current = location.get_location() #solved the close points problem using rounding latLong = (round(current['latitude'], 4), round(current['longitude'], 4)) picTaken = latLong in self.photoLocations #get the location on the screen of the touch x, y = touch.location #if the image is open, close it when you tap (has to be off the image) if self.imageModeOpen == True: self.imageModeOpen = False self.img.hidden = True #if you have the loop Prompt, you must tap an answer in order to use #the other functions if self.loopPrompt == True: if x > 50 and x < self.size.x/2 and y < self.size.y/2 \ and y > self.size.y/2 - 50: self.loopPrompt = False self.loopPromptState = 1 elif x > self.size.x/2 and x < self.size.x-50 \ and y < self.size.y/2 and y > self.size.y/2 - 50: self.loopPrompt = False self.loopPromptState = 2 #when it has the more menu open, you must are not able to tap any of #the other buttons, other than the ones in the more menu elif self.MoreState == True: #SOS State tap, call the cops if you tap if x < self.size.w/2 + 30 and x > self.size.w/2 - 30 \ and y > 50 and y < 100 and self.MoreState == True: webbrowser.open('tel:911') #MapView tap elif x < 100 and x > 50 and y < 220 and y > 160 and \ len(self.locations) >= 2: mapView(self) #create the query, but make it a link for phone users, and copy #it to the clipboard elif x < self.size.x/2+40 and x > self.size.x/2-40 and \ y < 220 and y > 160 and len(self.locations) >= 2: googleMapsMaxPoints = 20 mapLocations = copy.deepcopy(self.locations) if len(self.locations) > googleMapsMaxPoints: mapLocations = [] jump = math.ceil(len(self.locations) / googleMapsMaxPoints) for i in range(0, len(self.locations), jump): mapLocations += [self.locations[i]] self.query = 'safari-https://www.google.com/maps/dir/' for loc in mapLocations: self.query += str(loc[0]) self.query += "," self.query += str(loc[1]) self.query += "/" self.query = self.query[:-1] clipboard.set(self.query[7:]) self.clipState = True #tap on Trace button to reveal the path elif x < self.size.x-50 and x > self.size.x-100 and y < 220 \ and y > 160 and len(self.locations) > 2: self.pathState = True #tap on theme button to switch the theme elif x < self.size.w/2 + 30 and x > self.size.w/2 - 30 \ and y > self.size.y-95-40 and y < self.size.y-95+40: self.themeSwitch += 1 if self.themeSwitch % 2 == 0: self.theme = self.lightMode elif self.themeSwitch % 2 == 1: self.theme = self.darkMode #tap off a button while in the more menu, and it exits the menu else: self.MoreState = False self.clipState = False self.pathState = False #open landmark by tapping on the banner elif y > 150 and y < 200 and self.imageMode == True: openLandmark(self) #if in image mode, tap off the image to get rid of it off the screen elif y < 150 and y > 200 and self.imageMode == True: self.imageMode = False #reset button resets everything elif x < 100 and x > 50 and y < 100 and y > 50: self.measuringOn = False self.functionState = 0 self.background_color = self.theme["backgroundColor"] self.locations = [] self.needMore = False self.photoCount = 0 self.photoLocations = [] self.locationsLeft = [] self.needMore = False self.timerCount = 0 #more button is a small and out of the way, opens up more menu elif x < self.size.w/2 + 25 and x > self.size.w/2 - 25 and y < 30 \ and y > 0: self.MoreState = True #take photos and add to album elif x < self.size.w/2 + 30 and x > self.size.w/2 - 30 \ and y > 50 and y < 100 and self.MoreState == False and \ self.measuringOn == True and picTaken == False: imageree = photos.capture_image() if imageree != None: #open up the camera and you can take photo photos.save_image(imageree) time.sleep(1) self.photoCount += 1 allAssets = photos.get_assets() theImage = allAssets[-1] #if there is no album, create album 'Thread' try: self.photoLibrary = [a for a in photos.get_albums() \ if a.title == 'Thread'][0] except IndexError: self.photoLibrary = photos.create_album('Thread') #add the image to the album for the user to have and for #future use in the app's use (landmarks!) theImage = allAssets[len(allAssets) - 1] self.photoLibrary.add_assets([theImage]) self.photoLocations += [latLong] #compass State: Letters (NWSE) or degrees elif x < 325 and x > 275 and y < 100 and y > 50: self.compassStat = not (self.compassStat) #go to measuring mode when tapped for the first time elif self.measuringOn == False and self.functionState == 0: self.measuringOn = True self.background_color = self.theme["backgroundColor"] self.functionState += 1 #if you need more values do not let the user stop recording elif self.measuringOn == True and self.functionState == 1 \ and len(self.locations) < 4: self.needMore = True #if you have enough locations, when you tap you can move to next state elif self.measuringOn == True and self.functionState == 1 \ and len(self.locations) > 3: #sound.play_effect('arcade:Laser_1') self.needMore = False self.measuringOn = False self.background_color = self.theme["backgroundColor"] self.functionState += 1 #move function state up to state 4 so you can begin tracing back elif self.measuringOn == False and self.functionState == 3: #sound.play_effect('arcade:Laser_1') self.background_color = self.theme["backgroundColor"] self.functionState += 1
# https://forum.omz-software.com/topic/4004/raw-jpeg import photos from objc_util import * for a in photos.get_assets(): if ObjCInstance(a).isRAW(): a.delete() print('deleted ', a)
resolution = 'high' import console, time import photos, os, ui r = dialogs.alert('Image', '', 'Camera', 'Photo Library') rolling = True if r == 1: x = photos.capture_image() x.save('placeholder.jpg') elif r == 2: x = photos.Asset.get_image(photos.pick_asset(photos.get_assets())) x.save('placeholder.jpg') im = Image.open('placeholder.jpg') global imsize if im.height > im.width: vals = {'low': [6.3, 95], 'med': [4.75, 130], 'high': [3, 205]} v = ui.load_view('uiImageAscii') sa = ui.ButtonItem() sa.action = save sa.title = 'Save' v.right_button_items = [sa] print('Loading in portrait...') else: v = ui.load_view('uiImageAsciiLan')
for (Float64 i = 0; i < CMTimeGetSeconds(asset.duration) * FPS ; i++){ @autoreleasepool { CMTime time = CMTimeMake(i, FPS); NSError *err; CMTime actualTime; CGImageRef image = [generator copyCGImageAtTime:time actualTime:&actualTime error:&err]; UIImage *generatedImage = [[UIImage alloc] initWithCGImage:image]; [self saveImage: generatedImage atTime:actualTime]; // Saves the image on document directory and not memory CGImageRelease(image); } } ''' from objc_util import * import ui,time,os,photos assets = photos.get_assets(media_type='video') #print(len(assets)) asset = photos.pick_asset(assets) duration=asset.duration #asset.get_image().show() print(asset.duration) print(asset.local_id) #file=os.path.expanduser('~/Documents/capturedvideo.MOV') #with open(file,'wb') as f: # f.write(asset.get_image_data().getvalue()) #if not os.path.exists(file): # raise IOError phasset=ObjCInstance(asset) asseturl='assets-library://asset/asset.MOV?id={}&ext=MOV'.format(str(phasset.localIdentifier()).split('/')[0]) asseturl=ObjCClass('AVURLAsset').alloc().initWithURL_options_(nsurl(asseturl),None)
v.close() s.stop_server() console.clear() console.hide_output() quit() # This might break on non-English iOS. Too lazy to test. for album in photos.get_smart_albums(): if album.title == 'Portrait': my_album = album break # Again using iOS API to get the photo's proper filename try: if allow_ML: chosen_pic = photos.pick_asset(assets = photos.get_assets(), title = 'Select a photo') # chosen_pic = photos.pick_image(show_albums=True, include_metadata=False, original=True, raw_data=False, multi=False) else: chosen_pic = photos.pick_asset(assets = my_album.assets, title = 'Select a portrait photo') filename, file_extension = os.path.splitext(str(objc_util.ObjCInstance(chosen_pic).originalFilename())) assert filename != 'None' output_filename = 'Holo_' + filename + '.png' except: quit() try: chosen_pic_image = chosen_pic.get_image(original = False) except: print('Image format (' + file_extension[1:] + ') not supported.') quit() chosen_pic_data = chosen_pic.get_image_data(original = False).getvalue()
def main(): all_assets = photos.get_assets() asset = photos.pick_asset(assets=all_assets) if asset is None: return classify_asset(asset)
def build_skin(photo_filename, photo_offset_x, photo_offset_y): """ Build a minecraft skin and a thumbnail from the provided photo image. :param photo_filename: the source photo :param photo_offset_x: x-offset to start building the skin :param photo_offset_y: y-offset to start building the skin :return a new Image of the skin """ # open the reference images used to 'paint' body parts that are not available from the photo colours = { 'lightGrey': Image.open(IMG_FOLDER + '/lightGrey.png'), 'darkGrey': Image.open(IMG_FOLDER + '/darkGrey.png'), 'blue': Image.open(IMG_FOLDER + '/blue.png'), 'green': Image.open(IMG_FOLDER + '/green.png'), 'black': Image.open(IMG_FOLDER + '/black.png') } logger.info("Converting photo '%s' to skin with offset (%d, %d)", photo_filename, photo_offset_x, photo_offset_y) photo = photos.pick_asset(photos.get_assets(), multi=False).get_image() # resize the photo to match the skin size (keep the aspect ratio to avoid stretching) photo_scale = min(photo.width / SKIN_WIDTH, photo.height / SKIN_HEIGHT) logger.debug("Scaling factor = %f", photo_scale) x = int(photo.width / photo_scale) y = int(photo.height / photo_scale) logger.info("Resizing the photo from %dx%d to %dx%d", photo.width, photo.height, x, y) photo = photo.resize((x, y)) # Build the mappings to build the skin from the photo # by reading the position of each body part in the photo, and finding the location # in the Minecraft skin format. # If the part does not need to be taken from the photo, # use one of the reference images to 'paint' the part instead. # The image where the pixels are to be taken from are included in each # mapping entry (it is not always the photo - it is sometimes one of the reference images) mapping_photo_to_skin = {} for part in parts: from_coords = get_photo_coords(parts[part], photo_offset_x, photo_offset_y) if from_coords is None: # cannot use photo, so need to select another colour # colour = 'lightGrey' # default (e.g. back) colour = 'green' if 'Leg' in xstr(part): colour = 'blue' if 'Arm' in xstr(part): colour = 'green' if 'Bottom' in xstr(part): # takes priority over leg/arm colour = 'darkGrey' logger.debug("Painting %s with %s because from_coords are None", xstr(part), xstr(colour)) from_img = colours[colour] # uncomment this if you want textures # from_img = colours['black'] # uncomment this if you want black from_coords = (0, 0) else: from_coords = (from_coords[0] + photo_offset_x, from_coords[1] + photo_offset_y) from_img = photo to_coords = get_skin_coords(parts[part]) mapping_photo_to_skin[xstr(part)] = [ from_img, parts[part][2] - parts[part][0], parts[part][3] - parts[part][1], from_coords, to_coords ] logger.debug("Adding %s: %s", xstr(part), xstr(mapping_photo_to_skin[xstr(part)])) # create the skin new_skin = transform_image(64, 64, None, mapping_photo_to_skin) photo.close() return new_skin
if no_gps: print( '\nPhotos that did not get geo-tagged because there was no gps info in the photo\'s metadata:' ) print('\n'.join(no_gps)) # Re-enable idle timer console.set_idle_timer_disabled(False) if __name__ == '__main__': console.clear() # Make sure photos are available... if len(photos.get_assets()) != 0: # Grab all photos in camera roll all_assets = photos.get_assets() # Allow multiple selects assets = photos.pick_asset(all_assets, title='Select Desired Photos', multi=True) else: console.hud_alert('Camera roll is empty') sys.exit() # Were any photos selected? try: count = len(assets) except TypeError: console.hud_alert('No photos selected')
if no_resize: print '\nPhotos that did not get resized because either you chose not to resize, or they were smaller than the minumum size of 1600x1200:' print '\n'.join(no_resize) if no_gps: print '\nPhotos that did not get geo-tagged because there was no gps info in the photo\'s metadata:' print '\n'.join(no_gps) # Re-enable idle timer console.set_idle_timer_disabled(False) if __name__ == '__main__': console.clear() # Make sure photos are available... if len(photos.get_assets()) != 0: # Grab all photos in camera roll all_assets = photos.get_assets() # Allow multiple selects assets = photos.pick_asset(all_assets,title = 'Select Desired Photos', multi=True) else: sys.exit('Camera roll is empty.') # Where any photos selected? try: count = len(assets) except TypeError: sys.exit('No photos selected.') # Default pic sizes fifty = False