處理圖像和音頻的時候,通常拿到的數據以及返回的結果需要轉成base64。最近爲了測試算法接口,找了下面這一小段代碼,實現圖像、音頻與對應base64編碼的相互轉換,做個記錄(其實也有許多在線工具可以將圖像轉base64)。關於base64的內容可以查看廖雪峯的網站https://www.liaoxuefeng.com/wiki/897692888725344/949441536192576
import matplotlib.pyplot as plt
import base64
import cv2
def ToBase64(file, txt):
with open(file, 'rb') as fileObj:
audio_data = fileObj.read()
base64_data = base64.b64encode(audio_data)
fout = open(txt, 'w')
fout.write(base64_data.decode())
fout.close()
def ToFile(txt, file):
with open(txt, 'r') as fileObj:
base64_data = fileObj.read()
ori_image_data = base64.b64decode(base64_data)
fout = open(file, 'wb')
fout.write(ori_image_data)
fout.close()
ToBase64("./street_music.wav",'desk_base64.txt') # 文件轉換爲base64
ToFile("./desk_base64.txt",'desk_cp_by_base64.jpg') # base64編碼轉換爲二進制文件
img = cv2.imread('desk_cp_by_base64.jpg')
plt.imshow(img)
plt.show