版权声明:本文为博主原创文章,欢迎转载,请注明出处 https://blog.csdn.net/mouday/article/details/85074600
思路是这样的:
pdf -> image -> 识别其中的图表 -> 通过PIL截取图片
整个过程尝试了很多方式,最终效果不是很完美,还需要继续探索
包括以下开源库
Tabula
前端截图提取表格数据,效果还可以,使用简单
使用步骤:
- 下载 https://tabula.technology/
- 启动 Tabula
- 打开 http://localhost:8080
如果是安装python的第三方模块,使用命令:
pip install tabula-py
ImageMagick
可以进行图片格式转换,pdf转图片
mac
brew install ImageMagick
Linux
yum install ImageMagick
或者:
官网下载对应平台的压缩包:https://www.imagemagick.org/script/download.php
安装ghostscript:brew install ghostscript
配置ImageMagick环境变量vim ~/.bash_profile
export MAGICK_HOME=/Users/qmp/Applications/ImageMagick-7.0.8
export PATH="$MAGICK_HOME/bin:$PATH"
export DYLD_LIBRARY_PATH="$MAGICK_HOME/lib/"
source ~/.bash_profile
命令行测试
convert -version
convert a.jpg a.png
convert -limit thread 1 names.pdf -background white -alpha remove -colorspace RGB -colorspace sRGB out.jpg
提高图片质量
$ convert -density 300 -quality 100 test.pdf 1.png
参数解析:
-density 300
图像每英寸面积内的像素点数,数值越高图片质量越高
-quality 100
这个为转换png时的压缩率,100表示不压缩
参数设置:
https://www.imagemagick.org/www/script/convert.php
python库wand
支持ImageMagick接口,只支持6版本,而ImageMagick最新为7版本,Mac上尝试安装不成功
http://docs.wand-py.org/
网络资源
pdf转图片:
http://app.xunjiepdf.com/pdf2jpg
http://pdftoword.55.la/pdf-to-jpg/
百度ai通用图像分析:
https://ai.baidu.com/tech/imagerecognition/general
完整过程
- 先使用ImageMagick将pdf文件转为png图片格式
import os
pdfname = "names.pdf"
os.makedirs("out", exist_ok=True)
cmd = (
"source ~/.bash_profile; "
"convert "
"-limit thread 1 {} "
"-background white "
"-alpha remove "
"-colorspace RGB "
"-colorspace sRGB "
"out/out.jpg"
).format(pdfname)
result = os.popen(cmd)
print(result.read())
- 通过百度AI接口将图片中的主物体识别出来,获取坐标
from aip import AipImageClassify
""" 你的 APPID AK SK """
APP_ID = '你的 App ID'
API_KEY = '你的 Api Key'
SECRET_KEY = '你的 Secret Key'
filename = "name.png"
client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)
with open(filename, "rb") as f:
image = f.read()
result = client.objectDetect(image)
print(result)
data = result.get("result")
- 通过百度识别出来的坐标,使用PIL将需要的图片截取出来
width = data.get("width")
height = data.get("height")
top = data.get("top")
left = data.get("left")
from PIL import Image
im = Image.open(filename)
box = (left, top, left + width, top + height)
region = im.crop(box)
region.save("cutting.jpg")
参考: