File size: 3,065 Bytes
0c243c1 a8b0b54 0c243c1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | import numpy as np
from PIL import Image
import os
from pathlib import Path
import config
def load_tiles():
"""
Load all tiles from the tile directory.
NOTE: This loads tiles every time - inefficient!
"""
tile_path = Path(config.tile_directory)
if not tile_path.exists():
print(f"Warning: Tile directory {config.tile_directory} not found!")
print("Creating sample tiles...")
create_sample_tiles()
tile_path = Path(config.tile_directory)
# Load all image files
valid_extensions = {'.jpg', '.jpeg', '.png', '.bmp'}
tile_files = [f for f in tile_path.iterdir()
if f.suffix.lower() in valid_extensions]
if not tile_files:
print("No tile images found! Creating sample tiles...")
config.create_sample_tiles()
tile_files = [f for f in tile_path.iterdir()
if f.suffix.lower() in valid_extensions]
print(f"Loading {len(tile_files)} tiles...")
for tile_file in tile_files:
try:
tile = Image.open(tile_file)
tile = tile.convert('RGB')
tile = tile.resize((32, 32)) # Standard tile size
tile_array = np.array(tile)
config.tiles.append(tile_array)
# Compute average color for this tile
avg_color = np.mean(tile_array, axis=(0, 1))
config.tile_colors.append(avg_color)
except Exception as e:
print(f"Error loading {tile_file}: {e}")
print(f"Loaded {len(config.tiles)} tiles successfully")
def create_sample_tiles():
"""
Create sample colored tiles if no tiles are provided.
This creates a basic set of tiles with different colors.
"""
os.makedirs(config.tile_directory, exist_ok=True)
# Create tiles with different colors
colors = [
(255, 0, 0), # Red
(0, 255, 0), # Green
(0, 0, 255), # Blue
(255, 255, 0), # Yellow
(255, 0, 255), # Magenta
(0, 255, 255), # Cyan
(255, 255, 255), # White
(128, 128, 128), # Gray
(0, 0, 0), # Black
(255, 128, 0), # Orange
(128, 0, 255), # Purple
(0, 128, 128), # Teal
]
for i, color in enumerate(colors):
tile = np.full((32, 32, 3), color, dtype=np.uint8)
img = Image.fromarray(tile)
img.save(os.path.join(config.tile_directory, f'tile_{i:02d}.png'))
print(f"Created {len(colors)} sample tiles in {config.tile_directory}")
def find_best_tile(target_color):
"""
Find the tile that best matches the target color.
Parameters:
-----------
target_color : np.ndarray
Target RGB color
Returns:
--------
int : Index of best matching tile
"""
target_color = np.array(target_color)
differences = config.tile_colors - target_color
distances = np.linalg.norm(differences, axis=1)
distances = np.abs(distances)
return np.argmin(distances)
|