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


猜你喜欢
- 如下所示:import serialimport timet = serial.Serial('com6', 115200)
- 这篇文章主要介绍了python使用rsa非对称加密过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要
- 参考资料:正则表达式语法–菜鸟教程Java正则表达式实现简单批量替换举例:将and 批量替换为&&Python实现impor
- 例如:select (a+b) as c from 表 类型也一致都是varchar型的,可就是显示不正确。 直到concat() MySQ
- 学习完如何生成一个 excel 文件之后,接下来我们继续学习一下如何在 excel 文件中写入一个比较简单的图表,先来看一下所需要的几个函数
- <?php/*======================================事务处理==================
- 因项目需要,需要使用C#控制台程序执行python脚本,查询各种资料后可以成功调用了,记录一下,以备后面遗忘。只尝试了两种调用方式,第一种只
- 序言小学妹说要毕业了,学了一学期Python等于没学,现在要做毕设做不出来,让我帮帮她,晚上去她家吃夜宵。当时我心想,这不是分分钟的事情,还
- 1。下载mysql-noinstall-5.1.33-win32.zip,然后解压 2。复制my-huge配置文件为my.ini 在 [my
- 前言前几天逛github发现了一个有趣的并发库-conc,其目标是:更难出现goroutine泄漏处理panic更友好并发代码可读性高从简介
- Python lxml安装失败针对windows系统LXML安装失败而且pip升级也失败解决方案原因可能是pip没有安装到python我们需
- 多的不说,看了代码就懂了!df = pd.DataFrame ({'a' : np.random.randn(6), &nb
- 匿名函数lambda表达式 什么是匿名函数?匿名函数,顾名思义就是没有名字的函数,在程序中不用使用 def 进行定义,可以直接使用 lamb
- 包的引入:import numpy as npimport pandas as pd1. Series 对象的创建1.1 创建一个空的 Se
- 现在拥有了正则表达式这把神兵利器,我们就可以进行对爬取到的全部网页源代码进行筛选了。下面我们一起尝试一下爬取内涵段子网站:http://ww
- 想要用python自已手动序列化嵌套类,就要明白两个问题:1.Json是什么?2.Json支持什么类型?答案显而易见Json就是嵌套对象Js
- 阅读上一篇教程:WEB2.0网页制作标准教程(9)第一个CSS布局实例如果我们想在3列布局的最后加一行页脚,放版权之类的信息。就遇到必须对齐
- 一、需求来源:如果用户在文本框中填了一段<script>alert(xxx);</script>代码,然后我们还保存
- 一、获取Tensor神经网络在运算过程中实际上是以Tensor为格式进行计算的,我们只需稍稍改动一下forward函数即可从运算过程中抓到T
- 本系列文章是我在sqlskill.com的PAUL的博客看到的,很多误区都比较具有典型性和代表性,原文来自T-SQL Tuesday #11