"““快递面单OCR演示:图像预处理 -> 文字检测 -> 文字识别 -> 结构化纠错””“ import re class WaybillOCR: def init(self, addr_lib): self.addr_lib = addr_lib # 地址库 self.ph_re = re.compile(r”1[3-9]\d{9}“) self.results = [] # 识别结果列表 def preprocess(self, image): ”““预处理第1步:灰度化并二值化(模拟)””" gray = [[max(0, min(255, p)) for p in row] for row in image] return [[1 if p > 128 else 0 for p in row] for row in gray] def detect_text_blocks(self, binary): "““检测第2步:定位文字区域(模拟返回行坐标)””" h, w = len(binary), len(binary[0]) return [{"y0": int(h r), "h": int(h 0.05), "x0": int(w 0.1), "w": int(w (0.7 + 0.1 * (r % 3))), "text": ""} for r in range(4)] def recognize_block(self, block): "““识别第3步:将图像块转成文字(模拟OCR模型)””" import random random.seed(block["y0“]) pool = [“张三 13812345678”, “北京市朝阳区望京街10号”, “上海市浦东新区张江路88号”, “李四 13998765432”] return random.choice(pool) def correct_and_struct(self, text): ”““纠错第4步:正则校验+地址库匹配,输出结构化字段””" phone_match = self.ph_re.search(text) phone = phone_match.group() if phone_match else "" address = text.replace(phone, "").strip() addr_ok = any(k in address for k in self.addr_lib) conf = 0.95 if phone and addr_ok else 0.4 return {"phone": phone, "address": address, "confidence": round(conf, 2)} def run(self, image): binary = self.preprocess(image) blocks = self.detect_text_blocks(binary) out = [] for b in blocks: b["text"] = self.recognize_block(b) out.append(self.correct_and_struct(b["text“])) return out def main(): # 创建16x16的模拟灰度图像 fake_img = [[(r 7 + c 3) % 256 for c in range(16)] for r in range(16)] ocr = WaybillOCR(addr_lib=[“北京市”, “上海市”, “朝阳区”, “浦东新区”]) data = ocr.run(fake_img) for i, item in enumerate(data): print(f“字段{i+1}: {item}”) if name == ”main": main() ```
代码用途:完整演示快递面单OCR的四个核心环节——预处理、文字检测、文字识别、结构化纠错,输出带置信度的结构化字段。