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

推荐订阅源

博客园 - 三生石上(FineUI控件)
U
Unit 42
人人都是产品经理
人人都是产品经理
罗磊的独立博客
Recent Announcements
Recent Announcements
云风的 BLOG
云风的 BLOG
aimingoo的专栏
aimingoo的专栏
T
Tailwind CSS Blog
GbyAI
GbyAI
Blog — PlanetScale
Blog — PlanetScale
I
InfoQ
Last Week in AI
Last Week in AI
宝玉的分享
宝玉的分享
B
Blog RSS Feed
WordPress大学
WordPress大学
腾讯CDC
H
Help Net Security
博客园 - Franky
博客园 - 【当耐特】
博客园 - 聂微东
Stack Overflow Blog
Stack Overflow Blog
B
Blog
Vercel News
Vercel News
博客园 - 司徒正美

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#