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
예제 #2
0
파일: model.py 프로젝트: marksard/InstaSign
    def __get_watermark(self, image_object, watermark, file_date):
        if watermark.index == 2:
            exif_table = self.__get_exif(image_object)
            exif_date_string = exif_table.get("DateTimeOriginal")

            if exif_date_string is None:
                ret = console.alert(
                    'exif error',
                    'It selected image is not EXIF. Would you select original image file? (if cancel, use file creation date.)',
                    'OK',
                    'Cancel',
                    hide_cancel_button=True)
                if ret == 1:
                    image, file_date = photos.pick_asset().get_image()
                    #image = self.__get_image()
                    exif_table = self.__get_exif(image)
                    exif_date_string = exif_table.get("DateTimeOriginal")

            if exif_date_string is not None:
                exif_date = datetime.strptime(exif_date_string,
                                              '%Y:%m:%d %H:%M:%S')
                exif_date_reformat = exif_date.strftime(watermark.text2)
                return exif_date_reformat
            return file_date.strftime(watermark.text2)
        if watermark.index == 1:
            return watermark.text1
        else:
            return watermark.text0
예제 #3
0
def pick_image():
	
	a = photos.pick_asset()
	i = a.get_ui_image()
	b = i.to_jpeg()
	
	return rekognize_text(b)
예제 #4
0
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()
예제 #5
0
def choose_assets():
    search = dialogs.input_alert('What is your album called?')

    albums = photos.get_albums()
    albums = list([a for a in albums if search in a.title])
    albums = list([a for a in albums if get_album_ends(a)[0] is not None])

    if len(albums) == 0:
        dialogs.hud_alert('No album found!', icon='error')
        return None

    album_names = [
        {
            'id':
            a.local_id,
            'index':
            i,
            'title':
            "{0} ({1})".format(a.title,
                               get_album_dates(a)[0].strftime('%b %d, %Y')),
            #'image': get_asset_thumb(get_album_ends(a)[0]),
            'accessory_type':
            'checkmark'
        } for (i, a) in enumerate(albums)
    ]
    album = dialogs.list_dialog('Choose Album', album_names)

    if album is None: return None

    album_index = album['index']
    assets = photos.pick_asset(albums[album_index], 'Choose Photos', True)

    return assets
예제 #6
0
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() )
예제 #7
0
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)
예제 #8
0
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()
예제 #9
0
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
예제 #10
0
파일: model.py 프로젝트: marksard/InstaSign
 def __get_image(self):
     try:
         asset = photos.pick_asset(title='select')
         if asset is not None:
             return asset.get_image(), asset.creation_date
         else:
             print('no asset')
     except:
         print('exception: get_image')
         return None, None
     return None, None
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
예제 #12
0
    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
예제 #13
0
 def pick_image_action(self, sender):
     a = photos.get_favorites_album()
     if a:
         assets = a.assets
         if assets:
             asset = photos.pick_asset(assets=assets,
                                       title='Pick a photo ...')
         else:
             asset = photos.pick_asset()
         if asset:
             # imageView.image = asset.get_ui_image()
             crdate = asset.creation_date
             if crdate:
                 self._now_img = crdate
                 self._now = self._now_img
                 imageView = self._ui['ImageView']
                 imageView.image = asset.get_ui_image(
                     size=[imageView.x, imageView.y], crop=False)
                 self._info_msg('Image selected')
                 self._ui_set_context(Contexts.IMAGE.value)
                 self._calc()
                 self._button_action(sender)
예제 #14
0
def parse_image(index=-1, picker=False):
    asset = None
    if picker:
        asset = photos.pick_asset(title='Choose Image', multi=False)
    else:
        asset = photos.get_screenshots_album().assets[index]
    # print("retrieved asset: ", asset, "\n")

    image = asset.get_image()
    image = downsample(image)
    # image.show()

    main_areas = (((0., 0.), (0.827, 1.)), ((0.827, 0.), (1., 0.603)),
                  ((0.827, 0.603), (1., 1.)))
    board, colorpicker, controls = segment_image(image, main_areas)

    #colorpicker.show()
    #board.show()

    cp_hue_im = get_hue(colorpicker)
    create_histogram(cp_hue_im)
    cp_hue_im.show()

    board_hue_im = get_hue(board)
    create_histogram(board_hue_im)
    board_hue_im.show()

    colors = find_colors(cp_hue_im.histogram())
    # print(colors)

    s_coords = generate_sampling_coordinates()
    im_coords = map_to_image(board.size, s_coords)

    # draw = ImageDraw.Draw(board)
    # for p in im_coords:
    #     draw.point(p, 'white')
    # board.show()

    # board_hue_im.show()
    hues = [board_hue_im.getpixel(point) for point in im_coords]

    classified = list(map(lambda x: classify_hue(colors, x), hues))
    classified = [[classified[y + (10 * x)] for y in range(10)]
                  for x in range(29)]
    # for row in classified:
    #     print(row)

    #return colors, classified#, [board, colorpicker, controls]
    return colors, classified, [board, colorpicker, controls]
예제 #15
0
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)
예제 #16
0
 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()
예제 #17
0
def add():
	f=open("imageList.txt","a")
	
	fail = 0
	
	id = photos.pick_asset(title='Pick some assets', multi=False)

	try:
		if id == None:
			fail = 1
	except:
		pass
		
	if fail == 0:
		if debug == 1:
			print(id)
			
		g=str(id)
		g=g.strip()
		g=g.strip("<Asset")
		g=g.split("image")
		g2=g[0]
		g2=g2.strip(" - ")
		
		if debug == 1:
			print("\n")
			
		if debug == 1:
			print(g2)
			
		d=input("Name of this image: ")
		d=d.strip()
		d=d.lower()
		name=d+":"+g2
		name+="\n"
		f.write(name)
예제 #18
0
    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
예제 #19
0
# https://forum.omz-software.com/topic/3299/get-filenames-for-photos-from-camera-roll/13

import photos
from objc_util import *
from ftplib import FTP
import console
p = photos.pick_asset(assets=photos.get_assets(media_type='video'))
file_name = str(ObjCInstance(p).valueForKey_('filename'))
b = p.get_image_data()
try:
    ftp = FTP('Server')  #connect
    ftp.encoding = 'utf-8'
    ftp.login('User', 'pwd')
    ftp.storbinary('STOR ' + file_name, b)
    ftp.close()
except Exception as e:
    console.alert('Error ', str(e), 'ok', hide_cancel_button=True)
loc_file = open(file_name, mode='wb')
loc_file.write(b.getvalue())
loc_file.close()
예제 #20
0
import photos, PIL, os

pic_to_resize = photos.pick_asset()
img = pic_to_resize.get_image()
all_folders = photos.get_albums()
for album in all_folders:
    if album.title == 'medium-sized':
        meds = album
new_size = (int(pic_to_resize.pixel_width / 3),
            int(pic_to_resize.pixel_height / 3))
img_med = img.resize(new_size, PIL.Image.ANTIALIAS)
img_med.save('img_med.jpg')
new_med = photos.create_image_asset('img_med.jpg')
meds.add_assets([new_med])
try:
    os.remove('img_med.jpg')
except OSError:
    pass
예제 #21
0
load_framework('Vision')
VNRecognizeTextRequest = ObjCClass('VNRecognizeTextRequest')
VNImageRequestHandler = ObjCClass('VNImageRequestHandler')
VNDetectTextRectanglesRequest = ObjCClass('VNTextObservation')

# Prompts user to select photo from Camera or Photos app
selection = dialogs.alert('Get image', button1='Camera', button2='Photos')

language = ['en']
image = None

if selection == 1:
    image = photos.capture_image()
elif selection == 2:
    image = photos.pick_asset().get_image()

if image is not None:
    print('Recognizing text...\n')

    buffer = io.BytesIO()
    image.save(buffer, format='PNG')
    image_data = buffer.getvalue()

    req = VNRecognizeTextRequest.alloc().init().autorelease()
    req.setRecognitionLanguages_(language)
    handler = VNImageRequestHandler.alloc().initWithData_options_(
        image_data, None).autorelease()

    success = handler.performRequests_error_([req], None)
예제 #22
0
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')
예제 #23
0
        png_data = uiimage_to_png(ObjCInstance(ui_img))
        return png_data


quiltImages = []
done = False

# 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:
    chosen_pic = photos.pick_asset(assets=my_album.assets,
                                   title='Select a portrait photo')
    filename, file_extension = os.path.splitext(
        str(ObjCInstance(chosen_pic).originalFilename()))
    assert filename != 'None'
    output_filename = 'Holo_' + filename + '.png'
except:
    quit()

print('Step 1/6 - Extracting a depth map')
chosen_pic_image = chosen_pic.get_image(original=True)
chosen_pic_data = chosen_pic.get_image_data(original=True).getvalue()

chosen_pic_depth = CImage(ns(chosen_pic_data)).to_png()
chosen_pic_depth_stream = io.BytesIO(chosen_pic_depth)
chosen_pic_depth_image = Image.open(chosen_pic_depth_stream)
예제 #24
0
from scene import *
import photos, Image, ImageDraw, evolver, math

w = 254
h = 254
opacity = 125

controls = [[0, w], [0, h], [0, w / 4], [0, h / 4], [0, 255], [0, 255],
            [0, 255]]
population = 40
parents = 20
mrate = 0.05
figures = 300

moments = photos.get_albums()
asset = photos.pick_asset(moments[4], title='Pick your image', multi=False)
img = asset.get_image()
img = img.convert('RGB')

#scale photo to fit half the screen
width = img.size[0]
height = img.size[1]
widthratio = width / (w)
heightratio = height / h
if widthratio > heightratio:
    scale = widthratio
else:
    scale = heightratio
if scale != 1:
    width = int(width / scale)
    height = int(height / scale)
예제 #25
0
  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
  custom = False
  none = False
  ok = False
  
def main():
    all_assets = photos.get_assets()
    asset = photos.pick_asset(assets=all_assets)
    if asset is None:
        return
    classify_asset(asset)
예제 #27
0
# Show an image picker dialog (allowing multiple selection) and print the result

import photos
assets = photos.pick_asset(title='Pick photo', multi=False)
print(assets)
예제 #28
0
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
예제 #29
0
# coding: utf-8

# https://forum.omz-software.com/topic/3728/having-trouble-writing-a-video-file-to-local-storage-ends-up-corrupted

import vimeo
import photos
from io import BytesIO
from objc_util import ObjCInstance

client = vimeo.VimeoClient(token='my_api_token')

video_asset = photos.pick_asset()
video_data = video_asset.get_image_data()
video_bytes = video_data.getvalue()
filename = str(ObjCInstance(video_asset).filename())

with open(filename, 'wb') as video:
    video.write(video_bytes)
video.close()

video_uri = client.upload(filename)
예제 #30
0
import photos

# Pick multiple images (with transparency) from the camera roll, crop them by their bounding box and save them back to the camera roll inside of a user defined Album.

#album=photos.create_album('Test')

cropped = []
converted = []

assets = photos.pick_asset(title='pick some assets', multi=True)
print(assets)


def crop_all(L):
    try:
        for asset in L:
            # get the original(True) image of the asset, crop it by the imagers bounding box and show it.
            asset.get_image(True).crop(asset.get_image(True).getbbox()).show()
            cropped.append(
                asset.get_image(True).crop(asset.get_image(True).getbbox()))
            converted.append(photos.create_image_asset(asset))
        #album.add _assets(L)
    except:
        None


crop_all(assets)

print(converted)
#print(cropped)
예제 #31
0
    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)
generator=ObjCClass('AVAssetImageGenerator').alloc().initWithAsset_(asseturl)
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()
예제 #33
0
        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')
        sys.exit()

    # Default pic sizes
    fifty = custom = none = ok = False