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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
| import shutil import tkinter as tk import traceback from pathlib import Path from typing import *
import cv2 import numpy as np from PIL import Image, ImageTk
def read_mesh_obj(path): vertex = [] vertex_texture = [] vector_normal = [] face = [] with open(path, "r", encoding="utf8") as f: for line in f: type_, *values = line.strip().split(" ")
if type_ == "v": vertex.append(list(map(int, values[:2]))) elif type_ == "vt": vertex_texture.append(list(map(float, values))) elif type_ == "f": face.append([list(map(int, value.split("/"))) for value in values]) else: continue return vertex, vertex_texture, face
def restore_painting(texture: np.ndarray, v, vt, f) -> np.ndarray: v = np.array(v)[:, 0:2] vt = np.array(vt) f = np.array(f)[:, :, 0:2]
v = np.abs(v) v[:, 1] = np.max(v[:, 1]) - v[:, 1]
vt = vt * np.array(texture.shape[1::-1]).reshape(1, 2) vt[:, 1] = texture.shape[0] - vt[:, 1] vt = np.round(vt, 0).astype(int)
width, height = np.max(v, axis=0) + 2 png = np.zeros((height, width, 4), dtype=texture.dtype)
for i in range(0, len(f), 2): v_rect_pts: List[Tuple[int, int]] = [] vt_rect_pts: List[Tuple[int, int]] = []
for v_idx, vt_idx in f[i]: v_rect_pts.append(v[v_idx - 1]) vt_rect_pts.append(vt[vt_idx - 1])
for v_idx, vt_idx in f[i + 1]: v_rect_pts.append(v[v_idx - 1]) vt_rect_pts.append(vt[vt_idx - 1])
leftup_v, *_, rightdown_v = sorted(v_rect_pts, key=list) leftup_vt, *_, rightdown_vt = sorted(vt_rect_pts, key=list)
leftup_v = (leftup_v + 1) - 1 rightdown_v = (rightdown_v + 1) + 1 leftup_vt = leftup_vt - 1 rightdown_vt = rightdown_vt + 1
size1 = rightdown_v - leftup_v size2 = rightdown_vt - leftup_vt if not all(size1 == size2): texture_region = texture[leftup_vt[1]:rightdown_vt[1], leftup_vt[0]:rightdown_vt[0]] alpha_value = 10
row_delta = size2[1] - size1[1] if row_delta == 1: if np.all(texture_region[-1, :, -1] < alpha_value): rightdown_vt[1] -= 1 elif np.all(texture_region[0, :, -1] < alpha_value): leftup_vt[1] += 1 else: raise ValueError("Empty row not found!") elif row_delta > 1: raise ValueError(f"{row_delta} extra rows found.")
col_delta = size2[0] - size1[0] if col_delta == 1: if np.all(texture_region[:, -1, -1] < alpha_value): rightdown_vt[0] -= 1 elif np.all(texture_region[:, 0, -1] < alpha_value): leftup_vt[0] += 1 else: raise ValueError("Empty col not found!") elif col_delta > 1: raise ValueError(f"{col_delta} extra cols found.")
png[leftup_v[1]:rightdown_v[1], leftup_v[0]:rightdown_v[0]] = texture[leftup_vt[1]:rightdown_vt[1], leftup_vt[0]:rightdown_vt[0]]
return png
def choose_image(image_path): def on_confirm(): root.result = True root.destroy()
def on_cancel(): root.result = False root.destroy()
root = tk.Tk() root.title("选择保留") root.result = False
image = Image.open(image_path) max_size = (300, 300) image.thumbnail(max_size) photo = ImageTk.PhotoImage(image)
label = tk.Label(root, image=photo) label.pack(padx=5, pady=5)
confirm_button = tk.Button(root, text="复制", command=on_confirm) confirm_button.pack(side=tk.LEFT, padx=(20, 10), pady=10)
cancel_button = tk.Button(root, text="放弃", command=on_cancel) cancel_button.pack(side=tk.RIGHT, padx=(10, 20), pady=10)
root.mainloop() return root.result
PNG_DIR = Path("./Texture2D") OBJ_DIR = Path("./Mesh")
EXPORT_DIR = Path("./paintings")
if __name__ == "__main__": count = 0 for png in PNG_DIR.iterdir(): char_name = png.stem
print(char_name) count += 1
painting_path = EXPORT_DIR.joinpath(png.name)
for mesh in OBJ_DIR.glob(f"{char_name}-mesh*.obj"): v, vt, f = read_mesh_obj(mesh) texture: np.ndarray = cv2.imread(png.as_posix(), cv2.IMREAD_UNCHANGED)
try: painting = restore_painting(texture, v, vt, f) except ValueError: traceback.print_exc() print(f"Restore Error: {char_name}") continue
cv2.imwrite(painting_path.as_posix(), painting) break else: print(f"No valid mesh file found for {png}") if choose_image(png): print(f"Copy: {png}") shutil.copy(png, painting_path) else: print(f"Discard: {png}")
print(f"Total: {count}") input("Press <Enter> to exit...")
|