前言
jpeg4py是Python cffi (C Foreign Function Interface) libjpeg-turbo 绑定和辅助类工具包,是为 libjpeg-turbo 提供线程安全和感知GIL的Python绑定,基于Python 2/3 和 numpy 运行。
目前只能解码 jpeg 文件,在单线程中比 Image.open().tobytes() 和 scipy.misc.imread() 快约 1.3 倍,在多线程模式下快 9 倍.
本文简要介绍基于libjpeg-turbo库的jpeg4py安装与使用。
安装
以Ubuntu为例进行说明:
root用户安装
sudo apt-get install libturbojpeg
pip install jpeg4py
普通用户安装
tar -xf libjpeg-turbo-2.1.2.tar.gz
cd libjpeg-turbo-2.1.2/
mkdir build
cd build
cmake -G"Unix Makefiles" -DCMAKE_INSTALL_PREFIX:PATH=/InstallPath/libjpeg-turbo-2.1.2/lib64 ..
make -j16
make install
如遇cmake报错如下:
cmake -G"Unix Makefiles" -DCMAKE_INSTALL_PREFIX:PATH=/InstallPath/libjpeg-turbo-2.1.2/lib64 ..
Command 'cmake' not found, but can be installed with:
snap install cmake # version 3.23.3, or
apt install cmake
See 'snap info cmake' for additional versions.
则安装cmake:
pip install cmake
将相关路径添加进环境变量:
vi ~/.bashrc
在末尾添加:
# libjpeg-turbo
export PATH=$PATH:/InstallPath/libjpeg-turbo-2.1.2/lib64/bin/
# (动态库搜索路径) 程序运行期间查找动态链接库时指定查找共享库的路径
export LD_LIBRARY_PATH=/InstallPath/libjpeg-turbo-2.1.2/lib64/lib/:$LD_LIBRARY_PATH
# (静态库搜索路径) 程序编译期间查找动态链接库时指定查找共享库的路径
export LIBRARY_PATH=/InstallPath/libjpeg-turbo-2.1.2/lib64/lib/:$LIBRARY_PATH
# c程序头文件搜索路径
export C_INCLUDE_PATH=/InstallPath/libjpeg-turbo-2.1.2/lib64/include/:$C_INCLUDE_PATH
source ~/.bashrc
pip install jpeg4py
使用
Python 3.7.10 | packaged by conda-forge | (default, Feb 19 2021, 16:07:37)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import jpeg4py
>>> path = 'test.jpg'
>>> jpeg4py.JPEG(path).decode()
其他说明
如果libturbojpeg没有安装成功,则在调用jpeg4py方法时会报错:
Traceback (most recent call last):
File "", line 1, in
File "/data/conda/envs/test/lib/python3.7/site-packages/jpeg4py/_py.py"
, line 128, in __init__
super(JPEG, self).__init__(lib_)
File "/data/conda/envs/test/lib/python3.7/site-packages/jpeg4py/_py.py"
, line 64, in __init__
jpeg.initialize()
File "/data/conda/envs/test/lib/python3.7/site-packages/jpeg4py/_cffi.p
y", line 212, in initialize
_initialize(backends)
File "/data/conda/envs/test/lib/python3.7/site-packages/jpeg4py/_cffi.p
y", line 193, in _initialize
raise OSError("Could not load libjpeg-turbo library")
版权说明
本文为原创文章,独家发布在blog.youkuaiyun.com/TracelessLe。未经个人允许不得转载。如需帮助请email至tracelessle@163.com或扫描个人介绍栏二维码咨询。
参考资料
[1] ajkxyz/jpeg4py: Python cffi libjpeg-turbo bindings and helper classes
[2] libjpeg-turbo/libjpeg-turbo: Main libjpeg-turbo repository
[3] 源码安装libjpeg-turbo1.2.1,无root权限_xiamentingtao的博客-优快云博客