# Download panorama images (0, 90, 180, 270 stitching) with duplicate detection and 404 error handling # Input: CSV file (e.g., selected_data.csv) containing panoid field # Output: Panorama images saved to save_dir import os from PIL import Image import requests import io import csv from tqdm import tqdm import dotenv import pandas as pd import re from time import sleep import random dotenv.load_dotenv("../.env") API_KEY = os.getenv('GOOGLE_MAP_API_KEY') base_url = 'https://maps.googleapis.com/maps/api/streetview' save_dir = '/home/xiuying.chen/jingpu/data/panoramas' csv_path = '/home/xiuying.chen/jingpu/data/exist_pano.csv' headings = { 'north': '0', 'east': '90', 'south': '180', 'west': '270', } def get_street_view_image(pano_id): params = { 'size': '640x640', 'pano': pano_id, 'key': API_KEY, 'pitch': '0', 'return_error_code': 'true' } images = [] error_panoids = [] # Download images facing east, south, west, and north for direction, heading in headings.items(): params['heading'] = heading sleep(random.randint(1, 5)) response = requests.get(base_url, params=params) print(f'{direction} request status:', response.status_code) if response.status_code == 200: images.append(Image.open(io.BytesIO(response.content))) image_filename = f'{pano_id}_{direction}.jpg' save_path = os.path.join(save_dir, image_filename) with open(save_path, 'wb') as f: f.write(response.content) print(f'Saved {image_filename}') elif response.status_code == 404: if pano_id not in error_panoids: error_panoids.append(pano_id) print(f'Failed to get the {direction} image, panoid: {pano_id} does not exist') # If there are panoids causing a 404, write them to 404panoid.csv if error_panoids: error_df = pd.DataFrame(error_panoids, columns=['panoid']) error_df.to_csv('404panoid.csv', mode='a', header=not os.path.exists('404panoid.csv'), index=False) # Stitch images together to form a panorama try: # Calculate the dimensions of the final panorama image width = sum(img.width for img in images) height = images[0].height # Create a new image and stitch the downloaded images together panorama = Image.new('RGB', (width, height)) x_offset = 0 for img in images: panorama.paste(img, (x_offset, 0)) x_offset += img.width # Save the panorama image output_path = os.path.join(save_dir, f'{pano_id}_panoramic.jpg') panorama.save(output_path, quality=95) # Update exist_pano.csv with the new panoid information new_row = {'panoid': pano_id, 'address': save_dir} existing_data = pd.read_csv(csv_path) if os.path.exists(csv_path) else pd.DataFrame(columns=['panoid', 'address']) existing_data = existing_data._append(new_row, ignore_index=True) existing_data.to_csv(csv_path, index=False) return output_path except Exception as e: print(f"Error downloading panorama: {str(e)}") return None def check_panoramas_exist(panoid): """Check if the given panoid has already been crawled""" csv_path = '/home/xiuying.chen/jingpu/data/exist_pano.csv' # Read existing panoid data if not os.path.exists(csv_path): return False # If the file does not exist, return False existing_data = pd.read_csv(csv_path) # Check if the panoid exists in the 'panoid' column return panoid in existing_data['panoid'].values def read_pano_ids(file_path): pano_ids = [] with open(file_path, 'r', encoding='utf-8') as f: reader = csv.DictReader(f) # Use DictReader to read the CSV file for row in reader: pano_id = row['panoID'] pano_ids.append((pano_id)) # Add the panoid to the list return pano_ids def load_exist_pano(scaned_dir): """Read .jpg files in the specified directory and update exist_pano.csv""" # Read existing panoid data csv_path = '/home/xiuying.chen/jingpu/data/exist_pano.csv' if os.path.exists(csv_path): existing_data = pd.read_csv(csv_path) else: print("exist_pano.csv not found, quit") return # Iterate over all .jpg files in the specified directory for filename in os.listdir(scaned_dir): if filename.endswith('.jpg'): # Use regex to extract the panoid by removing the directional suffix match = re.match(r'^(.*?)(?:_east|_north|_south|_west|_panoramic)\.jpg$', filename) if match: panoid = match.group(1) # Extract the panoid part # Check whether the panoid already exists if panoid not in existing_data['panoid'].values: # Create a new row and save the file address new_row = {'panoid': panoid, 'address': scaned_dir} existing_data = existing_data._append(new_row, ignore_index=True) # Write the updated data back to the CSV file existing_data.to_csv(csv_path, index=False) if __name__ == '__main__': pano_ids = read_pano_ids("GT.csv") for pano_id in tqdm(pano_ids, desc="Downloading street view images"): # Check whether the image has already been downloaded if check_panoramas_exist(pano_id): # print(f'{pano_id} already exists') continue else: # print(f'{pano_id} does not exist') sleep(5) get_street_view_image(pano_id) print(f'{pano_id} downloaded')