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

yipeiwu_com5年前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设计】。

相关文章

pybind11和numpy进行交互的方法

使用一个遵循buffer protocol的对象就可以和numpy交互了. 这个buffer_protocol要有哪些东西呢? 要有如下接口: struct buffer_i...

Python登录并获取CSDN博客所有文章列表代码实例

Python登录并获取CSDN博客所有文章列表代码实例

分析登录过程 这几天研究百度登录和贴吧签到,这百度果然是互联网巨头,一个登录过程都弄得复杂无比,简直有毒。我研究了好几天仍然没搞明白。所以还是先挑一个软柿子捏捏,就选择CSDN了。 过程...

Python下rrdtool模块的基本使用方法

最近需要用python根据收集到的数据进行绘图,决定使用rrd数据库,然后配合rrdtool来绘图,故学习一下rrdtool的用法。 用法如下: 创建: create(...) crea...

Python3使用requests发闪存的方法

requests是一个python 轻量的http客户端库,相比python的标准库要优雅很多。接下来通过本文给大家介绍Python3使用requests发闪存的方法,一起学习吧。 使...

python tkinter实现界面切换的示例代码

python tkinter实现界面切换的示例代码

跳转实现思路 主程序相当于桌子: import tkinter as tk root = tk.Tk() 而不同的Frame相当于不同的桌布: face1 = tk....