Example #1
0
def gps_taginfo(image_path):
    exif = gpsphoto.getGPSData(image_path)
    file_name = (os.path.basename(image_path))
    if exif:
        lat = (exif['Latitude'])
        lng = (exif['Longitude'])
        date = (exif['Date'])
        d = date.split('/')
        year = d[2]
        #print('the latitude is {0}, the longitude is {1} and the year is year {2}' .format(lat,lng,year))
        url = f'https://api.bigdatacloud.net/data/reverse-geocode?latitude={lat}&longitude={lng}8&localityLanguage=en&key=2028335aee824d0ba128d6bcf363abdc'
        response = requests.get(url,timeout=5)
        try:
            country = response.json()["countryName"]
        except KeyError:
            country = "NoData"
        try:
            state = response.json()["principalSubdivision"]
        except KeyError:
            state = "NoData"
        try:
            city = response.json()["locality"]
        except:
            city = "NoData"
        response.close()
        return(file_name,city,state,country,year)
    else:
        print("ERROR:Exif data not present in pic")
        unknown = 'NoExif  Data'
        directory_path = directory_path_maker(image_path,unknown)
        directory_checker(directory_path,image_path)
        return(None,None,None,None,None)
Example #2
0
def main():

    # -- plot layouts --
    root = Path("./data/plot_layer/")
    fn = Path("Simpson_plots_2019.shp")
    path = root / fn
    data = gpd.read_file(path)
    data.plot()
    plt.savefig("./layout.png", transparent=True, dpi=300, bbox_inches='tight')
    plt.close("all")

    # -- compute Vegetative Indices --
    img_path = "./data/NEPAC_L4_170801_200ft/DJI_1930.JPG"
    gps_coord = gpsphoto.getGPSData(img_path)
    raw_img = np.array(Image.open(img_path))

    vari_img = compute_vgi(raw_img, "vari")
    vari_img = normalize_img(vari_img)
    fig, ax = plt.subplots(figsize=(10, 10))
    ax.imshow(vari_img, interpolation='none')
    plt.savefig("./vgi_vari.png",
                transparent=True,
                bbox_inches='tight',
                dpi=300)
    plt.close("all")

    tgi_img = compute_vgi(raw_img, "tgi")
    fig, ax = plt.subplots(figsize=(10, 10))
    ax.imshow(tgi_img, interpolation='none')
    plt.savefig("./vgi_tgi.png",
                transparent=True,
                bbox_inches='tight',
                dpi=300)
    plt.close("all")
Example #3
0
def main():

    # -- plot layouts --
    root = Path("./data/plot_layer/")
    plot_layout = load_plot_layout(root)
    plot_layout = plot_layout.to_crs('EPSG:32616')

    # -- sampling area layer --
    root = Path("./data/sampling_areas/")
    sampling_areas = load_sampling_areas(root)
    sampling_areas = sampling_areas.to_crs('EPSG:32616')

    # -- load example image --
    img_path = "./data/NEPAC_L4_170801_200ft/DJI_1930.JPG"
    gps_coord = gpsphoto.getGPSData(img_path)
    gps_coord = gps_to_crs(gps_coord, 'EPSG:32616')
    raw_img = np.array(Image.open(img_path))
    print("Image at {}".format(gps_coord))

    # -- plot sampling area and plot layout --
    fig, ax = plt.subplots(figsize=(8, 8))
    plot_layout.plot(ax=ax, alpha=0.5)
    sampling_areas.plot(column='Sarea_ID', ax=ax)
    plt.savefig("./output/sample_and_plot_layer_proj.png",
                transparent=True,
                bbox_inches='tight')
    plt.close("all")
Example #4
0
def make_pic_data_csv(paths_arr):
    file_name = 'pic_coords_time.csv'  # TODO: not hardcode this

    print("creating: %s" % file_name)
    outfile = open(file_name, 'w+')
    outfile.write('path, coordinates, date\n')
    for path in paths_arr:
        for root, dirs, files in os.walk(path):
            for name in files:
                full_path = os.path.join(root, name)
                try:
                    data = gpsphoto.getGPSData(full_path)
                    if data != {}:
                        csv_str = "%s, %s %s, %s,\n" % (
                            full_path, data.get('Latitude'),
                            data.get('Longitude'),
                            to_timestamp(data['Date'], data['UTC-Time']))

                        print(csv_str.rstrip())
                        outfile.write(csv_str)

                except (ValueError, KeyError) as e:
                    print("---ERROR---")
                    print(full_path)
                    print(e)

    outfile.close()
    print("created: %s" % file_name)
    return file_name
Example #5
0
def wrt_geo_viz():
    '''given a directory of jpeg images, a geojson file is written with long,lat and alt for each image'''

    path = '/media/antor/Transcend/drone/data/dhanmondi/100MEDIA/'
    json_out_path = './new_home/geojson_viz.json'

    file_lst = [f for f in listdir(path) if isfile(join(path, f))]
    empt = {"type": "FeatureCollection", "features": []}

    print('writing long, lat to geojson file ......')
    for i in range(len(file_lst)):
        file_path = join(path, file_lst[i])
        data = gpsphoto.getGPSData(file_path)
        empt["features"].append({
            "id": str(file_lst[i]),
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [data['Longitude'], data['Latitude']]
            },
            "properties": {
                "image_id": str(file_lst[i]),
                "longitude": data['Longitude'],
                "latitude": data['Latitude'],
                "altitude": data['Altitude']
            }
        })

        if i % 501 == 500 or i == len(file_lst):
            print(str(i) + ' images processed....')

    with open(json_out_path, 'w') as f:
        json.dump(empt, f)
Example #6
0
def get_gps(file_name):
    from GPSPhoto import gpsphoto
    gps_data = gpsphoto.getGPSData(file_name)
    try:
        return gps_data['Latitude'], gps_data['Longitude']
    except:
        return []  #exif 파일이 아닐 경우 빈 값 리턴
Example #7
0
    def extract_information_from_images(
        self
    ) -> dict:  # Time Complexity : O(n) where n is the number of images in all the folders
        image_source_path = self.__source
        crops_geo_data = {}

        crop_folders_list = [
            name for name in os.listdir(image_source_path)
            if name != ".DS_Store"
        ]

        for folder_name in tqdm(crop_folders_list):
            folder_location = "{}\{}".format(image_source_path, folder_name)
            file_names_list = [
                name for name in os.listdir(folder_location)
                if name != ".DS_Store"
            ]

            for file_name in file_names_list:
                if folder_name not in crops_geo_data:
                    crops_geo_data[folder_name] = []

                file_location = "{}\{}".format(folder_location, file_name)

                # Get the data from image file and return a dictionary
                data = gpsphoto.getGPSData(file_location)
                if data:  #Some Images dont have exif data
                    crops_geo_data[folder_name].append(
                        (data['Latitude'], data['Longitude']))
        return crops_geo_data
Example #8
0
def get_coordinates(filepath):
    try:
        data = gpsphoto.getGPSData(filepath)

        long = str(data['Longitude'])
        lat = str(data['Latitude'])
        coords = lat + "," + long
        params = {'latlng': coords, 'key': API_KEY, 'language': 'ru'}
        maps_params = coords
        url_maps = 'https://www.google.com/maps/search/?api=1&query='
        url_maps_full = url_maps + maps_params

        url_params = urllib.parse.urlencode(params)
        google_GeoCode_Url = 'https://maps.googleapis.com/maps/api/geocode/json?'
        url = google_GeoCode_Url + url_params
        response = requests.get(url)
        data = response.json()
        if data['status'] == 'OK':
            result = data['results'][0]
            location = result['formatted_address']
            print(location)
            print(url_maps_full)
        else:
            print("Произошла ошибка", data['status'])
    except:
        print("Файл не содержит координат.")
def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))

    # Get the object from the event and show its content type
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = event['Records'][0]['s3']['object']['key']
    try:
        print("trying to get " + key + " from bucket " + bucket)
        response = s3.get_object(Bucket=bucket, Key=key)
        download_path = '/tmp/foo.jpg'
        s3.download_file(bucket, key, download_path)
        
        print(response)
        print(download_path)
        
        data = gpsphoto.getGPSData(download_path)
        print(data['Latitude'], data['Longitude'])
        latLon = "(" + str(data['Latitude']) + ", " + str(data['Longitude']) + ")"
        now = datetime.now()
        current_time = now.isoformat()
        dynamodb.put_item(TableName='Dogs', Item={'location_found':{'S':latLon},'datetime_found':{'S':current_time}})
        print("CONTENT TYPE: " + response['ContentType'])
        return response['ContentType']
    except Exception as e:
        print(e)
        print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        raise e
Example #10
0
def gps(fileName):
    data = gpsphoto.getGPSData(getOutdoorImage(fileName))
    gpsData = str(data['Latitude']) + "," + str(data['Longitude'])
    writeTemp(gpsData)
    if "Latitude" in data:
        return gpsData
    else:
        return "No GPS Data"
Example #11
0
def get_geo_info(file_path):
    # Get the data from image file and return a dictionary
    data = gpsphoto.getGPSData(file_path)
    rawData = gpsphoto.getRawData(file_path)
    if 'Latitue' in data:
        return (data['Latitude'], data['Longitude'])
    else:
        return None
Example #12
0
def search(file):
    if Image:
        try:
            img = Image.open(file)
            data = gpsphoto.getGPSData(file)
            print('in file', file, 'GPS tag was founded: ', data['Latitude'], data['Longitude']) 
        except:
            pass 
Example #13
0
def get_meta_gps(img_path):
    try:
        gps_data = gpsphoto.getGPSData(img_path)
    except:
        return None, None
    # If GPS coordinates are in metadata, use those
    if gps_data is not None and 'Latitude' in gps_data and 'Longitude' in gps_data:
        return gps_data['Latitude'], gps_data['Longitude']
    return None, None
Example #14
0
def main():
    orig_pic = '/Users/Leon/Documents/project/modPhotoGPS/data/IMG_0752.jpeg'
    print(os.path.exists(orig_pic))
    data = gpsphoto.getGPSData(orig_pic)
    rawdata = gpsphoto.getRawData(orig_pic)
    for tag in data.keys():
        print("%s: %s" % (tag, data[tag]))
    print("%s : %s" % (data['Latitude'], data['Longitude']))
    print("Hellps")
def get_data(picture):

    a = gpsphoto.getGPSData(picture)

    try:
        return f"{a['Latitude']},{a['Longitude']}"

    except Exception as e:
        return ("ERROR")
def loadPictureOnDict(picture, picturesDict, latLongDict, path):
    #print('Will read GPS data from picture '+picture)
    try:
        innerPath = path / picture
        data = gpsphoto.getGPSData(innerPath.as_posix())
        picturesDict[picture] = (data['Latitude'], data['Longitude'])
        latLongDict[str((data['Latitude'], data['Longitude']))] = picture
    except:
        print('Failed to read the GPS data from the picture ' + picture)
Example #17
0
def get_image_location(url):
    urllib.request.urlretrieve(url, "tempimg.jpg")
    data = gp.getGPSData("tempimg.jpg")
    lat = data.get("Latitude")
    longe = data.get("Longitude")
    os.remove("tempimg.jpg")
    if (lat != None and longe != None):
        return {"latitude": lat, "longitude": longe}
    return None
def main():
    """Calibrate images here"""
    args = get_args()
    img_list = glob.glob(f'{args.dir}/*.tif', recursive=True)
    out_path = args.outdir

    if not os.path.isdir(out_path):
        os.makedirs(out_path)

    for img in img_list:

        meta_path = img.replace('.tif', '_meta.csv')
        filename = os.path.basename(img)
        outfile = os.path.join(os.getcwd(), out_path, filename)
        print(outfile)

        meta_df = pd.read_csv(meta_path, delimiter=';')
        print(meta_df['TempFPA'][0])

        g_img = gdal.Open(img)
        exif_dict = piexif.load(img)
        zeroth = str(exif_dict['0th'])
        exif = str(exif_dict['Exif'])
        GPS = str(exif_dict['GPS'])

        gps_data = gpsphoto.getGPSData(img)
        rawData = gpsphoto.getRawData(img)

        raw_data = g_img.GetRasterBand(1).ReadAsArray().astype('float')
        tc = raw2temp(raw_data, meta_df)

        create_geotiff(tc, (0, 0, 0, 0), outfile, None, True, None,
            extra_metadata=[
                f'0th={str(zeroth.strip("{}"))}\n\
                Exif={str(exif.strip("{}"))}\n\
                GPS={str(GPS.strip("{}"))}\n'
            ], compress=False)

        cmd = f'exiftool -overwrite_original -TagsFromFile {img} {outfile}'
        subprocess.call(cmd, shell=True)

        exif_dict = piexif.load(outfile)
        gps_data = gpsphoto.getGPSData(outfile)
        print(f'{gps_data}\n')
Example #19
0
def coords(path):
    try:
        gps_data = gpsphoto.getGPSData(path)
        if "Latitude" in gps_data and "Longitude" in gps_data:
            return gps_data.get("Latitude", 0.0), gps_data.get("Longitude", 0.0)
        else:
            return None
    except:
        print("Error getting GPS data from file {}".format(path))
        return None
def upload_images(bulk_dir):
    image_records = []
    for root, subdirs, files in os.walk(bulk_dir):
        for file in files:
            ext = os.path.splitext(file)[1].lower()
            if ext in supported_formats:
                imgPath = os.path.join(root, file)
                tags = exifread.process_file(open(imgPath, 'rb'))
                gpsData = gpsphoto.getGPSData(imgPath)

                Latitude = none_check_float(gpsData.get('Latitude'))
                Longitude = none_check_float(gpsData.get('Longitude'))
                Altitude = none_check_float(gpsData.get('Altitude'))
                DateTime = none_check_str(tags.get('Image DateTime'))
                ExposureTime = none_check_str(tags.get('EXIF ExposureTime'))
                FNumber = none_check_str(tags.get('EXIF FNumber'))
                MeteringMode = none_check_str(tags.get('EXIF MeteringMode'))
                FocalLength = none_check_str(tags.get('EXIF FocalLength'))
                ExifVersion = none_check_str(tags.get('EXIF ExifVersion'))
                Software = none_check_str(tags.get('Image Software'))
                Make = none_check_str(tags.get('Image Make'))
                Model = none_check_str(tags.get('Image Model'))
                BodySerialNumber = none_check_str(
                    tags.get('EXIF BodySerialNumber'))
                LightSource = none_check_str(tags.get('EXIF LightSource'))
                WhiteBalance = none_check_str(tags.get('EXIF WhiteBalance'))
                GainControl = none_check_str(tags.get('EXIF GainControl'))
                Contrast = none_check_str(tags.get('EXIF Contrast'))
                Saturation = none_check_str(tags.get('EXIF Saturation'))
                Sharpness = none_check_str(tags.get('EXIF Sharpness'))
                Compression = none_check_str(tags.get('Image Compression'))

                ImageWidth = none_check_int(
                    tags.get('Image ImageWidth')) or none_check_int(
                        tags.get('EXIF ExifImageWidth'))
                ImageLength = none_check_int(
                    tags.get('Image ImageLength')) or none_check_int(
                        tags.get('EXIF ExifImageLength'))
                ISOSpeed = none_check_int(
                    tags.get('EXIF ISOSpeed')) or none_check_int(
                        tags.get('EXIF ISOSpeedRatings'))
                ExposureProgram = none_check_str(
                    tags.get('EXIF ExposureProgram')) or none_check_str(
                        tags.get('EXIF ExposureMode'))

                image_records.insert(
                    0,
                    (None, None, str(imgPath), str(ext), DateTime, Latitude,
                     Longitude, Altitude, ImageWidth, ImageLength,
                     ExposureTime, FNumber, ISOSpeed, MeteringMode,
                     LightSource, FocalLength, ExposureProgram, WhiteBalance,
                     GainControl, Contrast, Saturation, Sharpness, Compression,
                     ExifVersion, Software, Make, Model, BodySerialNumber))

    image_dao.insert_images(image_records)
Example #21
0
def getCoordinates(image_name):
    data = gpsphoto.getGPSData(image_name)

    latitude = data['Latitude']
    longitude = data['Longitude']

    list = []
    list.append(latitude)
    list.append(longitude)

    return list
Example #22
0
def getTag(path):
    metaData = gpsphoto.getGPSData(path)
    geoLocalization = [0,0]

    for tag in metaData.keys():
        #print ("%s: %s" % (tag, metaData[tag]))
        if tag == "Latitude":
            geoLocalization[0] = metaData[tag]
        if tag == "Longitude":
            geoLocalization[1] = metaData[tag]

    return geoLocalization
    def get_data_from_exif(self):
        """
        Get image information from its EXIF metadata.

        :return: images information
        :rtype: tuple
        """
        dic = gpsphoto.getGPSData(self.path)
        self.lat = "{0:.6f}".format(dic["Latitude"])
        self.lon = "{0:.6f}".format(dic["Longitude"])
        self.datetime = exif_to_sql(dic['Date'], dic['UTC-Time'])
        return self.lat, self.lon, self.datetime
Example #24
0
def get_gps_search_tokens(image_filename: str,
                          resolver: LatLongResolver) -> List[str]:
    try:
        data = gpsphoto.getGPSData(image_filename)
        if 'Latitude' in data and 'Longitude' in data:
            tokens = resolver.nearest(data['Latitude'], data['Longitude'])
            return tokens
        else:
            return []
    except Exception as ex:
        logging.error('Unable to parse GPS coordinates for {} {}'.format(
            image_filename, ex))
        return []
Example #25
0
 def get_position_by_api(self):
     try:
         gps_info = gpsphoto.getGPSData(self.path)
         location = f"{gps_info.get('Longitude')},{gps_info.get('Latitude')}"
         resp = requests.get(
             self.url_get_position.format(location, self.api_key)).json()
         address = resp.get('regeocode').get('formatted_address')
         city = resp.get('regeocode').get('addressComponent').get('city')
         self.city = city
         self.address = address
         return address, city
     except Exception as err:
         return None, None
def get_date_and_location(path_to_image):

    name_date_location_list = []

    for i in os.listdir(path_to_image):

        time_stamp = (Image.open(path_to_image + i)._getexif()[36867])

        data = gpsphoto.getGPSData(path_to_image + i)

        name_date_location_list.append(
            [i, time_stamp, data['Latitude'], data['Longitude']])

    return name_date_location_list
Example #27
0
 def __init__(self, path):
     self.path = path
     data = gpsphoto.getGPSData(path)
     if "Latitude" in data.keys() and "Longitude" in data.keys():
         lat, lon = (data["Latitude"], data["Longitude"])
         if "Altitude" in data.keys():
             self.height = data['Altitude']
         z, l, x, y = utm.project((lon, lat))
         self.lat = lat
         self.lon = lon
         self.zone = z
         self.zone_letter = l
         self.x = x
         self.y = y
         self.has_georeference = True
Example #28
0
def get_map_screenshot():
    """
    Returns screenshot of whole google map page
    """
    image = "./test.jpg"
    data = gpsphoto.getGPSData(image)
    Lat, Long = data["Latitude"], data["Longitude"]
    url = "https://www.google.co.in/maps?q=" + str(Lat) + ",+" + str(Long)
    driver = webdriver.Firefox()
    # driver.set_window_position(-2000,0)
    driver.get(url)
    driver.save_screenshot("map.png")
    img = cv2.imread("map.png",1)
    img = img[:,int(0.35*img.shape[1]):,:]
    cv2.imwrite("map.png",img)
Example #29
0
def closest_plant(photo_path):
    data = gpsphoto.getGPSData(photo_path)
    try:
        photo_gps = (float(data['Latitude']), float(data['Longitude']))
        closest = None
        for i in plants:
            plant_gps = (float(i[10]), float(i[11]))
            if closest is None:
                closest = [haversine(plant_gps, photo_gps)] + i
            if closest[0] > haversine(plant_gps, photo_gps):
                closest = [haversine(plant_gps, photo_gps)] + i
        return closest
        # Catch KeyError so we can ignore photos without any GPS.
    except KeyError:
        return None
 def img_worker(self, fpath, fid):
     self.logger.info("PID:" + str(os.getpid()) + " fid = " + str(fid) +
                      " img_worker target = " + str(fpath))
     try:
         gpx = gpsphoto.getGPSData(fpath)
         with open(fpath, "rb") as inputfile:
             dpath = os.path.join(
                 Path(fpath).parent, "image",
                 os.path.splitext(os.path.basename(fpath))[0] + "_d.jpg")
             img_data = inputfile.read()
             img_np_arr = np.array(
                 Image.open(io.BytesIO(img_data)).convert("RGB"))
             img = {
                 'fid': fid,
                 'img_data': img_np_arr,
                 'img_path': fpath,
                 'dimg_path': dpath,
                 'speed': 0,
                 'VIDEOTIME': 0,
                 'isframe': 0
             }
             if (gpx != {}):
                 self.logger.debug("img_worker fid:" + str(fid) +
                                   " Find GPS data...")
                 img['lat'] = gpx['Latitude']
                 img['lon'] = gpx['Longitude']
                 img['kmp'] = kmplush(self.kmpoints, {
                     'lat': gpx['Latitude'],
                     'lon': gpx['Longitude']
                 })
                 img['UTCTIME'] = datetime.datetime.strptime(
                     gpx['Date'] + " " + gpx['UTC-Time'],
                     '%m/%d/%Y %H:%M:%S')
             else:
                 self.logger.error("GPS data Miss " + fpath)
                 img['lat'] = 23.470119
                 img['lon'] = 120.957689
                 img['kmp'] = {'name': "K0+0", 'meter': 0}
                 img['UTCTIME'] = datetime.datetime.now().strftime(
                     "%Y-%m-%d %H:%M:%S")
             self.imgs.put(img)
             # self.logger.debug(img)
             endflag = {'fid': fid, 'endflag': True}
             self.imgs.put(endflag)
             self.logger.debug(str(fid) + " endflag sended")
     except Exception as err:
         raise err
     os.kill(os.getpid(), signal.SIGTERM)