惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
GbyAI
GbyAI
G
Google Developers Blog
Engineering at Meta
Engineering at Meta
月光博客
月光博客
腾讯CDC
Recent Announcements
Recent Announcements
酷 壳 – CoolShell
酷 壳 – CoolShell
爱范儿
爱范儿
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
SegmentFault 最新的问题
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
阮一峰的网络日志
阮一峰的网络日志
博客园 - 【当耐特】
The GitHub Blog
The GitHub Blog
Last Week in AI
Last Week in AI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
Y
Y Combinator Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Martin Fowler
Martin Fowler
A
About on SuperTechFans
博客园 - 叶小钗

jdhao's digital space

腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN Mintty Tips and Configurations
Conversion between base64 and OpenCV or PIL Image
2020-03-17 · via jdhao's digital space

When we are building web services using Python, we often send or receive images in base64 encoded format. However, when we are doing image processing tasks, we need to use PIL or OpenCV. In this post, I will share how to convert between OpenCV or PIL image and base64 encoded image.

base64 to PIL Image#

import base64
from io import BytesIO
from PIL import Image

with open("test.jpg", "rb") as f:
    im_b64 = base64.b64encode(f.read())

im_bytes = base64.b64decode(im_b64)   # im_bytes is a binary image
im_file = BytesIO(im_bytes)  # convert image to file-like object
img = Image.open(im_file)   # img is now PIL Image object

In the above code, since Image.open() only accepts image path or file-like object, we first convert the base64 encoded image to BytesIO object and then read the image using PIL.

base64 to OpenCV Image#

import base64
import numpy as np
import cv2

with open("test.jpg", "rb") as f:
    im_b64 = base64.b64encode(f.read())

im_bytes = base64.b64decode(im_b64)
im_arr = np.frombuffer(im_bytes, dtype=np.uint8)  # im_arr is one-dim Numpy array
img = cv2.imdecode(im_arr, flags=cv2.IMREAD_COLOR)

In the above code, we first convert binary image to Numpy array, then decode the array with cv2.imdecode(). The final img is an OpenCV image in Numpy ndarray format.

PIL or OpenCV image to base64#

PIL Image to base64#

import base64
from io import BytesIO
from PIL import Image

img = Image.open('test.jpg')
im_file = BytesIO()
img.save(im_file, format="JPEG")
im_bytes = im_file.getvalue()  # im_bytes: image in binary format.
im_b64 = base64.b64encode(im_bytes)

In the above code, instead of saving the PIL Image object img to the disk, we save it to im_file which is a file-like object. Note that in this case, we need to specify the image format in img.save().

OpenCV to base64 image#

import base64
import numpy as np
import cv2

img = cv2.imread('test.jpg')
_, im_arr = cv2.imencode('.jpg', img)  # im_arr: image in Numpy one-dim array format.
im_bytes = im_arr.tobytes()
im_b64 = base64.b64encode(im_bytes)

In the above code, we first save the image in Numpy ndarray format to im_arr which is a one-dim Numpy array. We then get the image in binary format by using the tobytes() method of this array.

References#