cut-dialog-block.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. /**
  2. * 步骤1: 创建startCutDialogBlock()函数
  3. * 步骤2: 接收参数:cutPanelImgDir (切割好的图片存放路径)
  4. * 步骤3: 接收参数:cutCheckResultArr (切割好的图片路径数组,根据这个路径的图片文件名,新建对应数量的文件夹)
  5. * 步骤3: 调用Python脚本依次检测绿色线框并切图
  6. * 步骤4: 给切割好的图片编号,根据从右到左,从上到下顺序编号,保存到cutCheckResultArr对应图片文件名的文件夹下
  7. * 步骤5: 返回切割好的图片路径数组
  8. */
  9. import fs from 'fs';
  10. import path from 'path';
  11. import { fileURLToPath } from 'url';
  12. import { execSync } from 'child_process';
  13. import { getPythonPath } from './python-path.js';
  14. const __filename = fileURLToPath(import.meta.url);
  15. const __dirname = path.dirname(__filename);
  16. function getProjectRoot() {
  17. return path.join(__dirname, '..');
  18. }
  19. /**
  20. * 步骤1: 创建startCutDialogBlock()函数
  21. * @param {string} cutPanelImgDir - 步骤2: 切割好的图片存放路径(外部传入)
  22. * @param {Array} cutCheckResultArr - 步骤3: 切割好的图片路径数组(外部传入)
  23. * @returns {Promise<Array>} 步骤5: 返回切割好的图片路径数组
  24. */
  25. async function startCutDialogBlock(cutPanelImgDir, cutCheckResultArr) {
  26. try {
  27. console.log('🚀 开始文字块切割流程...');
  28. // 步骤2: 接收参数:cutPanelImgDir (切割好的图片存放路径)
  29. console.log('\n📂 步骤2: 验证图片存放路径参数');
  30. if (!cutPanelImgDir) {
  31. throw new Error('步骤2失败: cutPanelImgDir 参数不能为空');
  32. }
  33. if (!fs.existsSync(cutPanelImgDir)) {
  34. throw new Error(`步骤2失败: 图片存放路径不存在 - ${cutPanelImgDir}`);
  35. }
  36. console.log(`✅ 图片存放路径: ${cutPanelImgDir}`);
  37. // 步骤3: 接收参数:cutCheckResultArr (切割好的图片路径数组)
  38. console.log('\n📋 步骤3: 验证图片路径数组参数');
  39. if (!cutCheckResultArr || !Array.isArray(cutCheckResultArr)) {
  40. throw new Error('步骤3失败: cutCheckResultArr 必须是一个数组');
  41. }
  42. if (cutCheckResultArr.length === 0) {
  43. throw new Error('步骤3失败: cutCheckResultArr 不能为空数组');
  44. }
  45. console.log(`✅ 图片路径数组长度: ${cutCheckResultArr.length}`);
  46. // 根据图片路径的文件名,新建对应数量的文件夹
  47. console.log('\n📁 步骤3: 为每个图片创建对应的文件夹...');
  48. const panelFolders = [];
  49. for (let i = 0; i < cutCheckResultArr.length; i++) {
  50. const panelImgPath = cutCheckResultArr[i];
  51. const panelFileName = path.basename(panelImgPath, path.extname(panelImgPath));
  52. const panelFolderPath = path.join(cutPanelImgDir, panelFileName);
  53. if (!fs.existsSync(panelFolderPath)) {
  54. fs.mkdirSync(panelFolderPath, { recursive: true });
  55. }
  56. panelFolders.push({
  57. panelImgPath: panelImgPath,
  58. panelFolderPath: panelFolderPath,
  59. panelFileName: panelFileName
  60. });
  61. console.log(` 📁 [${i + 1}] 创建文件夹: ${panelFileName}/`);
  62. }
  63. // 步骤3: 调用Python脚本依次检测绿色线框并切图
  64. console.log('\n🔍 步骤3: 调用Python脚本检测绿色线框...');
  65. const allCutFiles = [];
  66. for (let i = 0; i < panelFolders.length; i++) {
  67. const { panelImgPath, panelFolderPath, panelFileName } = panelFolders[i];
  68. console.log(`\n 🔍 [${i + 1}/${panelFolders.length}] 处理图片: ${panelFileName}`);
  69. const cutFiles = await cutDialogBlocks(panelImgPath, panelFolderPath);
  70. // 步骤4: 给切割好的图片编号,根据从右到左,从上到下顺序编号
  71. console.log(` ✅ 检测到 ${cutFiles.length} 个文字块,正在编号保存...`);
  72. allCutFiles.push(...cutFiles);
  73. }
  74. // 步骤5: 返回切割好的图片路径数组
  75. console.log('\n📋 步骤5: 准备返回文字块图片路径数组...');
  76. console.log(`📄 文字块图片路径列表 (${allCutFiles.length} 个):`);
  77. allCutFiles.forEach((file, index) => {
  78. console.log(` ${index + 1}. ${path.basename(file)}`);
  79. });
  80. console.log(`✅ 步骤5完成: 文字块图片路径数组已准备就绪 (${allCutFiles.length} 个路径)`);
  81. console.log('\n🎉 所有步骤完成!');
  82. console.log(`📊 共处理 ${panelFolders.length} 个格子图片`);
  83. console.log(`📊 共切割 ${allCutFiles.length} 个文字块图片`);
  84. return allCutFiles; // 步骤5: 返回切割好的图片路径数组
  85. } catch (error) {
  86. console.error(`\n❌ 文字块切割失败: ${error.message}`);
  87. throw error;
  88. }
  89. }
  90. /**
  91. * 处理单个格子图片,检测绿色线框并切割文字块
  92. * @param {string} panelImgPath - 格子图片路径
  93. * @param {string} outputFolderPath - 输出文件夹路径
  94. * @returns {Promise<Array>} 切割后的文件路径数组
  95. */
  96. async function cutDialogBlocks(panelImgPath, outputFolderPath) {
  97. const projectRoot = getProjectRoot();
  98. const pythonEnv = getPythonPath();
  99. // 使用绿色线框检测脚本
  100. const cutScript = path.join(projectRoot, 'python', 'generate-anim', 'cut_dialog_blocks_by_green_box.py');
  101. if (!fs.existsSync(cutScript)) {
  102. throw new Error(`Python脚本不存在: ${cutScript}`);
  103. }
  104. // 调用Python脚本
  105. const command = `"${pythonEnv}" "${cutScript}" "${panelImgPath}" "${outputFolderPath}"`;
  106. try {
  107. const output = execSync(command, {
  108. encoding: 'utf-8',
  109. stdio: 'pipe',
  110. cwd: projectRoot,
  111. env: {
  112. ...process.env,
  113. PYTHONIOENCODING: 'utf-8',
  114. PYTHONUTF8: '1'
  115. },
  116. shell: true
  117. });
  118. // 打印Python脚本的调试输出(完整输出)
  119. if (output) {
  120. const debugLines = output.split('\n').filter(line => line.includes('[DEBUG]') || line.includes('center_x'));
  121. if (debugLines.length > 0) {
  122. console.log(` ${debugLines.join('\n ')}`);
  123. }
  124. }
  125. } catch (error) {
  126. console.log(` ⚠️ 该图片未检测到文字块: ${path.basename(panelImgPath)}`);
  127. if (error.stdout) {
  128. const debugLines = error.stdout.split('\n').filter(line => line.includes('[DEBUG]') || line.includes('center_x'));
  129. if (debugLines.length > 0) {
  130. console.log(` ${debugLines.join('\n ')}`);
  131. }
  132. }
  133. return [];
  134. }
  135. // 获取切割结果文件列表(按从右到左、从上到下的顺序编号)
  136. const cutFiles = fs.readdirSync(outputFolderPath)
  137. .filter(f => f.match(/^dialog_\d+\.png$/)) // 匹配 dialog_1.png, dialog_2.png 等
  138. .sort((a, b) => {
  139. const numA = parseInt(a.match(/dialog_(\d+)/)?.[1] || '0');
  140. const numB = parseInt(b.match(/dialog_(\d+)/)?.[1] || '0');
  141. return numA - numB;
  142. })
  143. .map(f => path.join(outputFolderPath, f));
  144. return cutFiles;
  145. }
  146. /**
  147. * 创建绿色线框检测和切割的Python脚本
  148. */
  149. function createCutDialogScript(scriptPath) {
  150. const scriptContent = `#!/usr/bin/env python3
  151. # -*- coding: utf-8 -*-
  152. """
  153. 简单的绿色线框检测和文字块切割脚本
  154. """
  155. import cv2
  156. import numpy as np
  157. import sys
  158. from pathlib import Path
  159. def detect_green_boxes_and_cut(image_path, output_dir):
  160. """检测绿色线框并切割文字块"""
  161. # 读取图片
  162. img_data = np.fromfile(str(image_path), dtype=np.uint8)
  163. img = cv2.imdecode(img_data, cv2.IMREAD_COLOR)
  164. if img is None:
  165. raise ValueError(f"无法读取图片: {image_path}")
  166. print(f"[INFO] 图片尺寸: {img.shape[1]}x{img.shape[0]}")
  167. # 检测绿色线框
  168. # 绿色范围 (BGR格式)
  169. lower_green = np.array([0, 100, 0])
  170. upper_green = np.array([100, 255, 100])
  171. # 创建绿色掩码
  172. mask = cv2.inRange(img, lower_green, upper_green)
  173. # 寻找轮廓
  174. contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  175. if len(contours) == 0:
  176. print("[INFO] 未检测到绿色线框")
  177. return
  178. # 获取边界矩形
  179. boxes = []
  180. for contour in contours:
  181. x, y, w, h = cv2.boundingRect(contour)
  182. if w > 10 and h > 10: # 过滤小框
  183. boxes.append({'x': x, 'y': y, 'w': w, 'h': h})
  184. if len(boxes) == 0:
  185. print("[INFO] 未找到有效的文字框")
  186. return
  187. print(f"[INFO] 检测到 {len(boxes)} 个绿色文字框")
  188. # 按从右到左、从上到下排序
  189. boxes.sort(key=lambda b: (b['y'], -b['x']))
  190. # 确保输出目录存在
  191. Path(output_dir).mkdir(parents=True, exist_ok=True)
  192. # 切割并保存每个文字块
  193. for i, box in enumerate(boxes, 1):
  194. x, y, w, h = box['x'], box['y'], box['w'], box['h']
  195. # 添加少量边距
  196. padding = 5
  197. x = max(0, x - padding)
  198. y = max(0, y - padding)
  199. w = min(w + 2 * padding, img.shape[1] - x)
  200. h = min(h + 2 * padding, img.shape[0] - y)
  201. # 切割区域
  202. dialog_img = img[y:y+h, x:x+w]
  203. # 保存文件
  204. output_file = Path(output_dir) / f"dialog_{i}.png"
  205. success, encoded = cv2.imencode('.png', dialog_img)
  206. if success:
  207. encoded.tofile(str(output_file))
  208. print(f"[{i}/{len(boxes)}] 保存: {output_file.name} ({w}x{h})")
  209. print(f"✅ 文字块切割完成: {len(boxes)} 个")
  210. if __name__ == '__main__':
  211. if len(sys.argv) != 3:
  212. print("用法: python cut_dialog_blocks.py <图片路径> <输出目录>")
  213. sys.exit(1)
  214. try:
  215. detect_green_boxes_and_cut(sys.argv[1], sys.argv[2])
  216. except Exception as e:
  217. print(f"[ERROR] {e}")
  218. sys.exit(1)
  219. `;
  220. // 确保目录存在
  221. const scriptDir = path.dirname(scriptPath);
  222. if (!fs.existsSync(scriptDir)) {
  223. fs.mkdirSync(scriptDir, { recursive: true });
  224. }
  225. fs.writeFileSync(scriptPath, scriptContent, 'utf-8');
  226. }
  227. /**
  228. * 导出函数供外部调用
  229. */
  230. export { startCutDialogBlock };