使用腾讯OCR,图片转表格

不是广告哈,就是记录一下操作,因为这些页面真的很难找,即便知道缺什么也找不到对应位置在哪…

调用说明:(以Python为例)

整个流程:

  1. 腾讯开服务
  2. 图片转base64编码
  3. 把base64编码转腾讯OCR
  4. 腾讯OCR返回的json,转Pandas Dict类型
  5. 整理dict的数据为Pandas DataFrame类型

步骤1:腾讯开服务

  1. 进入控制台:https://console.cloud.tencent.com/cam/capi,新建一个密钥:
    在这里插入图片描述

  2. 在控制台开启资源包:https://console.cloud.tencent.com/ocr/overview

步骤2:图片转Base64使用

def change_img_to_base64(image_path):
    """base64编码图片"""
    with open(image_path, 'rb') as f:
        image_data = f.read()
        base64_data: bytes = base64.b64encode(image_data)  # base64编码
        return base64_data

步骤3:把Base64编码转腾讯OCR

def tencent_ocr(suffix, image_based_64):
    """腾讯OCR
    :param suffix:图片的后缀,比如png,jpg
    :param image_based_64:图片的base64编码
    """
    from tencentcloud.common import credential
    from tencentcloud.common.profile.client_profile import ClientProfile
    from tencentcloud.common.profile.http_profile import HttpProfile
    from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
    from tencentcloud.ocr.v20181119 import ocr_client, models
    try:
        cred = credential.Credential("自己的SecretId(看步骤1)", "自己的SecretKey(看步骤1)")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "ocr.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = ocr_client.OcrClient(cred, "ap-beijing", clientProfile)

        req = models.RecognizeTableOCRRequest()
        params = {
            "ImageBase64": "data:image/{suffix};base64,{image_based_64}".format(
                suffix=suffix, image_based_64=image_based_64.decode("utf8"))
        }
        req.from_json_string(json.dumps(params))
        resp = client.RecognizeTableOCR(req)
        return resp.to_json_string()
    except TencentCloudSDKException as err:
        print(err)

步骤4:Json转Dict

def json_to_dict(my_json: str) -> dict:
    """json转dict类型"""
    return json.loads(my_json)

步骤5:Dict数据转Pandas.DataFrame格式:

def formation(json_data):
    """根据腾讯ocr识别结果整理格式并输出"""
    if json_data is not None:
        dict_data = json_to_dict(json_data)
        for table_index, table_data in enumerate(dict_data['TableDetections']):  # 遍历每个表格的数据
            table_data_list = []
            for each_table_data in table_data['Cells']:  # 遍历每个表中的数据
                content: str = each_table_data['Text']
                x_y: list = list(each_table_data['Polygon'][0].values())
                x_y.append(content)
                table_data_list.append(x_y)
            # 整理格式
            table_df = pd.DataFrame(table_data_list)
            table_df.columns = ['x', 'y', 'content']
            table_df.sort_values(by=['y', 'x'], ascending=True, inplace=True)
            for index, line_df in table_df.groupby("y"):  # 按每行进行处理
                line_df.sort_values(by=['x'], ascending=True, inplace=True)
                line_values = line_df['content'].values  # 当前行的数据
                print(",".join(line_values))

步骤6:整体依次调用

if __name__ == '__main__':
    image = "mypic.png"
    image_base64 = change_img_to_base64(image)  # 步骤1:图片转base64
    suffix = image.split('.')[-1]  # 后缀
    tencent_result: json = tencent_ocr(suffix, image_base64)
    formation(tencent_result)

完整代码

import base64
import json
import pandas as pd


def change_img_to_base64(image_path):
    """base64编码图片"""
    with open(image_path, 'rb') as f:
        image_data = f.read()
        base64_data: bytes = base64.b64encode(image_data)  # base64编码
        return base64_data


def json_to_dict(my_json: str) -> dict:
    """json转dict类型"""
    return json.loads(my_json)


def tencent_ocr(suffix, image_based_64):
    """腾讯OCR
    :param suffix:图片的后缀,比如png,jpg
    :param image_based_64:图片的base64编码
    """
    from tencentcloud.common import credential
    from tencentcloud.common.profile.client_profile import ClientProfile
    from tencentcloud.common.profile.http_profile import HttpProfile
    from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
    from tencentcloud.ocr.v20181119 import ocr_client, models
    try:
        cred = credential.Credential("自己的SecretId(看步骤1)", "自己的SecretKey(看步骤1)")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "ocr.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = ocr_client.OcrClient(cred, "ap-beijing", clientProfile)

        req = models.RecognizeTableOCRRequest()
        params = {
            "ImageBase64": "data:image/{suffix};base64,{image_based_64}".format(
                suffix=suffix, image_based_64=image_based_64.decode("utf8"))
        }
        req.from_json_string(json.dumps(params))
        resp = client.RecognizeTableOCR(req)
        return resp.to_json_string()
    except TencentCloudSDKException as err:
        print(err)


def formation(json_data):
    """根据腾讯ocr识别结果整理格式并输出"""
    if json_data is not None:
        dict_data = json_to_dict(json_data)
        for table_index, table_data in enumerate(dict_data['TableDetections']):  # 遍历每个表格的数据
            table_data_list = []
            for each_table_data in table_data['Cells']:  # 遍历每个表中的数据
                content: str = each_table_data['Text']
                x_y: list = list(each_table_data['Polygon'][0].values())
                x_y.append(content)
                table_data_list.append(x_y)
            # 整理格式
            table_df = pd.DataFrame(table_data_list)
            table_df.columns = ['x', 'y', 'content']
            table_df.sort_values(by=['y', 'x'], ascending=True, inplace=True)
            for index, line_df in table_df.groupby("y"):  # 按每行进行处理
                line_df.sort_values(by=['x'], ascending=True, inplace=True)
                line_values = line_df['content'].values  # 当前行的数据
                print(",".join(line_values))


if __name__ == '__main__':
    image = "mypic.png"
    image_base64 = change_img_to_base64(image)  # 步骤1:图片转base64
    suffix = image.split('.')[-1]  # 后缀
    tencent_result: json = tencent_ocr(suffix, image_base64)
    formation(tencent_result)

资料整理

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

好的,使用腾讯OCR进行文字识别需要以下步骤: 1. 注册并登录腾讯云账号,在控制台中开通腾讯OCR服务,获取API密钥。 2. 在代码中引入腾讯OCR SDK,并使用API密钥进行身份验证。 3. 准备要识别的图片,并将其换为Base64格式。 4. 调用腾讯OCRAPI,传入图片数据并设置识别类型(如通用文字识别、身份证识别等)。 5. 解析API返回的识别结果,获取识别出的文字内容。 以下是一个Python示例代码,用于使用腾讯OCR进行通用文字识别: ``` import base64 import json import requests # 设置密钥和API地址 app_id = "your_app_id" app_key = "your_app_key" api_url = "https://recognition.image.myqcloud.com/ocr/general" # 准备图片数据 with open('image.jpg', 'rb') as f: image_data = f.read() image_base64 = str(base64.b64encode(image_data), 'utf-8') # 构造请求参数 params = { "appid": app_id, "image": image_base64, "nonce_str": "random_string", "time_stamp": str(int(time.time())), } # 生成签名 sign_str = "&".join([f"{key}={params[key]}" for key in sorted(params.keys())]) sign_str += f"&appkey={app_key}" sign = hashlib.md5(sign_str.encode('utf-8')).hexdigest().upper() # 发送POST请求 headers = {'Content-Type': 'application/json'} data = { "appid": app_id, "image": image_base64, "nonce_str": "random_string", "time_stamp": str(int(time.time())), "sign": sign, } response = requests.post(api_url, headers=headers, data=json.dumps(data)) # 解析结果 result = json.loads(response.text) if result.get("code") == 0: words_list = result.get("data").get("item_list") for words in words_list: print(words.get("itemstring")) else: print(result.get("message")) ``` 需要注意的是,使用腾讯OCR服务需要收取一定的费用,具体费用标准可以在腾讯云控制台中查看。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆萌的代Ma

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值