图像转换为二进制

图像转换为二进制主要是方便数据传输,比如在web开发中,将数据从客户端传到服务端需要将客户端的数据转换为Byte类型,然后在服务端接收到数据后再将Byte类型的数据转换为图像.

RGB图像转换为二进制方式有两种 1. 通过url读取图像并且转换为二进制字节流

from urllib import request
image = request.urlopen('https://pic.cnblogs.com/avatar/875028/20160405220401.png').read()
  1. 读入本地图像然后转换为二进制字节流
import cv2
with open('/media/work/data/temp.jpg', 'rb') as data:
    image = data.read()

二进制图像转换为RGB图像方式有两种

  1. 通过PIL 读取二进制字节流
from PIL import Image
import io
import numpy as np
# covert byte to RGB image
img = Image.open(io.BytesIO(image))
# Image 转numpy
img_np = np.array(img)
  1. 通过cv2读取二进制字节流
import cv2
import numpy as np
from PIL import Image
# img BGR
img = cv2.imdecode(np.frombuffer(image, np.uint8), cv2.IMREAD_COLOR)
# covert BRG to RGB
img_np = cv2.cvtColor(img. cv2.COLOR_RGB2BGR)
#numpy 转Image
img = Image.fromarray(img_np)

string 与 byte 之间转换

# bytes 
b = b"something"
# str 
s = "something"
# str to bytes two method
b = bytes(s, encoding = "utf8")
b = str.encode(s)
# bytes to str two method
s = str(b, encoding = "utf-8")
s = bytes.decode(b)