python PIL/cv2/base64相互轉(zhuǎn)換實例
更新時間:2020年01月09日 09:11:10 作者:二加三等于五
今天小編就為大家分享一篇python PIL/cv2/base64相互轉(zhuǎn)換實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
PIL和cv2是python中兩個常用的圖像處理庫,PIL一般是anaconda自帶的,cv2是opencv的python版本。base64在網(wǎng)絡(luò)傳輸圖片的時候經(jīng)常用到。
##PIL讀取、保存圖片方法 from PIL import Image img = Image.open(img_path) img.save(img_path2) ##cv2讀取、保存圖片方法 import cv2 img = cv2.imread(img_path) cv2.imwrite(img_path2, img) ##圖片文件打開為base64 import base64 def img_base64(img_path): with open(img_path,"rb") as f: base64_str = base64.b64encode(f.read()) return base64_str
1、PIL和cv2轉(zhuǎn)換
##PIL轉(zhuǎn)cv2 import cv2 from PIL import Image import numpy as np def pil_cv2(img_path): image = Image.open(img_path) img = cv2.cvtColor(np.asarray(image),cv2.COLOR_RGB2BGR) return img ##cv2轉(zhuǎn)PIL import cv2 from PIL import Image def cv2_pil(img_path): image = cv2.imread(img_path) image = Image.fromarray(cv2.cvtColor(image,cv2.COLOR_BGR2RGB)) return image
2、PIL和base64轉(zhuǎn)換
##PIL轉(zhuǎn)base64 import base64 from io import BytesIO def pil_base64(image): img_buffer = BytesIO() image.save(img_buffer, format='JPEG') byte_data = img_buffer.getvalue() base64_str = base64.b64encode(byte_data) return base64_str ##base64轉(zhuǎn)PIL import base64 from io import BytesIO from PIL import Image def base64_pil(base64_str): image = base64.b64decode(base64_str) image = BytesIO(image) image = Image.open(image) return image
3、cv2和base64轉(zhuǎn)換
##cv2轉(zhuǎn)base64 import cv2 def cv2_base64(image): base64_str = cv2.imencode('.jpg',image)[1].tostring() base64_str = base64.b64encode(base64_str) return base64_str ##base64轉(zhuǎn)cv2 import base64 import numpy as np import cv2 def base64_cv2(base64_str): imgString = base64.b64decode(base64_str) nparr = np.fromstring(imgString,np.uint8) image = cv2.imdecode(nparr,cv2.IMREAD_COLOR) return image
以上這篇python PIL/cv2/base64相互轉(zhuǎn)換實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
一篇文章帶你了解python標(biāo)準(zhǔn)庫--random模塊
這篇文章主要給大家介紹了關(guān)于Python中random模塊常用方法的使用教程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-08-08python爬取拉勾網(wǎng)職位數(shù)據(jù)的方法
這篇文章主要介紹了python爬取拉勾網(wǎng)職位數(shù)據(jù)的實現(xiàn)方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2018-01-01使用sklearn對多分類的每個類別進行指標(biāo)評價操作
這篇文章主要介紹了使用sklearn對多分類的每個類別進行指標(biāo)評價操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06