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 实现简单的 switch/case 语句的方法

在Python中是没有Switch / Case语句的,很多人认为这种语句不够优雅灵活,在Python中用字典来处理多条件匹配问题字典会更简单高效,对于有一定经验的Python玩家不得不...

Python 逐行分割大txt文件的方法

代码如下所示: # -*- coding: <encoding name> -*- import io LIMIT = 150000 file_count = 0 url...

python网络应用开发知识点浅析

发送电子邮件 在即时通信软件如此发达的今天,电子邮件仍然是互联网上使用最为广泛的应用之一,公司向应聘者发出录用通知、网站向用户发送一个激活账号的链接、银行向客户推广它们的理财产品等几乎...

python 实现文件的递归拷贝实现代码

python 实现文件的递归拷贝实现代码

所以就想把这些照片翻着看一遍,可是拷出来的照片手机 里是按时间自动分文件夹的,一个一个文件夹拷很是麻烦,于是打算写个python小脚本来完成这个工作(扯这么多,终于 到主题了,囧) 这...

python 数据生成excel导出(xlwt,wlsxwrite)代码实例

这篇文章主要介绍了python 数据生成excel导出(xlwt,wlsxwrite)代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以...