Ejemplo n.º 1
0
def geolocate_img(s_img, gps_cords, timestamp=None):
    """ add GPS data and timestamp to image """
    img = gpsphoto.GPSPhoto(s_img)

    if timestamp is not None:
        info = gpsphoto.GPSInfo(gps_cords, timeStamp=timestamp)
    else:
        info = gpsphoto.GPSInfo(gps_cords)

    img.modGPSData(info, s_img)
Ejemplo n.º 2
0
def set_gps(filePath):
    # get GPS coordinates
    try:
        resp = requests.get("https://www.marinetraffic.com/map/getvesseljson/shipid:" + marineTrafficId,
                            headers=headers)
    except Exception as e:
        log("marinetraffic not reached",e)
        raise NoGPSInfoException
    longitude = resp.json()["LON"]
    latitude = resp.json()["LAT"]

    # set gps in exif
    photo = gpsphoto.GPSPhoto(filePath)
    info = gpsphoto.GPSInfo((float(latitude), float(longitude)))
    photo.modGPSData(info, filePath)

    # remove broken gps exif data
    brokenImg = Image.open(filePath)
    exif_dict = piexif.load(brokenImg.info["exif"])
    exif_dict["GPS"].pop(piexif.GPSIFD.GPSProcessingMethod, None)
    exif_bytes = piexif.dump(exif_dict)

    folder = createFolderIfPossible()

    try:
        filePath = os.path.join(folder, shipName + datetime.now(timeZone).strftime(DATE_FORMAT_FILE) + ".jpg")
        brokenImg.save(filePath, exif=exif_bytes)
    except Exception as e:
        log("failed to save manipulated exif data", e)
        raise NoGPSInfoException
Ejemplo n.º 3
0
def main():
    """Get center coordinate using GDAL, then add to EXIF metadata"""

    args = get_args()

    if not os.path.isdir(args.outdir):
        os.makedirs(args.outdir)

    # Scan for tif images in input directory
    images = glob.glob(args.dir + "*.tif", recursive=True)
    
    num = 0
    for i in images:
        num += 1
        ds = gdal.Open(i)
        meta = gdal.Info(ds)
        coord_list = []
        lines = meta.splitlines()

        for line in lines:
            if 'Center' in line:
                location = ' '.join(line.split()[:1]).strip('()')
                lat_dec = ' '.join(line.split()[2:3]).strip('()')
                long_dec =  ' '.join(line.split()[1:2]).strip('(),')
                print(f'{num}: ' + i + "\n" + 'Lat, Long: ' + f'({lat_dec}, {long_dec})' + "\n")

        filename = os.path.splitext(os.path.basename(i))[0]
        photo = gpsphoto.GPSPhoto(i)
        info = gpsphoto.GPSInfo((float(lat_dec), float(long_dec)))
        photo.modGPSData(info, args.outdir + filename + '_exif.tif')

    print(f'Done, images saved in {args.outdir}')
Ejemplo n.º 4
0
 def saveResults(self,loc,**kwargs):
     ''' Use the links from above to download the images; rename and tag them '''
     timestamp = humandate(time.time())[:-7]
     loc['results'].download_links(self.settings["IMGDIR"])
     numf = len(loc['results'].links)
     GSVHEADER='GSV_' + loc['rtname'] + \
             "_p" + str(self.settings['PITCH']) + "_" + timestamp + "_"        
     headinglst = self.settings['HEADINGS'].split(";")
     imnamelst = []
     nfnlst = []
     for fct in range(0,numf):
         ''' Give the file a unique name '''
         try:
             fn = loc['results'].metadata[fct]['_file']
         except:
             self.logger.error("Filename not found -- skip point")
             continue
         ffn = os.path.join(self.settings["IMGDIR"],fn)
         newfn = os.path.join(self.settings["IMGDIR"],GSVHEADER+fn).replace("gsv_","").replace("_p","_h%s_p" % headinglst[fct])
         nfnlst.append(newfn)
         self.logger.debug("%s to %s" % (fn,newfn))
         if not os.path.isfile(ffn):
             self.logger.error(ffn," does not exist")
             continue
         os.rename(ffn,newfn)
     
         ''' Add metadata '''
         loctup = (float(loc['lat']),float(loc['lng']))
         photo = gpsphoto.GPSPhoto(newfn)
         if 'alt' in loc:
             altv = loc['alt']
         else:
             altv = 0
         info = gpsphoto.GPSInfo((loctup),alt=altv)
         photo.modGPSData(info, newfn)
         imnamelst.append(newfn)
         
     ''' Display the images '''
     if self.settings['PLOTON']:
         imlst = []
         for im in imnamelst:
             imlst.append(Image.open(im))
         ''' Get the Map '''
         if self.settings['MAPON']:
             cntr = "{0},{1}".format(loctup[0],loctup[1])
             mapim = self.getMap(cntr)
             nfnlst.append('{}/tmpmap.png'.format(self.settings['IMGDIR']))
             imlst.append(mapim)
         title = "{} at {}".format(loc['rtname'],loc['locstr']) \
                 if 'TITLE' not in self.settings else self.settings['TITLE']
         self.plotImages(imlst,xpos=self.settings['XPOS'],ypos=self.settings['YPOS'],title=title)
         
     if self.settings['CLEAN']:
         self.logger.debug("Deleting downloaded files: {}".format(nfnlst))
         for fn in nfnlst:
             if os.path.isfile(fn):
                 os.remove(fn)
def Extract_hands(stack_l,
                  stack_r,
                  no,
                  no_l,
                  no_r,
                  area_img,
                  iou_thr,
                  frame,
                  buffer_fps=7):
    global c11, c21, radius1, c12, c22, radius2
    count = 0
    if ((no - no_r) % buffer_fps == 0):
        stack_r.append((0, 0, 0))

    if ((no - no_l) % buffer_fps == 0):
        stack_l.append((0, 0, 0))
    if (len(stack_l) == 1):
        (c11, c21, radius1) = stack_l.pop()
    if (len(stack_r) == 1):
        (c12, c22, radius2) = stack_r.pop()
    if (radius1 and radius2):

        intersecting_area = intersecting(c11, c21, radius1, c21, c22, radius2)

        total_area = math.pi * (radius2**2 + radius1**2)
        # iou_normalized = (iuo_area/(math.pi*radius*radius))*area_img
        # print(np_p)
        iou = intersecting_area / total_area
        iou_normalized = iou / area_img
        print("iou >>", iou)
        print("iou_norm=>", iou_normalized)
        flag = False
        if ((iou > iou_thr)):
            flag = True

        cv.putText(frame, "Searching", (100, 20), cv.FONT_HERSHEY_SIMPLEX, 1,
                   (0, 255, 0))

        if (flag):
            cv.putText(frame, "Rescuse Detected", (100, 20),
                       cv.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255))
            print("*****************FOUND TRAPPED*****************")
            print("UR MOM IS AT ", vehicle.location.global_frame)
            cv.imwrite("lost_mom_found.jpg", saveFrame)
            lat = vehicle.location.global_frame.lat
            lon = vehicle.location.global_frame.lon
            alt = vehicle.location.global_frame.altitude
            photo = gpsphoto.GPSPhoto("lost_mom_found.jpg")
            info = gpsphoto.GPSInfo((lat, lon), alt=alt)
            photo.modGPSData(info, "lost_mom_found.jpg")
            count += 1
            flag = False

    return stack_l, stack_r
Ejemplo n.º 6
0
def edit_exif(path, gps_data):
    '''
	Takes gps coordinates and inserts them to the picture's metadata
	:param path : (str) path to picture
	:param gps_data : (tuple) (latitude, longitude)
	
	'''

    photo = gpsphoto.GPSPhoto(path)
    info = gpsphoto.GPSInfo(gps_data)
    photo.modGPSData(info, path)
Ejemplo n.º 7
0
def geotag(df):
    os.mkdir('geotagged_'+track_name+'/')
    i = 0
    sys.stdout.flush()
    for frame in tqdm(df['frame'],desc='Geotagging '+ str(len(df['frame'])) + ' frames to path: '+'geotagged_'+track_name+'/',unit='frames'):
        photo = gpsphoto.GPSPhoto('frames/'+frame)
        info = gpsphoto.GPSInfo((df.loc[i, 'latitude'], 
                                 df.loc[i, 'longitude']), 
                                alt=int(df.loc[i, 'elevation']), 
                                timeStamp=df.loc[i, 'timestamp'])
        photo.modGPSData(info, 'geotagged_'+track_name+'/'+ frame)
        i+=1
Ejemplo n.º 8
0
def add_lost_and_found(mybasedir):
    os.chdir(mybasedir)
    for photofile in glob.glob("*.jpg"):
        petid = photofile.split('_')[0]
        if petid in list95138:
            gps = geodict["95138"]
        elif petid in list75093:
            gps = geodict["75093"]
        elif petid in list47907:
            gps = geodict["47907"]
        elif petid in list27712:
            gps = geodict["27712"]
        photo = gpsphoto.GPSPhoto(photofile)
        info = gpsphoto.GPSInfo(gps)
        photo.modGPSData(info, photofile)
Ejemplo n.º 9
0
    def get_picture(self):
        """
        Takes and saves a picture from zumi front cam
        GPS Information are added to the image
        """
        frame = self.zumi.get_picture()

        jpg_name = "{}/Zumicam_{}.jpeg".format(self.directory_two, datetime.now().strftime("%H-%M-%S"))
        jpg_name_gps = "{}/Zumicam_{}_GPS.jpeg".format(self.directory_two, datetime.now().strftime("%H-%M-%S"))

        cv2.imwrite(jpg_name, img=np.array(frame))

        photo = gpsphoto.GPSPhoto(jpg_name)
        info = gpsphoto.GPSInfo(((float(self.position.last_y) / 100), (float(self.position.last_x) / 100)))
        photo.modGPSData(info, jpg_name_gps)
        return frame
Ejemplo n.º 10
0
def GeoTagAlt(x, photopath, startpath, d_t, dtCombined):

    #moet nog if statement komen voor als file niet gevonden kan worden, of als kolom data types niet kloppen
    #moet nog data check komen op csv, want gpsphoto stelt bepaalde eisen aan de waardes, anders error

    #check if .jpg is in row string, only work with positive results
    if ".JPG" in str(x.Photo):

        file = os.path.join(photopath,
                            x.Photo)  #identify image corresponding to csv row
        print(x.Photo)  #report progress to terminal
        fileNew = os.path.join(
            new_folder, 'GEO' + d_t +
            x.Photo)  #set up directory and name for resulting tagged image
        pic = gpsphoto.GPSPhoto(file)  #open image orresponding to csv row
        #-----------------------------------------------------------------------------#
        #this whole part is needed to convert the DateTime entry to the required format of 'YYYY:MM:DD hh:mm:ss'
        #sadly this procedure will likely have to be changed per csv style...current style: 'YYYY/MM/DD hh:mm:ss.mill'

        if not dtCombined:
            DateTime = str(x.Date) + " " + str(x.Time)

        else:
            DateTime = str(x.DateTime)

        if "/" in DateTime:  #replace date delimiter '/' by ':'
            Dsep = DateTime.split("/")
            DateForm = Dsep[0] + ":" + Dsep[1] + ":" + Dsep[2]
        else:
            DateForm = DateTime

        if "." in DateForm:
            DateTimeForm = DateForm.split(
                ".")  #eliminate .milliseconds part of Timestamp
            DTstamp = str(DateTimeForm[0])

        else:
            DTstamp = DateForm
        #-----------------------------------------------------------------------------#
        #format all info to be attached to resulting image
        info = gpsphoto.GPSInfo((x.Lat, x.Long),
                                alt=int(x.Alt),
                                timeStamp=DTstamp)
        #attach
        pic.modGPSData(info, fileNew)

    return
Ejemplo n.º 11
0
    def test_metadata_gps(self):  ### CHECKED ###
        # Case: the database processing should be able to detect
        # GPS data adequately in files and put that in the database.
        # If a file doesn't have GPS data, it should get a -999 in
        # both latitude and longitude.
        # Expected outcome: pretty much that. I'm randomizing
        # GPS values in ~half of the images, writing to the JPG,
        # and expecting to get that same data back and put it in
        # the database. gpsphoto seems to have small bugs in a couple
        # things, so I'm catching OS and Key errors for that.

        for file in self.goodFiles:
            # Random select if the photo will have GPS data
            rv = random.randint(0, 1)
            photo = gpsphoto.GPSPhoto(file)
            if rv == 1:
                try:
                    # Create GPSInfo Data Object
                    lat = (random.random() - 0.5) * 180
                    lon = (random.random() - 0.5) * 360
                    info = gpsphoto.GPSInfo((lat, lon))
                    # Modify GPS Data
                    photo.modGPSData(info, file)
                    create_image_file(file)
                    fdata = ImageFile.objects.filter(filename=file)
                    # Due to rounding precision in GPS, not every decimal
                    # is represented, so we assert that the stored and
                    # actual values are within a small margin.
                    self.assertTrue(abs(fdata[0].gps_lat_decimal - lat) < 0.01)
                    self.assertTrue(abs(fdata[0].gps_lon_decimal - lon) < 0.01)
                except OSError:
                    pass
                except KeyError:
                    pass
            else:
                # Get the file. Some files have GPS built in already, so I either
                # check that there was no GPS there and both fields are set to
                # default, or make the not-unreasonable assumption that the
                # lat and lon are different and assert such.
                create_image_file(file)
                fdata = ImageFile.objects.filter(filename=file)
                if fdata[0].gps_lat_decimal == -999:
                    self.assertEqual(fdata[0].gps_lon_decimal, -999)
                else:
                    self.assertNotEqual(fdata[0].gps_lat_decimal,
                                        fdata[0].gps_lon_decimal)
Ejemplo n.º 12
0
def add_all(mybasedir):
    os.chdir(mybasedir)
    for petid in os.listdir("./"):
        if os.path.isdir(mybasedir + petid):
            os.chdir(mybasedir + petid)
            if petid in list95138:
                gps = geodict["95138"]
            elif petid in list75093:
                gps = geodict["75093"]
            elif petid in list47907:
                gps = geodict["47907"]
            elif petid in list27712:
                gps = geodict["27712"]
            for photofile in glob.glob("*.jpg"):
                photo = gpsphoto.GPSPhoto(photofile)
                info = gpsphoto.GPSInfo(gps)
                photo.modGPSData(info, photofile)
            os.chdir(mybasedir)
Ejemplo n.º 13
0
 def tagAssetWithCoords(self, asset, latitude, longitude, altft=1):
     img_coords = (float(latitude), float(longitude))
     img_timestamp = datetime.now().strftime("%Y:%m:%d %H:%M:%S")
     filename = asset.getActiveFile()
     # case jpgs
     if asset.ext == 'jpg' or asset.ext == 'jpeg':
         # create a GPSPhoto Object
         photo = gpsphoto.GPSPhoto(filename)
         # create GPSInfo Data Object
         info = gpsphoto.GPSInfo(img_coords,
                                 alt=altft,
                                 timeStamp=img_timestamp)
         # modify GPS Data
         photo.modGPSData(info, filename)
     # case pngs
     elif asset.ext == 'png':
         print('cannot GEOTag PNGs yet')
     # case gifs
     elif asset.ext == 'gif':
         print('cannot GEOTag PNGs yet')
     return True
Ejemplo n.º 14
0
        for point in segment.points:
            # Kind of just assuming this shit is in order.
            point_list.append((
                point.time,
                Point(latitude=point.latitude,
                      longitude=point.longitude,
                      elevation=point.elevation),
            ))


def find_closest_points(image_time_utc: datetime, points: List) -> tuple:
    # LOL so inefficient
    start = None
    end = None
    for i, p in enumerate(points):
        # TODO handle the beginning / end of this list
        if p[0] < image_datetime < points[i + 1][0]:
            next_point = points[i + 1]
            # Earth is flat, screw it
            mid_point_y = (p[1]["latitude"] + next_point[1]["latitude"]) / 2
            mid_point_x = (p[1]["longitude"] + next_point[1]["longitude"]) / 2
            alt = (p[1]["elevation"] + next_point[1]["elevation"]) / 2
    return (mid_point_y, mid_point_x, alt)


y, x, alt = find_closest_points(image_time_utc, point_list)
info = gpsphoto.GPSInfo((y, x), timeStamp=image_datetime, alt=int(alt))

new_image = current_image_path.split(".jpg")[0] + "_with_gps.jpg"
gps_photo.modGPSData(info, new_image)
for image in images:
    if ".JPG" in image:
        imageNameTime = image.split('.')[0]
        dbTime = "2020-09-05 " + str(
            int(imageNameTime[0:2]) -
            6) + ":" + imageNameTime[2:4] + ":" + imageNameTime[4:6]
        utcTime = "2020-09-05 " + str(
            int(imageNameTime[0:2]) -
            0) + ":" + imageNameTime[2:4] + ":" + imageNameTime[4:6]

        # Get assoc GPS coords
        mycursor.execute(
            "SELECT lat,lng,alt FROM gpsUpdates ORDER BY abs(TIMESTAMPDIFF(second, timestamp, '"
            + dbTime + "')) LIMIT 1")

        myresult = mycursor.fetchone()

        # print(image,myresult)

        photo = gpsphoto.GPSPhoto(imageDir + "/" + image)

        # Create GPSInfo Data Object
        info = gpsphoto.GPSInfo((float(myresult[0]), float(myresult[1])),
                                alt=int(myresult[2]),
                                timeStamp=utcTime.replace('-', ':'))

        # Modify GPS Data
        photo.modGPSData(info, '/mnt/c/Users/blaze/Desktop/procPics/' + image)

        print(image)
Ejemplo n.º 16
0
# -*- coding: utf-8 -*-

from GPSPhoto import gpsphoto
#读取GPS信息
photo = gpsphoto.GPSPhoto('黄河源头.jpg')
photo.getGPSData()
'''
{'Latitude': 35.019564,
 'Longitude': 95.990063,
 'Altitude': 0,
 'UTC-Time': '18:58:14',
 'Date': '05/31/2020'}
'''

#写入GPS坐标
photo = gpsphoto.GPSPhoto('牛头碑.jpg')
info = gpsphoto.GPSInfo((34.908458, 97.492676))
photo.modGPSData(info, 'new_photo.jpg')
#把new_photo.jpg转到iPad上查看地图
Ejemplo n.º 17
0
def addLocation(fileName, locationData):
    photo = gpsphoto.GPSPhoto(fileName)
    longitude = locationData['longitudeE7'] / 1e7
    latitude = locationData['latitudeE7'] / 1e7
    info = gpsphoto.GPSInfo((latitude, longitude))
    photo.modGPSData(info, fileName)
Ejemplo n.º 18
0
def match(videos=['null'],
          tracks=['null'],
          inputPath=False,
          projectPath=False,
          autoscan=True,
          maxTimeDifference=1.0):
    now = datetime.now()

    #MANAGE PATH
    if inputPath == False:
        inputPath = os.getcwd() + '\\'
    if projectPath == False:
        projectPath = os.getcwd() + '\\'
    if inputPath[-1] != '/':
        if inputPath[-1] != '\\':
            inputPath = inputPath + '\\'
    if projectPath[-1] != '/':
        if projectPath[-1] != '\\':
            projectPath = projectPath + '\\'

    #MANAGE CREATE PROJECT
    createProject = True
    projectName = 'project' + time.strftime("%d-%b-%Y_%H.%M.%S")
    if 'projects' not in os.listdir(projectPath):
        os.mkdir(projectPath + 'projects/')
    if projectName not in os.listdir(projectPath + 'projects/'):
        os.mkdir(projectPath + 'projects/' + projectName)
    projectPath += '/projects/' + projectName + '/'

    #MANAGE AUTOSCAN
    if autoscan == True:
        videos = []
        tracks = []
        for filename in os.listdir(inputPath):
            if 'MP4' in filename.split('.'):
                if len(filename.split('.')) <= 2:
                    videos.append(filename)
            if 'gpx' in filename.split('.'):
                if len(filename.split('.')) <= 2:
                    tracks.append(filename)
            if 'csv' in filename.split('.'):
                if len(filename.split('.')) <= 2:
                    tracks.append(filename)
        inputDF = pd.DataFrame()
        inputDF['Videos'] = videos
        inputDF['Tracks'] = tracks
        if 'input' not in os.listdir(projectPath):
            os.mkdir(projectPath + 'input/')
        inputDF.to_csv(projectPath + 'input/inputFiles.csv')

    #READ DATA INTO DATAFRAMES
    framesDF = pd.DataFrame()
    pointsDF = pd.DataFrame()
    if createProject == True:
        for video in videos:
            framesDF = framesDF.append(vTk.getTimestamps(inputPath,
                                                         video,
                                                         projectPath,
                                                         export=True),
                                       ignore_index=True)
        for track in tracks:
            pointsDF = pointsDF.append(tTk.trackExtract(
                inputPath, track, projectPath),
                                       ignore_index=True)
    else:
        timestampDFs = [
            x for x in os.listdir(projectPath + 'timestamps/')
            if x.split('.')[-1] == 'csv'
        ]
        for x in timestampDFs:
            framesDF = framesDF.append(pd.read_csv(projectPath +
                                                   'timestamps/' + x),
                                       ignore_index=True)
        pointDFs = [
            x for x in os.listdir(projectPath + 'tracks/')
            if x.split('.')[-1] == 'csv'
        ]
        for x in pointDFs:
            pointsDF = pointsDF.append(pd.read_csv(projectPath + 'tracks/' +
                                                   x),
                                       ignore_index=True)
        framesDF['Timestamp'] = [
            dateparser.parse(i) for i in framesDF['Timestamp']
        ]
        pointsDF['timestamp'] = [
            dateparser.parse(i) for i in pointsDF['timestamp']
        ]

    #MATCH POINTS TO CLOSEST FRAME OR SET UNDEFINED IF INSUFFICIENT TIME DIFFERENCE
    taggedDF = pointsDF
    i = 0
    for pointTime in tqdm(pointsDF['timestamp'],
                          desc='Matching: ' + str(videos) + ' and: ' +
                          str(tracks),
                          unit='frames'):
        timedeltas = [
            abs((pointTime - frameTime).total_seconds())
            for frameTime in framesDF['Timestamp']
        ]
        if min(timedeltas) <= maxTimeDifference:
            closestFrame = framesDF.loc[timedeltas.index(min(timedeltas)),
                                        'Frame']
            taggedDF.loc[i, 'Frame'] = closestFrame
        else:
            taggedDF.loc[i, 'Frame'] = float('nan')
        i += 1

    #DROP UNDEFINED POINTS FROM DF
    taggedDF = taggedDF.dropna()
    taggedDF = taggedDF.reset_index(drop=True)

    #CREATE FRAMES FROM MP4
    for video in videos:
        vTk.createFrames(inputPath, video, projectPath, taggedDF)

    #ADD TELEMETRY TO PHOTOS
    if 'geotagged frames' not in os.listdir(projectPath):
        os.mkdir(projectPath + 'geotagged frames/')
    i = 0
    sys.stdout.flush()
    for frame in tqdm(taggedDF['Frame'],
                      desc='Geotagging ' + str(len(taggedDF['Frame'])) +
                      ' frames to path: geotagged frames/',
                      unit='frames'):
        photo = gpsphoto.GPSPhoto(projectPath + 'frames/' + frame)
        info = gpsphoto.GPSInfo(
            (taggedDF.loc[i, 'latitude'], taggedDF.loc[i, 'longitude']),
            alt=int(taggedDF.loc[i, 'elevation']),
            timeStamp=taggedDF.loc[i, 'timestamp'])
        photo.modGPSData(info, projectPath + 'geotagged frames/' + frame)
        i += 1
    print(r'Done (Processing time: ' + str((
        (datetime.now() - now).total_seconds()) / len(pointsDF['timestamp'])) +
          ' seconds per point')