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
| import os from decimal import Decimal import numpy as np import cv2 import easyocr import json import shutil from tqdm import tqdm from PIL import Image from pypinyin import pinyin, Style
lan_code = ['ru', 'ind', 'tur', 'deu', 'ita', 'jpn', 'fra', 'tha', 'por', 'spa', 'vie', 'ara', 'kor', 'msa'] language_map = { '俄语': 'ru', '印尼': 'ind', '土耳其': 'tur', '德语': 'deu', '意大利语': 'ita', '日语': 'jpn', '法语': 'fra', '泰语': 'tha', '葡萄牙': 'por', '西班牙语': 'spa', '越南语': 'vie', '阿拉伯语': 'ara', '韩语': 'kor', '马来语': 'msa' }
reader = easyocr.Reader(['ru'], gpu=True) def convert_to_pinyin(text): """ 将中文字符转换为拼音。 """ result = pinyin(text, style=Style.NORMAL) return ''.join([item[0] for item in result])
def clean_path(path): """ 将���径中的非法字符替换为拼音。 """ illegal_chars = r'[\/:*?"<>|]' path_parts = path.split(os.sep) cleaned_parts = []
for part in path_parts: part = convert_to_pinyin(part) cleaned_parts.append(part)
return os.sep.join(cleaned_parts)
def check_language_code_in_directory(directory_path, lan_codes): """ 检查指定路径中是否包含语言代码列表中的任何一个内容。 """ found_codes = []
try: for lan_code in lan_codes: if lan_code in directory_path: found_codes.append(lan_code) return found_codes except Exception as e: print(f"发生错误: {e}") return []
def numpy_encoder(obj): """ 自定义 JSON 序列化函数。 """ if isinstance(obj, np.ndarray): return obj.tolist() raise TypeError(f"Type {type(obj)} not serializable")
def extract_text_with_coords(image_path, folder, lan_code): """ 从图像中提取文字及其坐标,并返回格式化的 JSON 数据。 """ try: lan_zh = check_language_code_in_directory(image_path, folder)
language_codes = "ru" img = Image.open(image_path) img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
if img is None: return {"error": f"无法读取图像: {image_path}"}
results = reader.readtext(image_path)
formatted_results = [] for result in results: bbox, text, _ = result if text.strip(): x_min, y_min = bbox[0] x_max, y_max = bbox[2]
coords = np.array([ [x_min, y_min], [x_max, y_min], [x_max, y_max], [x_min, y_max] ], dtype=np.float64)
result_dict = { "label": text, "points": numpy_encoder(coords), "language": lan_zh[0], "textType": "Mix" if len(text) > 1 else "Single", "textDirection": "Horizontal_0", "assign": "Normal", "group_id": None, "shape_type": "polygon", "flags": {} }
formatted_results.append(result_dict)
cv2.rectangle(img, (int(x_min), int(y_min)), (int(x_max), int(y_max)), (0, 255, 0), 2)
output_image_path = os.path.splitext(image_path)[0] + "_with_boxes.jpg" output_image_path = clean_path(output_image_path)
output_folder = os.path.dirname(output_image_path) if not os.path.exists(output_folder): os.makedirs(output_folder)
result = cv2.imwrite(output_image_path, img) print(f"已保存带框图像: {output_image_path}, result: {result}")
original_image_path = clean_path(image_path) original_output_folder = os.path.dirname(original_image_path) if not os.path.exists(original_output_folder): os.makedirs(original_output_folder)
shutil.copy(image_path, original_image_path) print(f"原图已复制到: {original_image_path}")
return formatted_results
except Exception as e: return {"error": f"发生错误: {str(e)}"}
def save_json_result(image_path, result): """ 将识别结果保存为 JSON 文件。 """ try: image_name = os.path.splitext(os.path.basename(image_path))[0] json_path = os.path.join(os.path.dirname(image_path), f"{image_name}.json") json_path = clean_path(json_path)
with open(json_path, 'w', encoding='utf-8') as json_file: json.dump(result, json_file, ensure_ascii=False, indent=4)
print(f"结果已保存到: {json_path}") except Exception as e: print(f"保存 JSON 文件时发生错误: {str(e)}")
def get_all_images_in_directory(directory_path): """ 递归读取指定目录及其子目录中的所有图像文件。 """ image_files = [] for root, dirs, files in os.walk(directory_path): for file in files: if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')): image_files.append(os.path.join(root, file)) return image_files
def process_images_in_directory(directory_path, folders, lan_code): """ 批量处理指定目录中的所有图像文件。 """ image_paths = get_all_images_in_directory(directory_path)
for image_path in tqdm(image_paths, desc="Processing images"): try: print(f"正在处理图像: {image_path}") folder_name = os.path.basename(os.path.dirname(image_path)) if folder_name in language_map: lan_code = language_map[folder_name] else: print(f"未找到对应的语言代码: {folder_name}") continue
result = extract_text_with_coords(image_path, folders, lan_code)
if isinstance(result, dict) and "error" in result: print(f"处理 {image_path} 时发生错误: {result['error']}") elif isinstance(result, list) and result: save_json_result(image_path, result) else: print(f"处理 {image_path} 时没有检测到有效文本。") except Exception as e: print(f"处理 {image_path} 时发生错误: {str(e)}")
def get_all_folders_in_directory(directory_path): """ 获取目录下所有文件夹名。 """ try: items = os.listdir(directory_path) folders = [item for item in items if os.path.isdir(os.path.join(directory_path, item))] return folders except Exception as e: print(f"发生错误: {e}") return []
def fix_non_ascii_path(path): """ 修复路径中的非 ASCII 字符问题。 """ return path.encode('utf-8').decode('utf-8')
image_directory = r"C:\Users\DELL\Desktop\CZQ\俄语" image_directory = fix_non_ascii_path(image_directory) folders = get_all_folders_in_directory(image_directory) print("文件夹列表:", folders)
process_images_in_directory(image_directory, folders, lan_code)
|