Python实现图像的二进制与base64互转
作者:Vertira 发布时间:2021-03-18 17:57:55
标签:Python,图像,二进制,base64
函数使用
def base64_to_image(base64_code):
img_data = base64.b64decode(base64_code)
img_array = numpy.fromstring(img_data, numpy.uint8)
# img_array = np.frombuffer(image_bytes, dtype=np.uint8) #可选
image_base64_dec = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)
return image_base64_dec
def image_to_base64(full_path):
with open(full_path, "rb") as f:
data = f.read()
image_base64_enc = base64.b64encode(data)
image_base64_enc = str(image_base64_enc, 'utf-8')
return image_base64_enc
#传base64
img_bytes = request.json["img_stream"]
img_cv = base64_to_image(img_bytes)
uuid_str = str(uuid.uuid1())
img_path = uuid_str +".jpg"
cv2.imwrite(img_path,img_cv)
1.图像转base64编码
import cv2
import base64
def cv2_base64(image):
img = cv2.imread(image)
binary_str = cv2.imencode('.jpg', img)[1].tostring()#编码
base64_str = base64.b64encode(binary_str)#解码
base64_str = base64_str.decode('utf-8')
myjson={"bs64":cv2_base64("1.jpg")}
print(myjson)
return base64_str
2.图像转二进制编码
import cv2
import base64
def cv2_binary(image):
img = cv2.imread(image)
binary_str = cv2.imencode('.jpg', img)[1].tostring()#编码
print(binary_str)
# base64_str = base64.b64encode(binary_str)#解码
# base64_str = base64_str.decode('utf-8')
# print(base64_str)
return binary_str
cv2_binary("1.jpg")
# 或者
image_file =r"1.jpg"
image_bytes = open(image_file, "rb").read()
print(image_bytes)# 二进制数据
3.图像保存成二进制文件并读取二进制
# python+OpenCV读取图像并转换为二进制格式文件的代码
# coding=utf-8
'''
Created on 2016年3月24日
使用Opencv读取图像将其保存为二进制格式文件,再读取该二进制文件,转换为图像进行显示
@author: hanchao
'''
import cv2
import numpy as np
import struct
image = cv2.imread("1.jpg")
# imageClone = np.zeros((image.shape[0],image.shape[1],1),np.uint8)
# image.shape[0]为rows
# image.shape[1]为cols
# image.shape[2]为channels
# image.shape = (480,640,3)
rows = image.shape[0]
cols = image.shape[1]
channels = image.shape[2]
# 把图像转换为二进制文件
# python写二进制文件,f = open('name','wb')
# 只有wb才是写二进制文件
fileSave = open('patch.bin', 'wb')
for step in range(0, rows):
for step2 in range(0, cols):
fileSave.write(image[step, step2, 2])
for step in range(0, rows):
for step2 in range(0, cols):
fileSave.write(image[step, step2, 1])
for step in range(0, rows):
for step2 in range(0, cols):
fileSave.write(image[step, step2, 0])
fileSave.close()
# 把二进制转换为图像并显示
# python读取二进制文件,用rb
# f.read(n)中n是需要读取的字节数,读取后需要进行解码,使用struct.unpack("B",fileReader.read(1))函数
# 其中“B”为无符号整数,占一个字节,“b”为有符号整数,占1个字节
# “c”为char类型,占一个字节
# “i”为int类型,占四个字节,I为有符号整形,占4个字节
# “h”、“H”为short类型,占四个字节,分别对应有符号、无符号
# “l”、“L”为long类型,占四个字节,分别对应有符号、无符号
fileReader = open('patch.bin', 'rb')
imageRead = np.zeros(image.shape, np.uint8)
for step in range(0, rows):
for step2 in range(0, cols):
a = struct.unpack("B", fileReader.read(1))
imageRead[step, step2, 2] = a[0]
for step in range(0, rows):
for step2 in range(0, cols):
a = struct.unpack("b", fileReader.read(1))
imageRead[step, step2, 1] = a[0]
for step in range(0, rows):
for step2 in range(0, cols):
a = struct.unpack("b", fileReader.read(1))
imageRead[step, step2, 0] = a[0]
fileReader.close()
cv2.imshow("source", image)
cv2.imshow("read", imageRead)
cv2.imwrite("2.jpg",imageRead)
cv2.waitKey(0)
4.二进制转图像
def binary_cv2(bytes):
file = open("4.jpg","wb")
file.write(bytes)
binary_cv2("bytes")
#或者
from PIL import Image
import io
img = Image.open(io.BytesIO("bytes"))
img.save("5.jpg")
5.base64转图像
def base64_cv2(base64code):
img_data = base64.b64decode(base64code)
file = open("2.jpg","wb")
file.write(img_data)
file.close()
base64_cv2("base64code")
============================================
with open("1.txt","r") as f:
img_data = base64.b64decode(f.read())
file = open("3.jpg","wb")
file.write(img_data)
file.close()
6.互转
def base64_to_image(base64_code):
img_data = base64.b64decode(base64_code)
img_array = numpy.fromstring(img_data, numpy.uint8)
image_base64_dec = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)
return image_base64_dec #图像矩阵,需要cv2.imwrite写入cv2.imwrite("1.jpg",img)
def image_to_base64(full_path):
with open(full_path, "rb") as f:
data = f.read()
image_base64_enc = base64.b64encode(data)
image_base64_enc = str(image_base64_enc, 'utf-8')
return image_base64_enc
7.二进制转base64
def binary_base64(binary):
img_stream = base64.b64encode(binary)
bs64 = img_stream.decode('utf-8')
print(bs64)
8.base64转二进制
import base64
bs64 = ""
img_data = base64.b64decode(bs64)
print(img_data)
来源:https://blog.csdn.net/Vertira/article/details/123844551
0
投稿
猜你喜欢
- 通过《SQL Server 数据库备份和还原认识和总结(一)》,相信您对数据备份和还原有了一个更深入的认识,在上文中我没有对事务日志做剖析,
- hello,大家好,我是Dream。马上就跨年了,为了广大的单身男性成员,我就慈悲一下,把我的存货–表白神器拿出来了,百试百灵(虽然我一次也
- 项目介绍最近学习django,通过文件上传下载这个小项目,总结下常用的知识点。做这个案例我有以下需求:1.要支持一次上传多个文件2.支持上传
- Pytorch损失函数torch.nn.NLLLoss()在各种深度学习框架中,我们最常用的损失函数就是交叉熵(torch.nn.Cross
- 本文实例讲述了PHP实现的简单排列组合算法应用。分享给大家供大家参考,具体如下:一、问题:给你一个40斤的西瓜,给3个人分,有多少种分法?二
- 本文实例为大家分享了python手写均值滤波的具体代码,供大家参考,具体内容如下原理与卷积类似,设置一个n*n的滤波模板,滤波模板内的值累加
- 假设通过爬虫你获取到了北京2016年3,10月份每天白天的最高气温(分别位于列表a,b),那么此时如何寻找出气温随时间(天)变化的某种规律?
- 关于这个话题,我也看到网上有其他方法来解决。 不过从性能和代码量上来看,我有更好的办法。 在这里和大家 分享。 原理其实很简单, 知识1、长
- python启用多线程后,调用exit出现无法退出的情况,原因是exit会抛出Systemexit的异常,如果在exit外围调用了try,就
- 本文实例为大家分享了js实现滑动进度条效果的具体代码,供大家参考,具体内容如下进度条:<!DOCTYPE html><ht
- 代码如下:<%@LANGUAGE="VBSCRIPT"%> <% option&n
- language.xml 代码如下:<?xml version="1.0" encoding=
- 在自动化中, Selenium 自动化测试中有一个名字经常被提及 PageObject( 思想与面向对象的特征相 同 ) ,通常 PO 模型
- 有时候需要比较大的计算量,这个时候Python的效率就很让人捉急了,此时可以考虑使用numba 进行加速,效果提升明显~(numba 安装貌
- torch.save:保存序列化的对象到磁盘,使用了Python的pickle进行序列化,模型、张量、所有对象的字典。torch.load:
- 写桌面程序或有些特殊操作的,经常需要访问剪切板。python有专用的模块,可以很方便简单的操作剪切板如下:#coding:utf-8impo
- 本文实例为大家分享了使用python的twisted框架编写一个简单的聊天室具体代码,供大家参考,具体内容如下下面是基本架构代码:# -*-
- 知识补充表单简介(来自Mr._Dang)action:提交的地址method:提交的方式 get: 参数是在url中的,不安全,传输量比较少
- 在深度学习的数据训练过程中,虽然tensorflow和pytorch都会自带打乱数据进行训练的方法,但是当我们自己生成数据,或者某些情况下依
- 今天我们分享一个小案例,获取天气数据,进行可视化分析,带你直观了解天气情况!核心功能设计总体来说,我们需要先对中国天气网中的天气数据进行爬取