Guest User

Generate terrain data-set from google earth data

a guest
Oct 24th, 2017
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.97 KB | None | 0 0
  1. # based on this code: https://gist.github.com/BenElgar/0d5b3e7cc89cb2180c6e
  2. import requests
  3. import shutil
  4. import random
  5. import time
  6. import statistics
  7. import os
  8. from PIL import Image
  9. from PIL import ImageStat
  10. from PIL import ImageEnhance
  11. from os.path import isfile, join
  12. from selenium import webdriver
  13. from selenium.webdriver.common.keys import Keys
  14. from selenium.webdriver.common.by import By
  15. from selenium.webdriver.support.ui import WebDriverWait
  16. from selenium.webdriver.support import expected_conditions as EC
  17.  
  18. # define constants
  19. NUM_IMAGES = 7700
  20. IMAGE_REGION = (0, 0, 256, 256)
  21. NUM_COLORS = 8
  22. IMAGE_SIZE = 128, 128
  23. MAX_STANDARD_DEVIATION = 10000
  24. MIN_BLUE = 0.452
  25.  
  26. get_zoom = lambda: random.choice([8, 9, 10, 11])
  27. BASE_URL = 'http://maps.google.com/maps/api/staticmap?scale=1&center={}%2C{}&zoom={}&maptype=satellite&sensor=false&size=280x280'
  28. REQUEST_DELAY = 0
  29. SAVE_LOCATION = 'Images'
  30.  
  31. ROUTER_URL = 'http://10.0.0.138/gateway.lp'
  32. ROUTER_USERNAME = 'admin'
  33. ROUTER_PASSWORD = 'radmin2016'
  34.  
  35. driver = webdriver.Chrome()
  36.  
  37.  
  38. def mean_color(colors, type='histogram'):
  39.     # get the average color of the image
  40.     if type == 'histogram':
  41.         frequency = []
  42.         for c in colors:
  43.             frequency += [c[1]]*c[0]
  44.         colors = frequency
  45.        
  46.     elif type != 'samples':
  47.         raise KeyError
  48.        
  49.     mean_color = map(statistics.mean, zip(*colors))
  50.     return mean_color
  51.    
  52. def color_standard_deviation(colors):
  53.     # get the standard deviation of various colors in the image
  54.     frequency = []
  55.     for c in colors:
  56.         frequency += [c[1]]*c[0]
  57.        
  58.     mean = mean_color(frequency, type='samples')
  59.    
  60.     s = []
  61.     for color in frequency:
  62.         # standard deviation over 3 dimensions
  63.         s.append(sum(map(lambda x: (color[x]-mean[x])**2, [0, 1, 2])))
  64.    
  65.     stdev = sum(s)**0.5
  66.     return stdev
  67.    
  68. def color_percentage(color):
  69.     # get how much each channel makes up the color as a percentage
  70.     total = sum(color)
  71.     try:
  72.         c_percentage = map(lambda x: x/total, color)
  73.        
  74.     except ZeroDivisionError:
  75.         return 1.0/3, 1.0/3, 1.0/3
  76.    
  77.     return c_percentage
  78.  
  79. def random_location():
  80.     # pick a random latitude and longditude
  81.     lat = str(round(random.uniform(-90, 89), 7))
  82.     lon = str(round(random.uniform(-180, 179), 7))
  83.     return lat, lon
  84.    
  85. def format_image(img):
  86.     # how the image suitable for processing. Reduce color palette and size.
  87.     img = img.convert('P', palette=Image.ADAPTIVE, colors=NUM_COLORS)
  88.     img = img.crop(IMAGE_REGION)
  89.     return img.convert('RGB')
  90.    
  91. def eval_image(img):
  92.     # get whether or not the image is suitable for the dataset.
  93.     stdev = color_standard_deviation(img.getcolors())
  94.     if stdev > MAX_STANDARD_DEVIATION:
  95.         mean = mean_color(img.getcolors())
  96.         r, g, b = color_percentage(mean)
  97.        
  98.         if b < MIN_BLUE:
  99.             return True
  100.    
  101.     return False
  102.    
  103. def handle_api_limit():
  104.     print '[!] API limit hit'
  105.     WebDriverWait(driver, 40).until(EC.presence_of_element_located((By.ID, 'Disconnect')))
  106.    
  107.     driver.find_element_by_id('Disconnect').click()
  108.     WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, 'Connect')))
  109.    
  110.     driver.find_element_by_id('Connect').click()
  111.     WebDriverWait(driver, 40).until(EC.presence_of_element_located((By.ID, 'Disconnect')))
  112.    
  113. def post_format_images():
  114.     # normalize the brightness for all images in dataset
  115.     # list files, get average brightness
  116.     files = [f for f in listdir(SAVE_LOCATION) if isfile(join(SAVE_LOCATION, f))]
  117.     total = []
  118.     for f in files:
  119.         img = Image.open(os.join+f).convert('L')
  120.         stat = ImageStat.Stat(img)
  121.         total.append(stat.mean[0])
  122.        
  123.     avrg = statistics.mean(total)
  124.     print '[*] Normalizing images for average brightness: {}'.format(avrg)
  125.    
  126.     # normalize brightness for each image and save in 'Normalized_SAVE_LOCATION'
  127.     for f in files:
  128.         img = Image.open(join(SAVE_LOCATION, f))
  129.         gs_img = img.convert('L')
  130.         stat = ImageStat.Stat(gs_img)
  131.         intensity = avrg / stat.mean[0]
  132.         enhancer = ImageEnhance.Brightness(img)
  133.         img = enhancer.enhance(intensity)
  134.         img = img.resize(IMAGE_SIZE)
  135.        
  136.         img.save(os.join('Normalized_{}'.format(SAVE_LOCATION), f))
  137.        
  138. def initiate_driver(d):
  139.     d.get(ROUTER_URL)
  140.     username_box = d.find_element_by_id('srp_username')
  141.     username_box.clear()
  142.     username_box.send_keys(ROUTER_USERNAME)
  143.    
  144.     password_box = d.find_element_by_id('srp_password')
  145.     password_box.clear()
  146.     password_box.send_keys(ROUTER_PASSWORD)  
  147.  
  148.     d.find_element_by_id('sign-me-in').click()
  149.    
  150.     WebDriverWait(driver, 40).until(EC.element_to_be_clickable((By.XPATH, '//u[text()=\'Internet Access\']'))).click()
  151.     time.sleep(6)
  152.     return True
  153.  
  154.    
  155. def main():
  156.     initiate_driver(driver)
  157.     num_images = 0
  158.    
  159.     while num_images < NUM_IMAGES:
  160.         # get 20,000 images
  161.         time.sleep(REQUEST_DELAY)
  162.         lat, lon = random_location()
  163.         r = requests.get(BASE_URL.format(lat, lon, get_zoom()), stream=True)
  164.  
  165.         if r.status_code == 200:
  166.             r.raw.decode_content = True
  167.             try:
  168.                 img = Image.open(r.raw).convert('RGB')
  169.              
  170.             except IOError:
  171.                 continue
  172.                
  173.             img = format_image(img)
  174.             if not eval_image(img):
  175.                 # image is not suitable for dataset
  176.                 continue
  177.                
  178.             # file object
  179.             num_images += 1
  180.             img.save('{}/{}_{}.png'.format(SAVE_LOCATION, lat, lon))
  181.            
  182.         elif r.status_code == 403:
  183.             handle_api_limit()
  184.            
  185.         else:
  186.             print '[!] Recieved status code: {}'.format(r.status_code)
  187.        
  188.     normalize_brightness()
  189.  
  190. if __name__ == '__main__':
  191.     try:
  192.         main()
  193.     except KeyboardInterrupt:
  194.         exit()
Add Comment
Please, Sign In to add comment