2025-08-19利用opencv检测图片中文字及图片的坐标

同时还 计算出坐标及字体大小

bash 复制代码
from cnocr import CnOcr
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont

# 初始化 cnocr
ocr = CnOcr()


def put_chinese_text(image, text, position, font_size=20, color=(0, 255, 0)):
    """
    在图像上绘制中文文本
    """
    # 将OpenCV的BGR图像转换为RGB图像
    image_pil = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

    # 设置字体,需要系统中有支持中文的字体
    try:
        # Windows系统常用字体
        font = ImageFont.truetype("simhei.ttf", font_size)
    except:
        try:
            # 尝试其他常见中文字体
            font = ImageFont.truetype("arial.ttf", font_size)
        except:
            # 如果找不到特定字体,使用默认字体
            font = ImageFont.load_default()

    # 创建绘图对象
    draw = ImageDraw.Draw(image_pil)

    # 绘制文本
    draw.text(position, text, font=font, fill=color)

    # 转换回OpenCV格式
    image_cv = cv2.cvtColor(np.asarray(image_pil), cv2.COLOR_RGB2BGR)

    return image_cv


def detect_text_positions(image_path):
    """检测图片中的文字位置"""
    # 加载图片
    image = cv2.imread(image_path)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 使用 cnocr 检测文字
    results = ocr.ocr(gray)  # 使用 ocr.ocr 而不是 ocr.ocr_for_single_line

    # 保存文字框
    text_positions = []
    for result in results:
        text = result['text']
        bbox = result['position']
        x_min, y_min = bbox[0]
        x_max, y_max = bbox[2]
        x, y, w, h = int(x_min), int(y_min), int(x_max - x_min), int(y_max - y_min)

        # 计算文字的像素宽度和高度
        pixel_width = w
        pixel_height = h

        text_positions.append({
            "text": text,
            "bbox": (x, y, w, h),
            "pixel_width": pixel_width,
            "pixel_height": pixel_height
        })

        # 在图片上绘制文字框
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # 使用支持中文的函数绘制文本
        image = put_chinese_text(image, text, (x, y - 20), font_size=15, color=(0, 255, 0))

    return image, text_positions


def main(image_path):
    """主函数:检测文字位置"""
    # 检测文字
    text_image, text_positions = detect_text_positions(image_path)

    # 显示结果
    cv2.imshow("Detected Text", text_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # 打印文字位置及尺寸信息
    print("文字位置:")
    for text_pos in text_positions:
        print(f"文本: {text_pos['text']}, 坐标: {text_pos['bbox']}, "
              f"像素宽度: {text_pos['pixel_width']}, 像素高度: {text_pos['pixel_height']}")

    return {"text_positions": text_positions}


if __name__ == "__main__":
    image_path = "6.png"  # 替换为你的图片路径
    results = main(image_path)
相关推荐
大龄程序员狗哥3 小时前
第47篇:使用Speech-to-Text API快速构建语音应用(操作教程)
人工智能
KKKlucifer3 小时前
数据安全合规自动化:策略落地、审计追溯与风险闭环技术解析
人工智能·安全
RWKV元始智能3 小时前
RWKV超并发项目教程,RWKV-LM训练提速40%
人工智能·rnn·深度学习·自然语言处理·开源
dyj0953 小时前
Dify - (一)、本地部署Dify+聊天助手/Agent
人工智能·docker·容器
墨染天姬3 小时前
【AI】Hermes的GEPA算法
人工智能·算法
小超同学你好3 小时前
OpenClaw 深度解析系列 · 第8篇:Learning & Adaptation(学习与自适应)
人工智能·语言模型·chatgpt
紫微AI3 小时前
前端文本测量成了卡死一切创新的最后瓶颈,pretext实现突破了
前端·人工智能·typescript
码途漫谈4 小时前
Easy-Vibe开发篇阅读笔记(四)——前端开发之结合 Agent Skills 美化界面
人工智能·笔记·ai·开源·ai编程
易连EDI—EasyLink4 小时前
易连EDI–EasyLink实现OCR智能数据采集
网络·人工智能·安全·汽车·ocr·edi
冬奇Lab4 小时前
RAG 系列(二):用 LangChain 搭建你的第一个 RAG Pipeline
人工智能·langchain·llm