新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
python中如何實現(xiàn)PIL/cv2/base64相互轉(zhuǎn)換-創(chuàng)新互聯(lián)
這篇文章主要為大家展示了“python中如何實現(xiàn)PIL/cv2/base64相互轉(zhuǎn)換”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“python中如何實現(xiàn)PIL/cv2/base64相互轉(zhuǎn)換”這篇文章吧。
PIL和cv2是python中兩個常用的圖像處理庫,PIL一般是anaconda自帶的,cv2是opencv的python版本。base64在網(wǎng)絡傳輸圖片的時候經(jīng)常用到。
##PIL讀取、保存圖片方法 from PIL import Image img = Image.open(img_path) img.save(img_path3) ##cv2讀取、保存圖片方法 import cv2 img = cv2.imread(img_path) cv2.imwrite(img_path3, 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中如何實現(xiàn)PIL/cv2/base64相互轉(zhuǎn)換”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
網(wǎng)站名稱:python中如何實現(xiàn)PIL/cv2/base64相互轉(zhuǎn)換-創(chuàng)新互聯(lián)
文章鏈接:http://www.ef60e0e.cn/article/doegcg.html