如何精简OpenCV中为图像每个字母绘制矩形框的代码?
精简字母矩形框绘制代码
可以通过合并中间变量、优化坐标转换逻辑来精简代码,同时修正原代码中可能存在的坐标计算错误(Tesseract的y轴原点在图像底部,所以右下角y坐标应为himg - h而非himg + h):
精简后完整代码
import cv2 import pytesseract pytesseract.pytesseract.tesseract_cmd = "D:\\Tesseract\\tesseract.exe" img = cv2.imread('1.png') h_img, _, _ = img.shape # 直接遍历OCR结果,跳过字符值,处理坐标并绘制矩形 for _, x, y, w, h in [line.split() for line in pytesseract.image_to_boxes(img).splitlines()]: x, y, w, h = map(int, (x, y, w, h)) cv2.rectangle(img, (x, h_img - y), (w, h_img - h), (0, 255, 0), 1) # 可选:显示处理后的图像 cv2.imshow('Boxed Characters', img) cv2.waitKey(0) cv2.destroyAllWindows()
精简要点说明
- 移除中间变量:直接在循环中处理
pytesseract.image_to_boxes返回的每行数据,无需提前存储拆分后的列表k,减少内存占用 - 简化类型转换:用
map(int, ...)批量将字符串坐标转为整数,比嵌套列表推导式更简洁高效 - 优化变量命名:将
i改为img、himg改为h_img提升代码可读性 - 修正坐标逻辑:原代码中
himg + h会导致矩形超出图像范围,改为h_img - h符合Tesseract的坐标规则 - 可选增强:添加矩形颜色和线宽参数,让识别框更清晰可见
内容的提问来源于stack exchange,提问作者The SP Show
相关产品推荐
相关产品推荐

