栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

PIL/cv2/base64相互转换实例
  • 1、PIL和cv2转换
  • 2、PIL和base64转换
  • 3、cv2和base64转换
  • 4、eg1.
  • 5、eg2.
  • 6、eg3.

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
4、eg1.
import os
from PIL import Image
import re
import base64
from io import BytesIO


def image_to_base64(file_path):
    """
    file_path 文件路径
    将图片转换为b64encode编码格式
    """
    print(file_path)
    print(type(file_path))
    with open(file_path, 'rb') as fp:
        return base64.b64encode(fp.read()).decode('utf-8')


def pImg_to_base64(pImg):
    """
    二进制图片转base64
    """
    buffered = BytesIO()
    pImg.save(buffered, format="JPEG")
    # return base64.b64encode(buffered.getvalue())
    return base64.b64encode(buffered.getvalue()).decode('utf-8')


# https://www.jb51.net/article/178106.htm
def base64_to_pImg(data):
    """
    base64 转为二进制图片 方便用 PIL 的  Image.open(binary_img).show()
    """
    # binary_img = BytesIO(base64.b64decode(data))
    binary_img = BytesIO(base64.b64decode(data.encode('utf-8')))
    return Image.open(binary_img)


def base64_to_image(filename, data, path=''):
    """
    :param filename: 转换后的image名称
    :param data: base64
    :param path: 转换后的image文件存在路径
    :return:
    """
    file_path = os.path.join(path, filename)
    with open(file_path, "wb") as fp:
        fp.write(base64.b64decode(data.encode('utf-8')))  # 转换为image
5、eg2.
from flask import Flask, request
import time
import os
from PIL import Image
from model.nets.yolo import YOLO
import base64


app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'data/save'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}


def make_dir(path):
    if not os.path.exists(path):
        os.makedirs(path)
    return path


def base64_to_image(filename, data, path="script"):
    """
    :param filename: 转换后的image名称
    :param data: base64
    :param path: 转换后的image文件存在路径
    :return:
    """
    path = os.join(path, filename)
    with open(path, "wb") as fp:
        fp.write(base64.b64decode(data))                # 转换为image


def allowed_file(filename):
    """
    判断文件类型是否允许上传
    """
    return '.' in filename and 
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def image_to_base64(file_path):
    """
    file_path 文件路径
    将图片转换为b64encode编码格式
    """
    with open(file_path, 'rb') as fp:
        return base64.b64encode(fp.read())


@app.route('/hi')
def hello():
    return "Hello world"


@app.route("/predict", methods=["POST"])
def predict():
    if 'imageName' not in request.files:
        return 'No file part'
    file = request.files['imageName']

    if file.filename == '':
        return 'No selected file'
    # ext_name = file.filename.split('.')[1]
    # f_name = str(int(round(time.time() * 1000))) + "." + ext_name

    if file and allowed_file(file.filename):
        image = Image.open(file)
        result_image = YOLO().detect_image(image)
        img_path = os.path.join(make_dir(app.config['UPLOAD_FOLDER']),  file.filename)
        result_image.save(img_path)
        return image_to_base64(img_path)
        # return "00001"
    else:
        return "文件类型不支持"


if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port='5000')
6、eg3.

项目所使用的

import base64
from io import BytesIO
from PIL import Image


# 输⼊为读取的图⽚,输出为bs64格式
def image_to_base64(image):
    # 创建一个字节流管道
    byte_data = BytesIO()
    # 将图片数据存入字节流管道
    image.save(byte_data, format="JPEG")
    # 从字节流管道中获取二进制
    byte_data = byte_data.getvalue()
    # 二进制转base64
    base64_str = base64.b64encode(byte_data)
    return base64_str


 # 输入为base64格式字符串,输出为PIL格式图片
def base64_to_image(base64_str):  # 用 b.show()可以展示
    image = base64.b64decode(base64_str)
    image = BytesIO(image)
    image = Image.open(image)
    return image
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/971506.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号