一、图片识别功能
from fastapi import FastAPI, UploadFile
from typing import List, Dict, Any
from PIL import Image
from pydantic import BaseModel
from cnocr import CnOcr
from copy import deepcopy
import uvicorn
import requests
from io import BytesIO
import utils
app = FastAPI()
class OcrResponse(BaseModel):
status_code: int = 200
results: List[Dict[str, Any]]
def dict(self, **kwargs):
the_dict = deepcopy(super().dict())
return the_dict
@app.post("/ocr")
async def ocr(url: str) -> Dict[str, Any]:
response = requests.get(url)
# 确保请求成功
if response.status_code == 200:
# 将图片内容转换为文件对象
image_file = BytesIO(response.content)
# 使用PIL打开图片
image = Image.open(image_file)
cn_ocr = CnOcr()
res = cn_ocr.ocr(image)
my_list = []
for item in res:
print(item['text'])
my_list.append(item['text'])
# result = {"code": 0, "data": my_list}
return utils.success(my_list)
else:
print('无法下载图片')
return utils.error(205, "无法下载图片")
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0')
二、检测图片是否被PS过
from PIL import Image
from PIL.ExifTags import TAGS
# 分析元数据
def get_exif_data(image_path):
image = Image.open(image_path)
exif_data = image._getexif()
if exif_data is not None:
for tag, value in exif_data.items():
tag_name = TAGS.get(tag, tag)
print(f"{tag_name}: {value}")
# image_path = "d:/1/a.jpeg" # 未PS过
image_path = "d:/1/b.png" # PS过
# image_path = "d:/1/c.jpg" # PS过
# image_path = "d:/1/d.jpg" # 未PS过
# image_path = "d:/1/e.jpg" # 未PS过
# image_path = "d:/1/f.png" # 未PS过
# image_path = "d:/1/i.jpg" # 微信原图 有元数据
# image_path = "d:/1/j.jpg" # 飞书原图 有元数据
# image_path = "d:/1/k.jpg" # 微信原图 有元数据
get_exif_data(image_path)
专注JAVA系统优化、系统结构调整、系统问题排查医治、系统升级、架构设计、SQL语句优化、小程序、APP、企业应用软件开发,请 + hekf888,欢迎关注,时常发布技术分享博文