#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2024/11/23 07:02:41 +0900> """ Adding gamma correction to mtl file. Usage: python add_gamma.py INPUT.mtl Windows10 x64 21H2 + Python 3.10.10 64bit """ import argparse import os import sys import re # DBG = True DBG = False def linearrgb_to_srgb(c): """Gamma correction.""" r = 0.0 if c < 0.0031308: r = 0.0 if c < 0.0 else c * 12.92 else: r = 1.055 * pow(c, (1.0 / 2.4)) - 0.055 return round(r, 6) def main(): parser = argparse.ArgumentParser(description="Adding gamma correction to mtl file.") parser.add_argument("infile", type=str, help=".mtl filename") args = parser.parse_args() infile = args.infile if not os.path.isfile(infile): print("Error : Not found %s" % (infile)) sys.exit() bakfile = "%s.orig.bak" % (infile) # read file with open(infile) as f: lines = [s.rstrip() for s in f.readlines()] pattern = r"^Kd (\d+\.\d+) (\d+\.\d+) (\d+\.\d+)$" newlines = [] for s in lines: result = re.match(pattern, s) if result: r = linearrgb_to_srgb(float(result.group(1))) g = linearrgb_to_srgb(float(result.group(2))) b = linearrgb_to_srgb(float(result.group(3))) nline = "Kd %f %f %f" % (r, g, b) newlines.append(nline) if DBG: print("%s -> %s" % (s, nline)) else: newlines.append(s) # backup file. rename original file os.rename(infile, bakfile) # write file with open(infile, "w", newline="\n") as fo: for s in newlines: fo.write("%s\n" % (s)) if __name__ == "__main__": main()