cosmo/scripts/gen_night_earth.py

73 lines
2.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""生成火箭模拟用的夜间地球贴图。
原始的 2k_earth_nightmap.jpg 只有城市灯光(98% 的像素亮度低于 30),
镜头拉远时几乎看不出大陆轮廓。这里以昼间图为底:
- 保留昼间图的海陆与地形起伏,压暗、去饱和、偏冷,作为「月光下的地球」;
- 沿海岸线加一圈向外衰减的冷色辉光,让大陆轮廓一眼可辨;
- 叠加原夜间图的城市灯光(含少量辉光),只落在陆地上。
全程在线性光域混合,最后再编码回 sRGB。
用法:python3 scripts/gen_night_earth.py
输入/输出都在 backend/upload/assets/ 下(随 git 分发)。
"""
from pathlib import Path
import numpy as np
from PIL import Image, ImageFilter
ASSETS = Path(__file__).resolve().parent.parent / "backend" / "upload" / "assets"
DAY = ASSETS / "2k_earth_daymap.jpg"
NIGHT = ASSETS / "2k_earth_nightmap.jpg"
OUT = ASSETS / "2k_earth_nightrelief.jpg"
# 昼间贴图里海洋是一整块纯色,直接按色距判定海陆
OCEAN_RGB = np.array([30, 59, 117]) / 255.0
def to_linear(c):
return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
def to_srgb(c):
return np.where(c <= 0.0031308, c * 12.92, 1.055 * np.power(np.maximum(c, 0), 1 / 2.4) - 0.055)
def blur(mask, sigma):
grown = Image.fromarray((mask * 255).astype("uint8")).filter(ImageFilter.GaussianBlur(sigma))
return np.asarray(grown).astype("float32") / 255.0
def main():
day = np.asarray(Image.open(DAY).convert("RGB")).astype("float32") / 255.0
lights_src = np.asarray(Image.open(NIGHT).convert("RGB")).astype("float32") / 255.0
d, n = to_linear(day), to_linear(lights_src)
# 海陆掩膜先模糊一次再取半阈值,免得沿 JPEG 方块长出毛刺
raw = (np.abs(day - OCEAN_RGB).sum(axis=2) < 0.06).astype("float32")
ocean = blur(raw, 1.2) >= 0.5
ice = day.min(axis=2) > 0.72
lum = d.mean(axis=2, keepdims=True)
land = (0.14 + 0.86 * (d * 0.35 + lum * 0.65)) * 0.175 * np.array([0.78, 0.90, 1.16])
land = land + ice[..., None] * np.array([0.012, 0.017, 0.026])
base = np.where(ocean[..., None], np.array([0.0022, 0.0062, 0.0155]), land)
coast = (blur(ocean, 1.4) * (~ocean))[..., None] * np.array([0.045, 0.068, 0.100])
shelf = (blur(~ocean, 2.4) * ocean)[..., None] * np.array([0.016, 0.030, 0.056])
strength = np.clip(n.mean(axis=2, keepdims=True) * 7, 0, 1)
lights = n * strength * 0.95
bloom = np.asarray(
Image.fromarray((lights.max(axis=2) * 255).clip(0, 255).astype("uint8")).filter(ImageFilter.MaxFilter(3))
).astype("float32") / 255.0
lights = (lights + bloom[..., None] * np.array([0.022, 0.014, 0.007])) * (~ocean)[..., None]
out = (to_srgb(base + coast + shelf + lights).clip(0, 1) * 255).astype("uint8")
Image.fromarray(out).save(OUT, quality=88)
print(f"{OUT.name}: {OUT.stat().st_size // 1024} KB")
if __name__ == "__main__":
main()