图片魔力转圈圈----【python】图像格式转化-ndarry base64 二进制

import base64,io
import numpy as np
from PIL import Image
import cv2 as cv

def base642bytes(base64_img):
    return base64.b64decode(base64_img)

def bytes2base64(byte_img):
    return base64.b64encode(byte_img)

def file2base64(url):

    with open(url,"rb") as f:
        return bytes2base64(f.read())

def numpy2ByteIO(image_data):
    imgRGB = cv.cvtColor(image_data, cv.IMREAD_COLOR)
    r, buf = cv.imencode(".jpg", imgRGB)
    bytes_image = Image.fromarray(np.uint8(buf)).tobytes()
    # array转换成二进制
    return io.BytesIO(bytes_image)

def numpy2base64(image_data):

    imgRGB = cv.cvtColor(image_data, cv.IMREAD_COLOR)
    r, buf = cv.imencode(".jpg", imgRGB)
    bytes_image = Image.fromarray(np.uint8(buf)).tobytes()
    # array转换成二进制
    return bytes2base64(bytes_image)


def base642numpy(byte_image):
    img = base642bytes(byte_image)
    nparr = np.fromstring(img, np.uint8)
    return cv.imdecode(nparr, cv.IMREAD_COLOR)


# 图片格式转化 qimage -> ndarry
def qimage2cvimg(qimage):
    size = qimage.size()
    s = qimage.bits().asstring(size.width() * size.height() * qimage.depth() // 8) 
    arr = np.fromstring(s, dtype=np.uint8).reshape((size.height(), size.width(), qimage.depth() // 8))
    return arr


# 图片格式转化 pixmap -> ndarry
def pixmap_to_cvimg(pix):
    return qimage_to_cvimg(pix.toImage())


# ndarry4通道转3通道->ndarray
def channel4_3(image):
    if image.shape[-1] == 4:
        image = image[:, :, :-1]
    return image



# ndarray2通道转3通道->ndarray
def channel2_3(image)
    t = image.shape
    if len(t) == 2:
        return np.repeat(image[...,np.newaxis],3,2)
       


# 读图片(支持中文路径)->ndarray
def myImread(path):
    return cv.imdecode(np.fromfile(path, dtype=np.uint8), -1)


# 写图片(支持中文路径)->ndarray
def imwrite(path,image):
    cv.imencode('.jpg', image)[1].tofile(path)

 

你可能感兴趣的:(图片魔力转圈圈----【python】图像格式转化-ndarry base64 二进制)