Advertisement
cubbypastes

Colab image download attempt

Jan 8th, 2025
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.29 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """Cartesmich attempt.ipynb
  3.  
  4. Automatically generated by Colab.
  5.  
  6. Original file is located at
  7. [irrelevant]
  8. """
  9.  
  10. pip install requests pillow
  11.  
  12. import os
  13. import requests
  14. from PIL import Image
  15.  
  16. # Base URL for tiles
  17. BASE_URL = "http://cartesmich.free.fr/images/France_LD/TileGroup{}/{}-{}-{}.jpg"
  18.  
  19. # Directory to save downloaded tiles
  20. SAVE_DIR = "tiles"
  21. os.makedirs(SAVE_DIR, exist_ok=True)
  22.  
  23. # Specify the range of tiles to download
  24. TILEGROUPS = range(0, 5)  # Adjust as needed
  25. ROWS = range(0, 10)       # Adjust based on tile layout
  26. COLS = range(0, 10)       # Adjust based on tile layout
  27.  
  28. def download_tile(tilegroup, row, col):
  29.     """Download a single tile and save it locally."""
  30.     url = BASE_URL.format(tilegroup, row, col, 0)
  31.     filename = os.path.join(SAVE_DIR, f"TileGroup{tilegroup}_{row}_{col}.jpg")
  32.  
  33.     try:
  34.         response = requests.get(url, stream=True)
  35.         if response.status_code == 200:
  36.             with open(filename, "wb") as file:
  37.                 file.write(response.content)
  38.             print(f"Downloaded: {filename}")
  39.         else:
  40.             print(f"Tile not found: {url}")
  41.     except Exception as e:
  42.         print(f"Error downloading {url}: {e}")
  43.  
  44. def stitch_tiles():
  45.     """Stitch downloaded tiles into a single image."""
  46.     tile_width, tile_height = Image.open(os.path.join(SAVE_DIR, os.listdir(SAVE_DIR)[0])).size
  47.     canvas_width = tile_width * len(COLS)
  48.     canvas_height = tile_height * len(ROWS)
  49.  
  50.     canvas = Image.new("RGB", (canvas_width, canvas_height))
  51.  
  52.     for tilegroup in TILEGROUPS:
  53.         for row in ROWS:
  54.             for col in COLS:
  55.                 filename = os.path.join(SAVE_DIR, f"TileGroup{tilegroup}_{row}_{col}.jpg")
  56.                 if os.path.exists(filename):
  57.                     tile = Image.open(filename)
  58.                     canvas.paste(tile, (col * tile_width, row * tile_height))
  59.  
  60.     canvas.save("stitched_map.jpg")
  61.     print("Map stitched and saved as stitched_map.jpg")
  62.  
  63. # Download tiles
  64. for tilegroup in TILEGROUPS:
  65.     for row in ROWS:
  66.         for col in COLS:
  67.             download_tile(tilegroup, row, col)
  68.  
  69. # Stitch tiles into one image
  70. stitch_tiles()
  71.  
  72. import os
  73. import requests
  74.  
  75. # Base URL for the tiles (update this to match your target URL)
  76. BASE_URL = "http://cartesmich.free.fr/images/France_LD/TileGroup{}/{}-{}-{}.jpg"
  77.  
  78. # Directory to save downloaded tiles
  79. SAVE_DIR = "tiles"
  80. if not os.path.exists(SAVE_DIR):
  81.     os.makedirs(SAVE_DIR)
  82.  
  83. def download_tiles_dynamically(tilegroup=0, max_empty_tiles=100):
  84.     """
  85.    Download tiles dynamically by checking for their existence.
  86.    Args:
  87.        tilegroup: The TileGroup number to start from.
  88.        max_empty_tiles: Stop after this many consecutive missing tiles.
  89.    """
  90.     empty_tile_count = 0
  91.  
  92.     for row in range(0, 100):  # Arbitrary high limit
  93.         for col in range(0, 100):  # Arbitrary high limit
  94.             url = BASE_URL.format(tilegroup, row, col, 0)
  95.             filename = os.path.join(SAVE_DIR, f"TileGroup{tilegroup}_{row}_{col}.jpg")
  96.  
  97.             try:
  98.                 response = requests.get(url, stream=True)
  99.                 if response.status_code == 200:
  100.                     with open(filename, "wb") as file:
  101.                         file.write(response.content)
  102.                     print(f"Downloaded: {filename}")
  103.                     empty_tile_count = 0  # Reset empty tile counter
  104.                 else:
  105.                     print(f"Tile not found: {url}")
  106.                     empty_tile_count += 1
  107.  
  108.                 if empty_tile_count >= max_empty_tiles:
  109.                     print("No more tiles found. Stopping.")
  110.                     return
  111.             except Exception as e:
  112.                 print(f"Error downloading {url}: {e}")
  113.  
  114. def find_tilegroups(max_groups=10):
  115.     """
  116.    Find available TileGroups dynamically.
  117.    Args:
  118.        max_groups: Maximum number of groups to check.
  119.    Returns:
  120.        List of available TileGroup indices.
  121.    """
  122.     available_groups = []
  123.     for tilegroup in range(max_groups):
  124.         url = BASE_URL.format(tilegroup, 0, 0, 0)
  125.         try:
  126.             response = requests.get(url, stream=True)
  127.             if response.status_code == 200:
  128.                 available_groups.append(tilegroup)
  129.         except Exception as e:
  130.             print(f"Error checking TileGroup{tilegroup}: {e}")
  131.     print(f"Available TileGroups: {available_groups}")
  132.     return available_groups
  133.  
  134. tilegroups = find_tilegroups()
  135. for tilegroup in tilegroups:
  136.     print(f"Starting download for TileGroup {tilegroup}")
  137.     download_tiles_dynamically(tilegroup=tilegroup)
  138.  
  139. !pip install pillow
  140.  
  141. from PIL import Image
  142. import os
  143. import re
  144.  
  145. # Path to the directory containing the tiles
  146. TILES_DIR = "tiles"
  147.  
  148. def merge_tiles(tiles_dir, output_file="merged_image.jpg"):
  149.     # List all files in the tiles directory
  150.     tile_files = [f for f in os.listdir(tiles_dir) if re.match(r'TileGroup\d+_\d+_\d+\.jpg', f)]
  151.  
  152.     if not tile_files:
  153.         print("No tiles found!")
  154.         return
  155.  
  156.     # Extract row and column information from file names
  157.     tiles = []
  158.     for file in tile_files:
  159.         match = re.search(r'TileGroup\d+_(\d+)_(\d+)\.jpg', file)
  160.         if match:
  161.             row, col = int(match.group(1)), int(match.group(2))
  162.             tiles.append((row, col, file))
  163.  
  164.     # Sort tiles by row and column
  165.     tiles.sort(key=lambda x: (x[0], x[1]))
  166.  
  167.     # Determine the number of rows and columns
  168.     max_row = max(t[0] for t in tiles)
  169.     max_col = max(t[1] for t in tiles)
  170.  
  171.     # Open the first tile to get its dimensions
  172.     first_tile = Image.open(os.path.join(tiles_dir, tiles[0][2]))
  173.     tile_width, tile_height = first_tile.size
  174.  
  175.     # Create a blank image for the full map
  176.     full_image = Image.new("RGB", ((max_col + 1) * tile_width, (max_row + 1) * tile_height))
  177.  
  178.     # Paste each tile into the correct position
  179.     for row, col, file in tiles:
  180.         tile_path = os.path.join(tiles_dir, file)
  181.         tile_image = Image.open(tile_path)
  182.         full_image.paste(tile_image, (col * tile_width, row * tile_height))
  183.  
  184.     # Save the full image
  185.     full_image.save(output_file)
  186.     print(f"Image successfully merged and saved as {output_file}")
  187.  
  188. # Run the merging function
  189. merge_tiles(TILES_DIR)
  190.  
  191. from google.colab import files
  192. files.download('merged_image.jpg')
  193.  
  194.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement