Skip to content

Instantly share code, notes, and snippets.

@stormxuwz
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stormxuwz/1ac09c0de4132aed5bd3 to your computer and use it in GitHub Desktop.
Save stormxuwz/1ac09c0de4132aed5bd3 to your computer and use it in GitHub Desktop.
How to use Google Navigation and street view API and extract some features from a image
import urllib2;
import numpy as np;
import json;
from pyproj import Geod;
def decode_line(encoded):
"""copied from https://github.com/jconst/Byway-Server/blob/master/polyline.py
"""
encoded_len = len(encoded)
index = 0
array = []
lat = 0
lng = 0
while index < encoded_len:
b = 0
shift = 0
result = 0
while True:
b = ord(encoded[index]) - 63
index = index + 1
result |= (b & 0x1f) << shift
shift += 5
if b < 0x20:
break
dlat = ~(result >> 1) if result & 1 else result >> 1
lat += dlat
shift = 0
result = 0
while True:
b = ord(encoded[index]) - 63
index = index + 1
result |= (b & 0x1f) << shift
shift += 5
if b < 0x20:
break
dlng = ~(result >> 1) if result & 1 else result >> 1
lng += dlng
array.append((lat * 1e-5, lng * 1e-5))
return array
# if __name__ == "__main__":
# latlngs = decode_line("grkyHhpc@B[[_IYiLiEgj@a@q@yEoAGi@bEyH_@aHj@m@^qAB{@IkHi@cHcAkPSiMJqEj@s@CkFp@sDfB}Ex@iBj@S_AyIkCcUWgAaA_JUyAFk@{D_]~KiLwAeCsHqJmBlAmFuXe@{DcByIZIYiBxBwAc@eCcAl@y@aEdCcBVJpHsEyAeE")
# for latlng in latlngs:
# print str(latlng[0]) + "," + str(latlng[1])
def GSV_json(origin='kirby+state,Champaign,IL',destination='Illini+Union,Urbana,IL',gotype="driving"):
api_key='AI';
url_json='https://maps.googleapis.com/maps/api/directions/json?origin='+origin+'&destination='+destination+'&sensor=false&key='+api_key+'&mode='+gotype+'&alternatives=true';
print url_json;
req = urllib2.Request(url_json)
f = urllib2.urlopen(req);
content = f.read();
response = json.loads(content)
print len(response['routes'])
all_alternative=[]
for alternative in response['routes']:
steps=alternative['legs'][0]['steps']
allstepPoints=[];
allDistance=[];
for step in steps:
### parse the points from polyline
step_distance=step['distance'];
step_start=step['start_location'];
step_end=step['end_location'];
poly_encode=step['polyline']['points'];
print poly_encode;
coord_points=decode_line(poly_encode);
print step_start;
print step_end;
# print coord_points;
allstepPoints.append(coord_points);
allDistance.append(step_distance);
all_alternative.append(allstepPoints)
# return allstepPoints;
return all_alternative
def GSVimages(all_alternative,gotype="driving",direction=0):
g = Geod(ellps='clrk66')
nImage=1
all_coords=[]
for alt_index, allstepPoints in enumerate(all_alternative):
coords=[]
nImage=1
for nleg,leg in enumerate(allstepPoints):
num_points=len(leg);
escape=0;
print num_points;
print "$$$$$$$$$$$$"
for i in range(num_points-1):
if escape==1:
continue;
escape=0;
currentLat=leg[i][0];
currentLong=leg[i][1];
coords.append([currentLat,currentLong])
nextLat=leg[i+1][0];
nextLong=leg[i+1][1];
az12,az21,dist = g.inv(currentLong,currentLat,nextLong,nextLat); # Calculate the Azimuth between two points to find the road direction
az12=az12+direction;
if az12<0:
az12=360+az12;
if dist<20: #if distance <20m
escape=0;
# print currentLat,currentLong,dist,az12;
url="http://maps.googleapis.com/maps/api/streetview?size=640x640&location="+str(currentLat)+","+str(currentLong)+"&sensor=True&key=AIzaSyt1FQgDQYNnPM&heading="+str(az12);
req = urllib2.Request(url)
f = urllib2.urlopen(req);
content = f.read();
# im=Image.open(StringIO(content))
output = open("./test/"+gotype+"_"+str(alt_index)+"_"+str(nImage).zfill(3)+"_view.jpg",'wb')
output.write(content)
output.close()
nImage+=1
all_coords.append(coords)
return all_coords
def saveCoords(all_coords,filename):
with open(filename,"w") as outputfile:
for coords in all_coords:
for i in coords:
line=str(i[0])+","+str(i[1])+"\n";
outputfile.write(line)
if __name__=="__main__":
origin='76+E+University+Ave,Champaign,IL+61820'
desti='801+W+Main+St,Urbana,IL+61801'
alternative_routes=GSV_json(origin,desti,"driving");
coords_driving=GSVimages(alternative_routes,"driving")
# print coords_driving
saveCoords(coords_driving,"driving_coords.txt")
# allstepPoints=GSV_json(origin,desti,"walking");
coords_walking=GSVimages(alternative_routes,"walking",90)
saveCoords(coords_walking,"walking_coords.txt")
function [ FeatureCols ] = ExtractFeature( path,filename )
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
param.imageSize = [256 256]; % it works also with non-square images (use the most common aspect ratio in your set)
param.orientationsPerScale = [8 8 8 8]; % number of orientations per scale
param.numberBlocks = 4;
param.fc_prefilt = 4;
img=imread([path filename]);
label=-1;
type=0;
[gist,param]=LMgist(img,'',param); % 1* 512
im_hsv = rgb2hsv(img);
im_hue = im_hsv(:,:,1);
im_sat=im_hsv(:,:,2);
im_val=im_hsv(:,:,3);
r=img(:,:,1);
g=img(:,:,2);
b=img(:,:,3);
justGreen=g-r/2-b/2;
bw=justGreen>10;
greenness=sum(bw(:));
subplot(1,2,1), subimage(img);
subplot(1,2,2), subimage(bw);
print ('-djpeg',[path 'green/' filename]);
% imshow(bw)
% imwrite(h,[path,'green' filename]);
%- Hue Histogram
hue_hist = imhist(im_hue); %1 * 256
sat_hist=imhist(im_sat); %1 * 256
val_hist=imhist(im_val); %1 * 256
%- Edge orientation Histogram
edgeOH=edgeOrientationHistogram(rgb2gray(img)); % 16*5=80
% Add features and add it to variable feature. Do remember to adjust the m values at the begining.
%%%%
FeatureCols = [type,label,greenness,gist,transpose(sat_hist),transpose(hue_hist),transpose(val_hist),reshape(edgeOH,1,[])];
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment