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 multiprocessing多进程变量共享与加锁的实现

python多进程和多线程是大家会重点了解的部分,因为很多工作如果并没有前后相互依赖关系的话其实顺序并不是非常的重要,采用顺序执行的话就必定会造成无谓的等待,任凭cpu和内存白白浪费,这...

Python实现的删除重复文件或图片功能示例【去重】

Python实现的删除重复文件或图片功能示例【去重】

本文实例讲述了Python实现的删除重复文件或图片功能。分享给大家供大家参考,具体如下: 通过python爬虫或其他方式保存的图片文件通常包含一些重复的图片或文件, 通过下面的pytho...

实例介绍Python中整型

Python中有以下几个基本的数据类型: 整数 int 字符串 str 浮点数 float 集合 set 列表 list 元组 tuple 字典 dict...

PyCharm2018 安装及破解方法实现步骤

PyCharm2018 安装及破解方法实现步骤

PyCharm就是Python语言开发中一个很受欢迎的IDE,界面类似于visual studio,android studio,集成的功能也很多。 1>. 安装 首先要...

python Flask 装饰器顺序问题解决

上周 RealWorld CTF 2018 web 题 bookhub 有个未授权访问的漏洞,比较有意思,赛后看了一下公开的 WriteUp,大家也都没写清楚,所以就有了这篇博文。 前言...