python PIL/cv2/base64相互轉(zhuǎn)換實(shí)例
PIL和cv2是python中兩個(gè)常用的圖像處理庫,PIL一般是anaconda自帶的,cv2是opencv的python版本。base64在網(wǎng)絡(luò)傳輸圖片的時(shí)候經(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)換實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- Python常用base64 md5 aes des crc32加密解密方法匯總
- python將圖片轉(zhuǎn)base64,實(shí)現(xiàn)前端顯示
- Python 解碼Base64 得到碼流格式文本實(shí)例
- Python 實(shí)現(xiàn)opencv所使用的圖片格式與 base64 轉(zhuǎn)換
- python base64庫給用戶名或密碼加密的流程
- Python中base64與xml取值結(jié)合問題
- python3 常見解密加密算法實(shí)例分析【base64、MD5等】
- Python3內(nèi)置模塊之base64編解碼方法詳解
- Python 利用base64庫 解碼本地txt文本字符串
相關(guān)文章
基python實(shí)現(xiàn)多線程網(wǎng)頁爬蟲
python是支持多線程的, 主要是通過thread和threading這兩個(gè)模塊來實(shí)現(xiàn)的,本文主要給大家分享python實(shí)現(xiàn)多線程網(wǎng)頁爬蟲,需要的朋友可以參考下2015-09-09一篇文章帶你了解python標(biāo)準(zhǔn)庫--random模塊
這篇文章主要給大家介紹了關(guān)于Python中random模塊常用方法的使用教程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-08-08python爬取拉勾網(wǎng)職位數(shù)據(jù)的方法
這篇文章主要介紹了python爬取拉勾網(wǎng)職位數(shù)據(jù)的實(shí)現(xiàn)方法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2018-01-01使用sklearn對多分類的每個(gè)類別進(jìn)行指標(biāo)評(píng)價(jià)操作
這篇文章主要介紹了使用sklearn對多分類的每個(gè)類別進(jìn)行指標(biāo)評(píng)價(jià)操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06