脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python实现图像的二进制与base64互转

Python实现图像的二进制与base64互转

2022-11-17 11:54Vertira Python

这篇文章主要为大家介绍了如何在Python中使用OpenCV从而实现图像转base64编码、图像转二进制编码、二进制转图像等功能,感兴趣的可以跟上小编一起学习一下

函数使用

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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编码

?
1
2
3
4
5
6
7
8
9
10
11
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.图像转二进制编码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.图像保存成二进制文件并读取二进制

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#   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.二进制转图像

?
1
2
3
4
5
6
7
8
9
10
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转图像

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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.互转

?
1
2
3
4
5
6
7
8
9
10
11
12
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

?
1
2
3
4
def binary_base64(binary):
    img_stream = base64.b64encode(binary)
    bs64 = img_stream.decode('utf-8')
    print(bs64)

8.base64转二进制

?
1
2
3
4
5
import base64
 
bs64 = ""
img_data = base64.b64decode(bs64)
print(img_data)

以上就是Python实现图像的二进制与base64互转的详细内容,更多关于Python图像二进制转base64的资料请关注服务器之家其它相关文章!

原文链接:https://blog.csdn.net/Vertira/article/details/123844551

延伸 · 阅读

精彩推荐
  • Pythonpython中的随机函数random的用法示例

    python中的随机函数random的用法示例

    这篇文章主要介绍了python中的随机函数random的用法示例,详细的介绍了python 随机函数random的用法和示例,具有一定的参考价值,感兴趣的小伙伴们可以参考...

    两只橙15862021-01-09
  • PythonPython中OpenCV实现查找轮廓的实例

    Python中OpenCV实现查找轮廓的实例

    本文将结合实例代码,介绍 OpenCV 如何查找轮廓、获取边界框。具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    GoCodingInMyWay9392021-11-26
  • Python人工智能学习PyTorch教程之层和块

    人工智能学习PyTorch教程之层和块

    这篇文章主要为大家介绍了人工智能学习Pytorch教程中的层和块的相关知识点,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步...

    LolitaAnn10882022-03-08
  • Python深入理解Python异常处理的哲学

    深入理解Python异常处理的哲学

    这篇文章主要给大家介绍了关于Python异常处理的哲学,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们...

    alpha_panda12442021-05-25
  • Pythonwx.CheckBox创建复选框控件并响应鼠标点击事件

    wx.CheckBox创建复选框控件并响应鼠标点击事件

    这篇文章主要为大家详细介绍了wx.CheckBox创建复选框控件并响应鼠标点击事件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    烈风13102021-02-05
  • PythonPython闭包和装饰器用法实例详解

    Python闭包和装饰器用法实例详解

    这篇文章主要介绍了Python闭包和装饰器用法,结合实例形式详细分析了Python闭包和装饰器的相关概念、原理、使用技巧与相关操作注意事项,需要的朋友可以...

    xuezhangjun7042021-06-28
  • Pythonpython3 中文乱码与默认编码格式设定方法

    python3 中文乱码与默认编码格式设定方法

    今天小编就为大家分享一篇python3 中文乱码与默认编码格式设定方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 ...

    EnjoySmile3892021-04-14
  • Pythonpython实现手机通讯录搜索功能

    python实现手机通讯录搜索功能

    这篇文章主要介绍了python模仿手机通讯录搜索功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    huo_121413312021-01-16