win10 环境下Python 3.8按装fastapi paddlepaddle 进行图片文字识别1

###按装

用conda 创建python 3.8的环境,可参看本人python下的其它文章。

在pycharm开发环境下按装相关的模块:

csharp 复制代码
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple fastapi
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple  "uvicorn[standard]"
pip install paddlepaddle -i https://mirror.baidu.com/pypi/simple
pip install "paddleocr>=2.0.1" -i https://mirror.baidu.com/pypi/simple
pip install  shapely -i https://mirror.baidu.com/pypi/simple

###开发代码:

python 复制代码
# 导入requests库,用于发送HTTP请求
import requests
# 导入FastAPI库,用于构建高性能的Web应用程序
from fastapi import FastAPI
# 导入PaddleOCR及其draw_ocr方法,PaddleOCR是一个使用PaddlePaddle深度学习框架的OCR工具
from paddleocr import PaddleOCR, draw_ocr
# 导入BytesIO,用于在内存中处理二进制流
from io import BytesIO
# 导入PIL库中的Image模块,用于处理图像
from PIL import Image
import os

# 初始化PaddleOCR实例,配置使用方向分类器、不使用GPU、识别中文
ocr = PaddleOCR(use_angle_cls=True, use_gpu=False, lang="ch")
# 创建一个FastAPI应用实例
app = FastAPI()


# 定义一个异步的GET请求处理函数,路径为"/",接收一个名为url的查询参数
@app.get("/")
async def root(url: str):
    try:
        # 使用requests库发送GET请求,获取指定URL的图片,stream=True表示以流的形式下载大文件
        response = requests.get(url, stream=True)
        # 如果HTTP请求返回的状态码不是200,则引发HTTPError异常
        response.raise_for_status()
        # 检查响应头中的content-type是否包含'image',以确认返回的内容是图片
        if 'image' not in response.headers.get('content-type', ''):
            # 如果不是图片,返回错误信息,HTTP状态码为400(Bad Request)
            return {"error": "The provided URL does not point to an image."}, 400
            # 使用BytesIO将响应内容转换为二进制流
        image_bytes = BytesIO(response.content)
        # 使用PIL库打开二进制流中的图像
        image = Image.open(image_bytes)

        # 将图像保存到临时文件中(这里是为了适应PaddleOCR可能需要文件路径的API)
        # 注意:这里的代码实际上有一个逻辑错误,因为image.save()应该放在with语句块内以确保文件正确关闭
        temp_image_path = "temp_image.jpg"
        with open(temp_image_path, "wb") as image_file:
            image.save(image_file, format='JPEG')
            # 调用PaddleOCR的ocr方法进行OCR处理,cls=True表示使用分类器
        result = ocr.ocr(temp_image_path, cls=True)
        if os.path.exists(temp_image_path):
            os.remove(temp_image_path)
        results = []
        # 遍历最外层的列表
        for item in result:
            # 遍历内层的列表
            for sub_item in item:
                # 提取文本和可能性
                text = sub_item[1][0]  # 文本位于第二个子列表的第一个位置
                probability = sub_item[1][1]  # 可能性位于第二个子列表的第二个位置
                # 将提取的文本和可能性作为一个元组添加到结果列表中
                results.append((text, probability))
        # 返回OCR处理结果,封装在message字段中(注意:这里没有删除临时文件,可能会导致磁盘空间被占用)
        return {"message": results}
    except requests.exceptions.RequestException as e:
        # 如果在发送HTTP请求过程中发生异常,捕获异常并返回错误信息,HTTP状态码为500(Internal Server Error)
        return {"error": f"An error occurred while downloading the image: {str(e)}"}, 500
    except Exception as e:
        # 如果在处理过程中发生其他类型的异常,同样捕获异常并返回错误信息,HTTP状态码为500
        return {"error": f"An error occurred during OCR processing: {str(e)}"}, 500

在网上找一张图片:

https://img-s-msn-com.akamaized.net/tenant/amp/entityid/BB1ifoqa.img?w=768\&h=662\&m=6

运行代码:

python 复制代码
uvicorn main:app --reload

返回结果:

python 复制代码
{
    "message": [
        [
            "狗仔说张天爱手撕徐开骋得罪了人,资源掉了不",
            0.9765021800994873
        ],
        [
            "少,最近一直没有新男友,是不是又怕被录音啊?",
            0.9926691055297852
        ],
        [
            "C薰衣草Sallie的微博视频",
            0.9560778737068176
        ],
        [
            "飞哥追瓜速报",
            0.9982643723487854
        ],
        [
            "快手搜索追瓜少年阿",
            0.8913857936859131
        ]
    ]
}
相关推荐
随心点儿17 分钟前
使用python 将多个docx文件合并为一个word
开发语言·python·多个word合并为一个
不学无术の码农21 分钟前
《Effective Python》第十三章 测试与调试——使用 Mock 测试具有复杂依赖的代码
开发语言·python
sleepybear111327 分钟前
在Ubuntu上从零开始编译并运行Home Assistant源码并集成HACS与小米开源的Ha Xiaomi Home
python·智能家居·小米·home assistant·米家·ha xiaomi home
纪伊路上盛名在33 分钟前
(鱼书)深度学习入门1:python入门
人工智能·python·深度学习
夏末蝉未鸣011 小时前
python transformers笔记(TrainingArguments类)
python·自然语言处理·transformer
德育处主任Pro1 小时前
「py数据分析」04如何将 Python 爬取的数据保存为 CSV 文件
数据库·python·数据分析
咸鱼鲸1 小时前
【PyTorch】PyTorch中数据准备工作(AI生成)
人工智能·pytorch·python
遇见你很高兴1 小时前
Pycharm中体验通义灵码来AI辅助编程
python
大虫小呓1 小时前
50个Python处理Excel示例代码,覆盖95%日常使用场景-全网最全
python·excel
大模型真好玩2 小时前
做题王者,实战拉跨!是时候给马斯克的Grok4泼盆冷水了!(Grok 4模型详细测评报告)
人工智能·python·mcp