python PIL/cv2/base64相互转换实例

yipeiwu_com6年前Python基础

PIL和cv2是python中两个常用的图像处理库,PIL一般是anaconda自带的,cv2是opencv的python版本。base64在网络传输图片的时候经常用到。

##PIL读取、保存图片方法
from PIL import Image
img = Image.open(img_path)
img.save(img_path2)
 
 
##cv2读取、保存图片方法
import cv2
img = cv2.imread(img_path)
cv2.imwrite(img_path2, img)
 
 
##图片文件打开为base64
import base64
 
def img_base64(img_path):
  with open(img_path,"rb") as f:
    base64_str = base64.b64encode(f.read())
  return base64_str 

1、PIL和cv2转换

##PIL转cv2
import cv2
from PIL import Image
import numpy as np
 
def pil_cv2(img_path):
  image = Image.open(img_path)
  img = cv2.cvtColor(np.asarray(image),cv2.COLOR_RGB2BGR)
  return img
 
 
##cv2转PIL
import cv2
from PIL import Image
 
def cv2_pil(img_path):
  image = cv2.imread(img_path)
  image = Image.fromarray(cv2.cvtColor(image,cv2.COLOR_BGR2RGB))
  return image

2、PIL和base64转换

##PIL转base64
import base64
from io import BytesIO
 
def pil_base64(image):
  img_buffer = BytesIO()
  image.save(img_buffer, format='JPEG')
  byte_data = img_buffer.getvalue()
  base64_str = base64.b64encode(byte_data)
  return base64_str
 
 
##base64转PIL
import base64
from io import BytesIO
from PIL import Image
 
def base64_pil(base64_str):
  image = base64.b64decode(base64_str)
  image = BytesIO(image)
  image = Image.open(image)
  return image

3、cv2和base64转换

##cv2转base64
import cv2
 
def cv2_base64(image):
  base64_str = cv2.imencode('.jpg',image)[1].tostring()
  base64_str = base64.b64encode(base64_str)
  return base64_str 
 
 
##base64转cv2
import base64
import numpy as np
import cv2
 
def base64_cv2(base64_str):
  imgString = base64.b64decode(base64_str)
  nparr = np.fromstring(imgString,np.uint8) 
  image = cv2.imdecode(nparr,cv2.IMREAD_COLOR)
  return image

以上这篇python PIL/cv2/base64相互转换实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python 获得命令行参数的方法(推荐)

本篇将介绍python中sys, getopt模块处理命令行参数 如果想对python脚本传参数,python中对应的argc, argv(c语言的命令行参数)是什么呢? 需要模块:sy...

Python获取某一天是星期几的方法示例

Python获取某一天是星期几的方法示例

本文实例讲述了Python获取某一天是星期几的方法。分享给大家供大家参考,具体如下: 这里以2017年的春节(1月28号)为例: import re; import time; im...

解读python logging模块的使用方法

1 logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;相比print,具备如下优点:...

布同 Python中文问题解决方法(总结了多位前人经验,初学者必看)

因为Python是自带文档,可以通过help函数来查询每一个系统函数的用法解释说明。一般来说,关键的使用方法和注意点在这个系统的文档中都说的很清楚。我试图在网上找过系统文档的中文版的函数...

python的中异常处理机制

什么是异常处理 定义:异常处理就是我们在写Python时,经常看到的报错信息,例如;NameError TypeError ValueError等,这些都是异常。 异常是一个事件,改事件...