File size: 1,911 Bytes
33201c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Downscale packaged textures in place (helper for package_task9_background.py).

Usage: python3 _downscale_textures.py <package_dir> <shell_max_px> <prop_max_px>

Reads resource/textures_manifest.tsv (rel_path<TAB>shell|prop) and caps the
longest image side per class. Only common raster formats PIL handles are
touched (.png/.jpg/.jpeg/.tga); .hdr/.exr/.mdl and anything PIL cannot
process are kept as-is. Never upscales.
"""

import sys
from pathlib import Path

from PIL import Image

Image.MAX_IMAGE_PIXELS = None  # dataset ships some very large textures

package_dir = Path(sys.argv[1])
max_px = {"shell": int(sys.argv[2]), "prop": int(sys.argv[3])}
manifest = package_dir / "resource" / "textures_manifest.tsv"

RASTER_EXTS = {".png", ".jpg", ".jpeg", ".tga"}

before_total = after_total = 0
resized = skipped = failed = 0
for line in manifest.read_text().splitlines():
    rel, cls = line.split("\t")
    path = package_dir / rel
    if not path.exists() or path.suffix.lower() not in RASTER_EXTS:
        skipped += 1
        continue
    size_before = path.stat().st_size
    before_total += size_before
    try:
        with Image.open(path) as im:
            longest = max(im.size)
            cap = max_px[cls]
            if longest <= cap:
                after_total += size_before
                skipped += 1
                continue
            scale = cap / longest
            new_size = (max(1, round(im.width * scale)), max(1, round(im.height * scale)))
            im = im.resize(new_size, Image.LANCZOS)
            im.save(path)
        after_total += path.stat().st_size
        resized += 1
    except Exception as exc:
        print(f"  keep as-is (PIL failed): {rel}: {exc}")
        after_total += size_before
        failed += 1

print(f"  resized {resized}, unchanged {skipped}, failed {failed}; "
      f"textures {before_total / 1e6:.1f} MB -> {after_total / 1e6:.1f} MB")