opencv,matplotlib,PIL,base64数据转换

发布时间 2023-11-10 14:16:07作者: 贝壳里的星海

opencv,matplotlib,PIL,base64数据转换

opencv

格式     numpy			np.ndarray
读取     cv2.imread
保存     cv2.imwrite
显示     cv2.imshow

读取保存和显示

import cv2
def read_img_cv(path):
	img_cv=cv2.imread(path)
	return img_cv


import cv2
def save_img_cv(img_cv,path):
	cv2.imwrite(path, img_cv)  # 保存图片

img=None
if isinstance(img, np.ndarray)
	save_img_cv(img,path='/data/demo.jpg')
import cv2
def show_img_cv(img_cv):
	cv2.imshow("Image", img_cv)
	cv2.waitKey(0)  # 暂停显示图片,数字0代表按键后 0 ms执行

Matplotlib

读取  img=mpimg.imread(path)
显示  plt.imshow(img) plt.show()
保存  plt.imsave(name,img)
import matplotlib.image as mpimg
def read_img_mat(path):
	img_mat=mpimg.imread(path)
	return img_mat

def save_img_pil(img_pil,name):
	plt.imsave(name,img_pil)
def show_img_pil(img_pil):
	plt.imshow(img_pil)
	plt.axis('off')
	plt.show()
    
def show_img_gray(img_gray):
	plt.imshow(img_gray,cmap='gray')
	plt.axis('off')
	plt.show()

PIL

类型   PIL.Image()       Image.Image()
读取   Image.open()
保存   img_pil.save(path)
显示   img_pil.show()
import PIL
from PIL import Image
def read_img_pil(path):
	img_pil=Image.open(path) # PIL Image 类型
	return img_pil


def save_img_pil(img_pil,path):
	img_pil.save(path)

def show_img_pil(img_pil):
	img_pil.show()

from PIL import Image  
  
def is_pil_image(image):  
    return isinstance(image, Image.Image)  
Opencv     的数据类型是Numpy数组,通道顺序为BGR
Matplotlib 的数据类型是Numpy数组, 通道顺序是RGB
PIL        的数据类型是PIL.Image类,通道顺序是RGB

相互转换

opencv和Matplotlib

# cv->mat
def cv2mat(img_cv):
	img_mat=cv2.cvtColor(img_cv,cv2.COLOR_BGR2RGB) # 将颜色通道从BGR改变成RGB
	# 另一种等价写法
	# img_mat=img_cv[:,:,::-1]
	return img_mat

def mat2cv(img_mat): # 将颜色通道从RGB改变成BGR
	img_cv=img_mat[:,:,::-1]
	return img_cv

Matplotlib和PIL

# mat->PIL
#方法1:三通道的转换
def mat2PIL_RGB(img_mat):
	img_pil=Image.fromarray(img_mat.astype('uint8'))
	# unit8 是无符号的8位整形,用astype [0,255]截断处理
	# 另外一种写法
	# img_pil= Image.fromarray(np.unit8(img_mat))
	return img_pil 

# 方法2: 四通道的转换
def mat2PIL_RGBA(img_mat):
	img_pil=Image.fromarray(img_mat.astype('uint8')).convert('RGB')
	return img_pil

# 方法三:使用torchvision的库函数
from torchvision import transforms
def mat2PIL_trans(img_mat):
	trans=transformers.ToPILImage()
	img_pil=trans(img_mat)
	return img_pil
	
'''PIL->mat'''

def PIL2mat(img_pil):
	img_mat=np.array(img_pil) # 深拷贝
	# 如果是jpg格式,通道顺序是RGB, (H,W,3)
	# 如果是png格式,通道顺序是RGBA, (H,W,4)
	# 返回的类型均是`numpy.ndarray`, `dtype=unit8`, 取值返回[0,255]
	# 或者也可以采用浅拷贝
	# img_mat=np.asarray(img_pil)
	return img_mat

'''区间变换'''
# [0,255]->[0,1] 
def PIL2mat_norm(img_pil):
	img_mat=np.asarray(img_pil)/255.0
	return img_mat
# [0,1]->[0,255]
def mat_255(img_mat):
	img_mat=(np.maximum(img_mat, 0) / img_mat.max()) * 255.0 
	img_mat=np.unit8(img_mat)

opencv和PIL

# cv->PIL
def cv2pil(img):
    img=cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = Image.fromarray(img)
    return  img

#方法1:三通道的转换
def cv2PIL_RGB(img_cv):
	img_rgb = img_cv[:,:,::-1] # OpenCV 的通道顺序为 BGR, 转换成RGB
	# nparray 
	img_pil= Image.fromarray(np.uint8(img_rgb))
	return img_pil 

# 方法2: 四通道的转换
def cv2PIL_RGBA(img_cv):
	img_rgb = img_cv[:,:,::-1]
	img_pil=Image.fromarray(img_rgb.astype('uint8')).convert('RGB')
	return img_pil

# 方法三:使用torchvision的库函数
from torchvision import transforms
def cv2PIL_trans(img_cv):
	img_rgb = img_cv[:,:,::-1]
	trans=transformers.ToPILImage()
	img_pil=trans(img_rgb)
	return img_pil
	
# PIL->cv
def pil2cv(img):
    img=np.asarray(img)
    img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
	return img

def PIL2cv(img_pil):
	img_ary=np.array(img_pil) # 深拷贝,通道顺序是 RGB, (H,W,C)
	# 或者也可以采用深拷贝
	# img_ary=np.asarray(img_pil)
	img_cv=img_ary[:,:,-1]
	return img_cv

opencv和base64

base64 打印比较特殊,不能完全print出来,最好借助txt文件,将base64保存到txt中,然后借助第三方工具查看是正确

第三方工具有 https://phototool.cn/

import cv2
import base64

def base64tocv():
    img_data = base64.b64decode(base64_code)
    img_array = np.frombuffer(img_data, np.uint8)  # convert into numpy
    img = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)  # convert into cv image
    
    
    
#base64 ======> opencv.image
def base642cv2():
	# base64解码
    image_base64 = '传入base64编码'
    image_data = base64.b64decode(image_base64)
    # 转换为np数组
    image_array = np.fromstring(image_data, np.uint8)
    # 转换成opencv可用格式
    image = cv2.imdecode(image_array, cv2.COLOR_RGB2BGR)
    return 
 
def cv2base64():
    path = '你的图片文件路径'
    image_cv = cv2.imread(path)
    image = cv2.imencode('.jpg',image_cv)[1]
    image_base64 = str(base64.b64encode(image))[2:-1]
 
    with open("./base.txt", 'w') as f:
        f.write(img_base64)

PIL和base64

import base64

# PIL类型图像转为base64编码
def pil2base64():
    image=Image.open(path) # PIL Image 类型
    buffered = io.BytesIO()
    image.save(buffered, format="JPEG")
    img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
    
    
    # 保存到本地测试
    with open("./base.txt", 'w') as f:
        f.write(img_base64)
 	return 

# pil2base64
def base642pil():
    encoded_image=""
    buffered=io.BytesIO(base64.b64decode(encoded_image))
    image = Image.open(buffered).convert("RGB")    
    return  image

参考资料

https://blog.csdn.net/zyw2002/article/details/131898067