cv2.imdecode() 函数从指定的内存缓存中读取数据,并把数据转换(解码)成图像格式;主要用于从网络传输数据中恢复出图像.
cv2.imencode() 函数是将图片格式转换(编码)成流数据,赋值到内存缓存中;主要用于图像数据格式的压缩,方便网络传输.

1. cv2.imdecode()

读取网络url图像数据,并转换成图片格式:

#!/usr/bin/python3
#!--*-- coding: utf-8 --*--
import numpy as np
import cv2
import requests

url = 'https://www.aiuai.cn/uploads/2202/beeb259c1c4056ce.jpeg'
resp = requests.get(url, timeout=3)
image = np.asarray(bytearray(resp.content), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
cv2.imshow('url_image',image)
cv2.waitKey()

2. cv2.imencode()

将图片进行编码,并保存到本地:

#!/usr/bin/python3
#!--*-- coding: utf-8 --*--
import numpy as np
import cv2

img = cv2.imread('test.jpg')
img_encode = cv2.imencode('.jpg', img)[1] #.jpg 编码格式
# img_encode = cv2.imencode('.png', img) #.png 编码格式

img_array = np.array(img_encode)
img_str = img_array.tostring()

# 缓存数据保存到本地
with open('img_encode.txt', 'w') as f:
    f.write(img_str)
    f.flush

3. cv2.imencode() + cv2.imdecode()

图片编码保存到本地,读取本地文件解码恢复成图片格式:

#!/usr/bin/python3
#!--*-- coding: utf-8 --*--
import numpy as np
import cv2

#imencode
img = cv2.imread('test.jpg')
img_encode = cv2.imencode('.jpg', img)[1] #.jpg 编码格式
# img_encode = cv2.imencode('.png', img) #.png 编码格式

img_array = np.array(img_encode)
img_str = img_array.tostring()

# 缓存数据保存到本地
with open('img_encode.txt', 'w') as f:
    f.write(img_str)
    f.flush

#imdecode
with open('img_encode.txt', 'r') as f:
    img_str = f.read()

img_array = np.fromstring(img_str, np.uint8)
#img_array = np.asarray(bytearray(img_str), dtype="uint8")
img_decode = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
cv2.imshow("img_decode", img_decode)
cv2.waitKey()

4. 性能提升

OpenCV 是基于libjpeg 库进行图片编解码,imdecode 速度可能会慢.

这里采用 turbojpeg 库进行速度提升.

4.1. cv2.imdecode()

#cv2.imdecode
img_cv2 = base64.b64decode(data)
img_array = np.frombuffer(img_cv2, np.uint8)
img_decode = cv2.imdecode(img_array, cv2.IMREAD_COLOR)

#turbojpeg
from turbojpeg import TurboJPEG,TJPF_GRAY,TJSAMP_GRAY,TJFLAG_PROGRESSIVE,TJPF_BGR
turboJpeg_lib_path = '/path/to/libTurboJpeg.so'
jpeg = TurboJPEG(turboJpeg_lib_path)

img = base64.b64decode(data)
img_decode = jpeg.decode(img, pixel_format=TJPF_BGR)

4.2. cv2.imwrite()

#cv2.imwrite
cv2.imwrite('img.jpg',img)

#turbojpeg
from turbojpeg import TurboJPEG,TJPF_GRAY,TJSAMP_GRAY,TJFLAG_PROGRESSIVE,TJPF_BGR
turboJpeg_lib_path = '/path/to/libTurboJpeg.so'
jpeg = TurboJPEG(turboJpeg_lib_path)

#
with open('img.jpg', 'wb') as fp:
    fp.write( jpeg.encode(image,quality=100))

材料

[1] - OpenCV-Python cv2.imdecode()和cv2.imencode() 图片解码和编码 - 2018.01.25

[2] - 关于opencv imdecode速度慢的问题 - 2021.09.18

Last modification:February 22nd, 2022 at 11:08 am