opencv中rgb格式資料和base64資料轉換
阿新 • • 發佈:2018-12-17
最近在做一個專案,需要將base64轉成圖片rgb格式。
一般的做法是將base64字串先解碼寫入檔案,然後再去cv2.imread讀取圖片。這樣就繞彎了,如果能夠從base64直接轉為imread得到的rbg矩陣,就會節省時間開銷,具體做法比較簡單:
def base64_to_image(base64_code): """將base64的資料轉換成rgb格式的影象矩陣""" img_data = base64.b64decode(base64_code) img_array = np.fromstring(img_data, np.uint8) img = cv2.imdecode(img_array, cv2.IMREAD_COLOR) return img
傳入的base64字串,得到的是rgb格式的資料。
那反過來該怎麼做呢?
從rgb格式的影象矩陣到base64字串,需要進行下面轉換:
def image_to_base64(img):
image = cv2.imencode('.jpg',img)[1]
image_code = str(base64.b64encode(image))
return image_code
介紹完畢!