最近在做一个项目,需要将base64转成图片rgb格式。
一般的做法是将base64字符串先解码写入文件,然后再去cv2.imread读取图片。这样就绕弯了,如果能够从base64直接转为imread得到的rbg矩阵,就会节省时间开销,具体做法比较简单:
def base64_to_image(base64_code):
"""将base64的数据转换成rgb格式的图像矩阵"""
img_data = base64.b64decode(base64_code)
img_array = np.fromstring(img_data, np.uint8)
img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
return img
传入的base64字符串,得到的是rgb格式的数据。
那反过来该怎么做呢?
从rgb格式的图像矩阵到base64字符串,需要进行下面转换:
def image_to_base64(img):
image = cv2.imencode('.jpg',img)[1]
image_code = str(base64.b64encode(image))
return image_code
介绍完毕!