-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimg2stru.py
More file actions
300 lines (244 loc) · 12.3 KB
/
Copy pathimg2stru.py
File metadata and controls
300 lines (244 loc) · 12.3 KB
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import os
import json
import re
import random
import numpy as np
from PIL import Image
from scipy.spatial import KDTree
from tqdm import tqdm
import mcstructure
from mcstructure import Block, Structure
# 1. 强制破解库的尺寸限制
mcstructure.STRUCTURE_MAX_SIZE = (999999, 999999, 999999)
# 2. 终极防卡死 & 防噪点黑名单 (去除了会导致画面变脏的带釉陶瓦、原矿、紫珀等杂色方块)
EXCLUDE_KEYWORDS = [
"carpet", "slab", "door", "dragon_egg", "anvil", "snow_layer",
"stairs", "button", "pressure_plate", "fence", "wall", "sign",
"daylight", "frame", "invisibleBedrock", "chorus", "trapdoor",
"lantern", "torch", "reeds", "wheat", "stem", "rail", "vine",
"ladder","stonecutter_block", "bed", "shulker_box", "skull",
"head", "barrier", "end_portal_frame", "piston","lectern",
"hopper", "cauldron", "brewing_stand","sculk_sensor",
"enchanting_table", "end_gateway", "end_portal", "moving_piston",
"light", "snow", "bubble_column", "coral", "sea_pickle", "kelp",
"vault", "structure", "bee_nest", "beehive", "spawner", "campfire"
]
print(f"已设置排除关键词 (防卡 & 防噪点): {EXCLUDE_KEYWORDS}")
# ==================== 核心视觉算法 ====================
def rgb_to_lab(rgb_input):
"""
将 RGB 数组转换为 CIELAB 色彩空间。
LAB 空间完美契合人类肉眼的感知特性,能彻底消除突兀的粉色、蓝色等色相偏差。
"""
rgb = rgb_input / 255.0
# RGB to XYZ
rgb = np.where(rgb > 0.04045, ((rgb + 0.055) / 1.055) ** 2.4, rgb / 12.92)
x = rgb[..., 0] * 0.4124564 + rgb[..., 1] * 0.3575761 + rgb[..., 2] * 0.1804375
y = rgb[..., 0] * 0.2126729 + rgb[..., 1] * 0.7151522 + rgb[..., 2] * 0.0721750
z = rgb[..., 0] * 0.0193339 + rgb[..., 1] * 0.1191920 + rgb[..., 2] * 0.9503041
xyz = np.stack([x, y, z], axis=-1)
xyz_ref_white = np.array([0.95047, 1.00000, 1.08883])
xyz = xyz / xyz_ref_white
# XYZ to LAB
xyz = np.where(xyz > 0.008856, xyz ** (1/3.0), (7.787 * xyz) + (16 / 116.0))
L = (116 * xyz[..., 1]) - 16
a = 500 * (xyz[..., 0] - xyz[..., 1])
b = 200 * (xyz[..., 1] - xyz[..., 2])
return np.stack([L, a, b], axis=-1)
# ======================================================
def get_texture_by_priority(tex_field, priority_list):
if isinstance(tex_field, str): return tex_field
if isinstance(tex_field, dict):
for key in priority_list:
if key in tex_field: return tex_field[key]
vals = list(tex_field.values())
return vals[0] if vals else None
return None
def is_texture_solid_16(img_path):
if not os.path.exists(img_path): return False
try:
with Image.open(img_path).convert("RGBA") as img:
if img.size != (16, 16): return False
img_np = np.array(img)
return not np.any(img_np[:, :, 3] < 255)
except:
return False
def load_palette(json_path, pack_root, is_3d_mode=False):
if not os.path.exists(json_path):
print(f"错误: 找不到 blocks.json: {json_path}")
return None
with open(json_path, 'r', encoding='utf-8') as f:
content = re.sub(r'//.*', '', f.read())
data = json.loads(content)
temp_palettes = {
"up": {"rgbs": [], "meta": []},
"flat": {"rgbs": [], "meta": []},
"down": {"rgbs": [], "meta": []}
}
items = list(data.items())
print(f"--- 正在分析方块贴图 ({'3D模式' if is_3d_mode else '2D模式'}) ---")
for block_id, info in tqdm(items, desc="构建色板", unit="方块"):
if block_id == "format_version" or not isinstance(info, dict): continue
if any(k in block_id for k in EXCLUDE_KEYWORDS): continue
tex_field = info.get("textures")
if not tex_field: continue
p_list = ["up", "all"] if is_3d_mode else ["side", "all", "up"]
target_tex = get_texture_by_priority(tex_field, p_list)
if not target_tex: continue
path = os.path.join(pack_root, "textures", "blocks", target_tex + ".png")
if not is_texture_solid_16(path): continue
try:
with Image.open(path).convert("RGB") as img:
base_rgb = np.array(img).mean(axis=(0, 1))
if is_3d_mode:
temp_palettes["up"]["rgbs"].append(np.clip(base_rgb * 1.0, 0, 255))
temp_palettes["up"]["meta"].append((f"minecraft:{block_id}", 1))
temp_palettes["flat"]["rgbs"].append(np.clip(base_rgb * 0.86, 0, 255))
temp_palettes["flat"]["meta"].append((f"minecraft:{block_id}", 0))
temp_palettes["down"]["rgbs"].append(np.clip(base_rgb * 0.71, 0, 255))
temp_palettes["down"]["meta"].append((f"minecraft:{block_id}", -1))
else:
temp_palettes["flat"]["rgbs"].append(base_rgb)
temp_palettes["flat"]["meta"].append((f"minecraft:{block_id}", 0))
except: continue
final_palettes = {}
for key, val in temp_palettes.items():
labs_arr = rgb_to_lab(np.array(val["rgbs"])) if val["rgbs"] else np.array([])
final_palettes[key] = {
"labs": labs_arr,
"meta": val["meta"]
}
return final_palettes
def convert(img_path, json_path, pack_root, target_w, target_h, mode, chunk_size):
is_3d = (mode == "7")
palettes = load_palette(json_path, pack_root, is_3d)
if palettes is None or len(palettes["flat"]["labs"]) == 0:
print("构建色板失败或为空,终止转换。")
return
tree_flat = KDTree(palettes["flat"]["labs"])
if is_3d:
if len(palettes["up"]["labs"]) == 0 or len(palettes["down"]["labs"]) == 0:
print("3D模式色板构建异常,终止转换。")
return
tree_up = KDTree(palettes["up"]["labs"])
tree_down = KDTree(palettes["down"]["labs"])
with Image.open(img_path).convert("RGB") as img:
orig_w, orig_h = img.size
if target_w and not target_h:
W = target_w
H = int(orig_h * (W / orig_w))
elif target_h and not target_w:
H = target_h
W = int(orig_w * (H / orig_h))
elif target_w and target_h:
W = target_w
H = target_h
else:
W = 128
H = int(orig_h * (W / orig_w))
img = img.resize((W, H), Image.Resampling.LANCZOS)
img_np = np.array(img)
img_lab = rgb_to_lab(img_np)
print(f"--- 阶段1: 全局像素感知分析 (尺寸: {W}x{H}) ---")
block_ids = np.empty((H, W), dtype=object)
heights = np.zeros((H, W), dtype=int)
if is_3d:
curr_y = np.full(W, 32, dtype=int)
for z in tqdm(range(H), desc="分析3D连贯性", unit="行"):
for x in range(W):
target_color = img_lab[z, x]
best_dist = float('inf')
best_block_id = "minecraft:stone"
best_y_step = 0
if curr_y[x] < 63:
d_up, idx_up = tree_up.query(target_color)
if float(d_up) < best_dist:
best_dist = float(d_up)
best_block_id = str(palettes["up"]["meta"][int(idx_up)][0])
best_y_step = 1
d_flat, idx_flat = tree_flat.query(target_color)
if float(d_flat) < best_dist:
best_dist = float(d_flat)
best_block_id = str(palettes["flat"]["meta"][int(idx_flat)][0])
best_y_step = 0
if curr_y[x] > 0:
d_down, idx_down = tree_down.query(target_color)
if float(d_down) < best_dist:
best_block_id = str(palettes["down"]["meta"][int(idx_down)][0])
best_y_step = -1
if z > 0: curr_y[x] += best_y_step
block_ids[z, x] = best_block_id
heights[z, x] = curr_y[x]
mode_str = "3DMap64"
else:
flat_pixels = img_lab.reshape(-1, 3)
_, indices = tree_flat.query(flat_pixels)
indices_list = indices.flatten().tolist()
flat_meta = palettes["flat"]["meta"]
for i in tqdm(range(len(indices_list)), desc="分析2D像素", unit="像素"):
z, x = divmod(i, W)
block_ids[z, x] = str(flat_meta[int(indices_list[i])][0])
mode_str = "2D"
print("--- 阶段2: 分片写入与导出 ---")
num_chunks_x = (W + chunk_size - 1) // chunk_size
num_chunks_y = (H + chunk_size - 1) // chunk_size
rand_id = random.randint(1000, 9999)
total_chunks = num_chunks_x * num_chunks_y
with tqdm(total=total_chunks, desc="导出结构文件", unit="片") as pbar:
for cy in range(num_chunks_y):
for cx in range(num_chunks_x):
x0 = cx * chunk_size
y0 = cy * chunk_size
cw = min(chunk_size, W - x0)
ch = min(chunk_size, H - y0)
if is_3d:
struct = Structure((cw, 64, ch))
for z in range(ch):
for x in range(cw):
# 强制转 str 修复 Pylance 错误 1
b_id = str(block_ids[y0 + z, x0 + x])
b_y = heights[y0 + z, x0 + x]
struct.set_block((x, int(b_y), z), Block(b_id))
else:
orient_map = {"1":(cw,1,ch), "2":(cw,1,ch), "3":(cw,ch,1), "4":(cw,ch,1), "5":(1,ch,cw), "6":(1,ch,cw)}
dim = orient_map.get(mode, (cw,ch,1))
struct = Structure(dim)
for z in range(ch):
for x in range(cw):
# 强制转 str 修复 Pylance 错误 2
b_id = str(block_ids[y0 + z, x0 + x])
if mode == "1": pos = (x, 0, z)
elif mode == "2": pos = (x, 0, ch-1-z)
elif mode == "3": pos = (cw-1-x, ch-1-z, 0)
elif mode == "4": pos = (x, ch-1-z, 0)
elif mode == "5": pos = (0, ch-1-z, cw-1-x)
elif mode == "6": pos = (0, ch-1-z, x)
else: pos = (x, ch-1-z, 0)
struct.set_block(pos, Block(b_id))
suffix = f"_part_{cx}_{cy}" if total_chunks > 1 else ""
out_name = f"art_{mode_str}_{rand_id}{suffix}.mcstructure"
with open(out_name, "wb") as f:
struct.dump(f)
pbar.update(1)
print(f"\n✅ 全部转换完成!(总计 {total_chunks} 个文件)")
if total_chunks > 1:
print(f"📌 拼装提示: 文件名中的 'part_X_Y' 代表坐标。\n X 表示从左往右第几个,Y 表示从上往下第几个。\n 如 part_0_0 为左上角第一块,拼装时请按顺序对接!")
if __name__ == "__main__":
root = os.path.dirname(os.path.abspath(__file__))
p = input("🖼️ 图片路径: ").replace("\"", "").strip()
size_input = input("📏 整体尺寸 (例: w5000 代表宽五千, h256 代表高256, 回车默认宽128): ").strip().lower()
target_w, target_h = None, None
if size_input.startswith("w") and size_input[1:].isdigit():
target_w = int(size_input[1:])
elif size_input.startswith("h") and size_input[1:].isdigit():
target_h = int(size_input[1:])
elif size_input.isdigit():
target_w = int(size_input)
else:
target_w = 128
chunk_input = input("📦 分片大小 (巨幅图片防卡死功能, 建议输入 256, 不分片请直接回车): ").strip()
chunk_size = int(chunk_input) if chunk_input.isdigit() else 999999
print("\n🗺️ 模式选择:")
print("1.地面 2.天花板 3.北墙 4.南墙 5.东墙 6.西墙 7.3D阶梯地图画")
m = input("请输入 (1-7): ") or "4"
convert(p, os.path.join(root, "blocks.json"), root, target_w, target_h, m, chunk_size)