import os import json import re import cv2 import numpy as np import requests from datetime import datetime import rasterio from rasterio.transform import from_origin file_dir = os.path.dirname(r"C:\Users\HP\Desktop\Hardik Balas") prefs_path = os.path.join(file_dir, 'preferences.json') default_prefs = { 'url': 'https://mt.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', 'tile_size': 256, 'tile_format': 'jpg', 'dir': os.path.join(file_dir, 'images'), 'headers': { 'cache-control': 'max-age=0', 'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'none', 'sec-fetch-user': '?1', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36' }, 'tl': '', 'br': '', 'zoom': '' } def take_input(messages): inputs = [] print('Enter "r" to reset or "q" to exit.') for message in messages: inp = input(message) if inp == 'q' or inp == 'Q': return None if inp == 'r' or inp == 'R': return take_input(messages) inputs.append(inp) return inputs def calculate_tile_coordinates(lat, lon, zoom): n = 2.0 ** zoom x_tile = int((lon + 180.0) / 360.0 * n) y_tile = int((1.0 - np.log(np.tan(np.radians(lat)) + 1.0 / np.cos(np.radians(lat))) / np.pi) / 2.0 * n) return x_tile, y_tile, zoom def download_image(lat1, lon1, lat2, lon2, zoom, url, headers, tile_size, channels): try: # Calculate x, y, and z based on latitudes, longitudes, and zoom x, y, z = calculate_tile_coordinates(lat1, lon1, zoom) # Replace this with actual image downloading logic response = requests.get(url.format(x=x, y=y, z=z), headers=headers) response.raise_for_status() # Check for HTTP errors image_data = response.content # Process the image data as needed # For simplicity, return a placeholder image return cv2.imdecode(np.frombuffer(image_data, np.uint8), cv2.IMREAD_COLOR) except Exception as e: print(f"Error downloading image: {e}") return None # Return None to indicate an error def save_image_as_tiff(image, tiff_path, lat1, lon1, lat2, lon2, zoom): x, y, _ = calculate_tile_coordinates(lat1, lon1, zoom) resolution = (lon2 - lon1) / image.shape[1], (lat2 - lat1) / image.shape[0] # Calculate the transform with upper-left coordinate and resolution transform = from_origin(lon1, lat2, resolution[0], resolution[1]) # You may need to adjust the compression options based on your requirements with rasterio.open(tiff_path, 'w', driver='GTiff', height=image.shape[0], width=image.shape[1], count=image.shape[2], dtype=str(image.dtype), crs='EPSG:4326', transform=transform, compress='JPEG', tiled=True) as dst: dst.write(image.transpose(2, 0, 1)) def run(): with open(os.path.join(file_dir, 'preferences.json'), 'r', encoding='utf-8') as f: prefs = json.loads(f.read()) if not os.path.isdir(prefs['dir']): os.mkdir(prefs['dir']) if (prefs['tl'] == '') or (prefs['br'] == '') or (prefs['zoom'] == ''): messages = ['Top-left corner (lat lon): ', 'Bottom-right corner (lat lon): ', 'Zoom level: '] inputs = take_input(messages) if inputs is None: return else: prefs['tl'], prefs['br'], prefs['zoom'] = inputs lat1, lon1 = map(float, re.findall(r'[+-]?\d*\.\d+|d+', prefs['tl'])) lat2, lon2 = map(float, re.findall(r'[+-]?\d*\.\d+|d+', prefs['br'])) zoom = int(prefs['zoom']) print(lat1, lon1, lat2, lon2, zoom) if prefs['tile_format'].lower() == 'png': channels = 4 else: channels = 3 img = download_image(lat1, lon1, lat2, lon2, zoom, prefs['url'], prefs['headers'], prefs['tile_size'], channels) if img is not None: timestamp = datetime.now().strftime("%Y%m%d%H%M%S") png_name = f'img_{timestamp}.png' tiff_name = f'img_{timestamp}.tiff' # Save PNG cv2.imwrite(os.path.join(prefs['dir'], png_name), img) print(f'Saved as {png_name}') # Convert PNG to TIFF tiff_path = os.path.join(prefs['dir'], tiff_name) save_image_as_tiff(img, tiff_path, lat1, lon1, lat2, lon2, zoom) print(f'Converted and saved as {tiff_name}') else: print('Image download failed.') if os.path.isfile(prefs_path): run() else: with open(prefs_path, 'w', encoding='utf-8') as f: json.dump(default_prefs, f, indent=2, ensure_ascii=False) print(f'Preferences file created in {prefs_path}') # Example: # Top-left corner (lat lon): 21.2285 72.8392 # Bottom-right corner (lat lon): 21.1332 72.9864 # Zoom level: 10