def main(): #----- Main process ----- console.clear() if not appex.is_running_extension(): #img = photos.pick_image() console.hud_alert('Must run in appex mod','error') return else: img = appex.get_image(image_type='pil') if img == None: console.alert('No image passed','','Ok',hide_cancel_button=True) return lat,lon, lat_lon_txt = get_gps(img) if not lat or not lon: console.alert('No GPS tags in image','','Ok',hide_cancel_button=True) return # Hide script back = MapView(frame=(0, 0, 540, 620)) back.background_color='white' back.name = 'GPS = '+lat_lon_txt back.present('sheet', hide_title_bar=False) back.set_region(lat, lon, 0.05, 0.05, animated=True) back.add_pin(lat, lon,str((lat, lon)))
def main(): img = None args = sys.argv if appex.is_running_extension(): img = appex.get_image() else: print('running in Pythonista, using test image.') img = PIL.Image.open('test:Mandrill') if img != None: print(img) i0 = img.resize((1600, 1600), PIL.Image.ANTIALIAS) i0.show() print('1600x1600') i1 = img.resize((800, 800), PIL.Image.ANTIALIAS) i1.show() print('800x800') i2 = img.resize((112, 112), PIL.Image.ANTIALIAS) i2.show() print('112x112') i3 = img.resize((56, 56), PIL.Image.ANTIALIAS) i3.show() print('56x56') i4 = img.resize((28, 28), PIL.Image.ANTIALIAS) i4.show() print('28x28')
def main(): """ Script for iOS share extensions in Photos app to remove EXIF data from image when shared. Original image is preserved. Image with no EXIF is saved as JPEG to camera roll with creation date and time as filename. Requires piexif. Add piexif to the site_packages_3 folder or use stash to use pip """ if not appex.is_running_extension(): print("This extension is designed to work with iOS share functionality, select and share photos from the Photos app") else: img = appex.get_image(image_type="pil") if img: if "exif" in img.info: exif_dict = piexif.load(img.info["exif"]) if piexif.ImageIFD.Orientation in exif_dict["0th"]: orientation = exif_dict["0th"][piexif.ImageIFD.Orientation] if piexif.ExifIFD.DateTimeOriginal in exif_dict["Exif"]: date_time = exif_dict["Exif"][piexif.ExifIFD.DateTimeOriginal] path = date_time.decode("utf-8").replace(' ', '') path = path.replace(':', '') path = f"{path}.jpg" else: path = "web_image.jpg" print('No EXIF data') if orientation == 2: img = img.transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 3: img = img.rotate(180) elif orientation == 4: img = img.rotate(180).transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 5: img = img.rotate(-90, expand=True).transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 6: img = img.rotate(-90, expand=True) elif orientation == 7: img = img.rotate(90, expand=True).transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 8: img = img.rotate(90, expand=True) img.save(path, quality = 95) photos.create_image_asset(path) os.remove(path) else: print('No input image found')
def main(): if not appex.is_running_extension(): print('This script is intended to be run from the sharing extension.') return img = appex.get_image() if not img: print('No input image') return if not img.mode.startswith('RGB'): img = img.convert('RGB') gray_img = ImageOps.grayscale(img) clipboard.set_image(gray_img)
def main(): if not appex.is_running_extension(): print('Running in Pythonista app, using test image...') img = Image.open('test:Mandrill') else: img = appex.get_image() if img: # TODO: Your own logic here... print('Converting image to grayscale...') grayscale = img.convert('L') grayscale.show() else: print('No input image found')
def main(): img = None args = sys.argv if appex.is_running_extension(): img = appex.get_image() else: print('running in Pythonista, using test image.') img = Image.open('test:Mandrill') if img != None: i0 = img.resize(scale_size_to_max(img.size, 400), Image.ANTIALIAS) preview = watermark_with_transparency(i0) preview.show()
def run(self, input=''): console.alert(title='Not complete', message='Does not work',button1='Ok',hide_cancel_button=True) if not appex.is_running_extension(): console.alert(title='Error', message='Not running from app extension',button1='Ok',hide_cancel_button=True) else: try: allowMultiple = self.get_param_by_name('allowMultiple').value if allowMultiple: images = appex.get_images() else: images = appex.get_image() ev = ElementValue(type='image',value=images) return ev except error: console.alert(title='Error', message='error: {}'.format(error),button1='Ok',hide_cancel_button=True)
def main(): if not appex.is_running_extension(): img = Image.open('test:Mandrill') else: img = appex.get_image() if not img: print('No input image found') return arr = io.BytesIO() img.save(arr, format='JPEG') text = rekognize_text(arr.getvalue()) res = '\n'.join(text) clipboard.set(res) print(res)
def main(wav_file): # checking if this script is run properly (as an iOS extension) if not appex.is_running_extension(): print('This script is intended to be run from the sharing extension.') return None # gets selected picture picture = appex.get_image(image_type='pil') if not picture: print('No input image') return None # main operation of conversion and creating wav file pixels = np.array(Image.open(picture)) audio = picture_to_wave.image_to_sound(pixels) picture_to_wave.save_wav(wav_file, audio) # playing just created wav file sound.set_volume(1) player = sound.Player(wav_file) player.play()
def main(): if not appex.is_running_extension(): print 'This script is intended to be run from the sharing extension.' return img = appex.get_image() if not img: print 'No input image' return if not img.mode.startswith('RGB'): img = img.convert('RGB') hist = img.histogram() max_h = float(max(hist)) height = 240 with ui.ImageContext(512, height) as ctx: a = 0.5 rgb = [(1, 0, 0, a), (0, 1, 0, a), (0, 0, 1, a)] for i, color in enumerate(rgb): ui.set_color(color) for j, count in enumerate(hist[i * 256:i * 256 + 256]): bar_height = count / max_h * height ui.fill_rect(2 * j, height - bar_height, 2, bar_height) ctx.get_image().show()
def main(): if not appex.is_running_extension(): print('This script is intended to be run from the sharing extension.') return img = appex.get_image() if not img: print('No input image') return if not img.mode.startswith('RGB'): img = img.convert('RGB') hist = img.histogram() max_h = float(max(hist)) height = 240 with ui.ImageContext(512, height) as ctx: a = 0.5 rgb = [(1, 0, 0, a), (0, 1, 0, a), (0, 0, 1, a)] for i, color in enumerate(rgb): ui.set_color(color) for j, count in enumerate(hist[i*256:i*256+256]): bar_height = count / max_h * height ui.fill_rect(2*j, height-bar_height, 2, bar_height) ctx.get_image().show()
def main(): if not appex.is_running_extension(): print('Running standalone, grabbing last picture created') img = photos.get_recently_added_album().assets[-1].get_image() else: img = appex.get_image() if img: print("You passed in an image of size {}x{}".format( img.width, img.height)) if img.width > max_image_size or img.height > max_image_size: print("Scaling down image since it's big") img.thumbnail((max_image_size, max_image_size), Image.ANTIALIAS) print("New size is {}x{}".format(img.width, img.height)) img.show() print('Starting upload... wait for another line to be printed') # open file on server ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('vvn.space', username='******') sftp = ssh.open_sftp() now = datetime.now() filename = "upload-{}-{}-{}_{}-{}-{}.jpg".format( now.year, now.month, now.day, now.hour, now.minute, now.second) file = sftp.file("public_html/" + filename, mode="w") img.save(file, "JPEG", quality=100) file.flush() sftp.close() ssh.close() clipboard.set("http://vvn.space/~vivlim/" + filename) print("done, url copied") else: print('No input image found')
def main(): if not appex.is_running_extension(): print 'Running in Pythonista app, using test image...' img = Image.open('monaLisa.jpeg') else: img = appex.get_image() print sys.argv[1:] if img: note_list = ['piano:A3', 'piano:A3#', 'piano:B3', 'piano:C3', 'piano:C3#', 'piano:C4', 'piano:C4#', 'piano:D3', 'piano:D3#', 'piano:D4', 'piano:D4#', 'piano:E3', 'piano:E4', 'piano:F3', 'piano:F3#', 'piano:F4', 'piano:F4#', 'piano:G3', 'piano:G3#', 'piano:G4', 'piano:G4#'] width, height = img.size resized = False while width > 960 or height > 590: width /= 2 height /= 2 resized = True if resized: img.resize((width, height)) number_of_pixels = width*height desired_duration = 3000 desired_bpm = 240 pixels_per_beat = int(round(number_of_pixels / (desired_bpm*(float(desired_duration)/60.0)))) block_size = (width/pixels_per_beat, height/pixels_per_beat) # (x, y) print block_size, pixels_per_beat colors = [] for y in range(0, height): for x in range(0, width): colors.append(tripleToSingle(img.getpixel((x, y)))) test = Image.new('RGB', (width, height)) color = 0 for y in range(0, height): for x in range(0, width): test.putpixel((x, y), singleToTriple(colors[color])) color += 1 test.show() notes = [] for pixels in range(0, number_of_pixels, pixels_per_beat): group = colors[pixels:pixels+pixels_per_beat] #notes.append(sum(group)/pixels_per_beat) notes.append(max(set(group), key=group.count)) #print(notes) music_image = Image.new('RGB', (width, height)) bunch = 0 count = 0 for y in range(0, height): for x in range(0, width): music_image.putpixel((x, y), singleToTriple(notes[bunch])) count += 1 if count == pixels_per_beat: bunch += 1 count = 0 music_image.show() delay = 1.0/(desired_bpm/60.0) for note in notes: sound.play_effect(note_list[note%len(note_list)]) time.sleep(delay) else: print 'No input image found'
import json import keychain api_key = keychain.get_password('Project Oxford', 'Computer Vision API') if api_key == None: import clipboard api_key = console.input_alert('Insert your API key', '', str(clipboard.get())) if api_key == None: raise Exception('You need an API key.') else: keychain.set_password('Project Oxford', 'Computer Vision API', api_key) if appex.is_running_extension(): image = appex.get_image() else: image = photos.capture_image() if image == None: image = photos.pick_image(original=True) if image == None: raise Exception('You must select one image') enhancerColor = ImageEnhance.Color(image) image = enhancerColor.enhance(0.0) output = StringIO.StringIO() image.save(output, format="PNG") data = output.getvalue()
# coding: utf-8 ## Resize an image (either from external apps' share-sheet, or via photo-roll) import photos, appex, sys, console if appex.is_running_extension(): im = appex.get_image() else: im = photos.pick_image() if im is None: console.hud_alert("No image chosen", "error", 1.0) sys.exit(0) else: assert str(type(im))[8:-2][4:].partition("ImagePlugin")[0] in ("Bmp", "Gif", "Jpeg", "Png", "Ppm", "Tiff") width, height = im.size percentage = int(console.input_alert("Resize image to _%", "Enter number")) fraction = percentage / 100.0 new_width = int(round(width*float(fraction))) new_height = int(round(height*float(fraction))) im2 = im.resize((new_width, new_height)) saved = photos.save_image(im2) if saved: console.hud_alert("Successfully saved resized image ({0}%)".format(int(percentage))) else: console.hud_alert("Unsuccessfully saved resized image ({0}%)".format(int(percentage)), "error")
def generate(): if not appex.is_running_extension(): img = photos.pick_image(show_albums=True) size_field.text = 'Open in Extension to view file size' else: img_path = appex.get_attachments()[0] size_field.text = size_fmt(os.path.getsize(img_path)) img = appex.get_image() if img: exif = get_exif(img) width, height = img.size if width > 3000 or height > 3000: img.thumbnail((1000, 1000)) orientations = { 1: 0, 2: 0, 3: 180, 4: 0, 5: 0, 6: 270, 7: 0, 8: 90 } if exif.get('Orientation'): img = img.rotate(orientations.get(exif['Orientation'], 0)) img_view.image = pil2ui(img) hist = get_histogram(img) hist_view.image = hist if exif.get('FocalLength'): focal_field.text = '%d' % (exif['FocalLength'][0] / exif['FocalLength'][1]) else: focal_field.text = '--' if exif.get('FNumber'): f = exif['FNumber'] aperture_field.text = '%.1f' % (float(f[0]) / f[1]) else: aperture_field.text = '--' if exif.get('ExposureTime'): shutter_field.text = '%d/%d' % exif['ExposureTime'] else: shutter_field.text = '----' iso_field.text = str(exif.get('ISOSpeedRatings', '--')) if exif.get('DateTimeOriginal'): date = datetime.strptime(exif['DateTimeOriginal'], '%Y:%m:%d %H:%M:%S') date_field.text = date.strftime('%B %d, %Y at %H:%M') else: date_field.text = 'No date and time information' wh_field.text = '%d x %d (%.1fMP)' % (width, height, width * height / 1000000.0) camera_field.text = exif.get('Model', 'Unknown') lens = exif.get('LensModel', 'Unknown') lens_field.text = lens artist_field.text = exif.get('Artist', 'Unknown') programs = { 0: 'Unknown', 1: 'Manual', 2: 'Program AE', 3: 'Aperture-priority AE', 4: 'Shutter-priority AE', 5: 'Sleep speed', 6: 'High speed', 7: 'Portrait', 8: 'Landscape', 9: 'Bulb'} program_field.text = programs.get(exif.get('ExposureProgram', 0), 'Unknown') flashes = { 0x0: 'No Flash', 0x1: 'Fired', 0x5: 'Fired, Return not detected', 0x7: 'Fired, Return detected', 0x8: 'On, Did not fire', 0x9: 'On, Fired', 0xd: 'On, Return not detected', 0xf: 'On, Return detected', 0x10: 'Off, Did not fire', 0x14: 'Off, Did not fire, Return not detected', 0x18: 'Auto, Did not fire', 0x19: 'Auto, Fired', 0x1d: 'Auto, Fired, Return not detected', 0x1f: 'Auto, Fired, Return detected', 0x20: 'No flash function', 0x30: 'Off, No flash function', 0x41: 'Fired, Red-eye reduction', 0x45: 'Fired, Red-eye reduction, Return not detected', 0x47: 'Fired, Red-eye reduction, Return detected', 0x49: 'On, Red-eye reduction', 0x4d: 'On, Red-eye reduction, Return not detected', 0x4f: 'On, Red-eye reduction, Return detected', 0x50: 'Off, Red-eye reduction', 0x58: 'Auto, Did not fire, Red-eye reduction', 0x59: 'Auto, Fired, Red-eye reduction', 0x5d: 'Auto, Fired, Red-eye reduction, Return not detected', 0x5f: 'Auto, Fired, Red-eye reduction, Return detected', 0x60: 'Unknown'} flash_field.text = flashes.get(exif.get('Flash', 0x60)) zoom_text = 'Unknown' if (lens == 'iPhone 7 Plus back iSight Duo camera 6.6mm f/2.8'): zoom_text = '2x Optical on Duo Camera' if exif.get('DigitalZoomRatio'): z = exif['DigitalZoomRatio'] zoom_text = '%.2gx Digital' % (float(z[0]) / z[1]) zoom_field.text = zoom_text software_field.text = exif.get('Software', 'Unknown') meterings = { 0: 'average.png', 1: 'average.png', 2: 'center-weighted.png', 3: 'spot.png', 4: 'spot.png', 5: 'average.png', 6: 'partial.png', 255: 'average.png' } metering_view.image = ui.Image(meterings.get(exif.get('MeteringMode', 0), 'average.png')) if exif.get('WhiteBalance') == 1: balance_field.text = 'MWB' if exif.get('GPSInfo'): try: lat = [float(x)/float(y) for x, y in exif['GPSInfo'][2]] latref = exif['GPSInfo'][1] lon = [float(x)/float(y) for x, y in exif['GPSInfo'][4]] lonref = exif['GPSInfo'][3] lat = lat[0] + lat[1]/60 + lat[2]/3600 lon = lon[0] + lon[1]/60 + lon[2]/3600 if latref == 'S': lat = -lat if lonref == 'W': lon = -lon geolocator = Nominatim() loc_str = '%f, %f' % (lat, lon) location_field.text = loc_str + '\nDecoding location...' location = geolocator.reverse(loc_str) location_field.text = location.address except KeyError: location_field.text = 'No location data found' else: location_field.text = 'No location data found' return True else: hud_alert('No valid photo selected', icon='error') return False
feature = feature.reshape((-1), numpy.prod(feature.shape[1:])) if return_indices: return feature, indices else: return feature #-------------Main--------------------------------- if __name__ == '__main__': #--------------------Read image-------------------- if not appex.is_running_extension(): print('Running in Pythonista app, using test image...') img = Image.open('test:Mandrill') else: img = appex.get_image() img = img.convert('L') img = numpy.array(img) print(img.shape) import time #----------Get HOG using a standard hog()---------- t1 = time.time() fd, hog_image = hog(img, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(3, 3), block_norm='l1', feature_vector=False, transform_sqrt=True,