1. 程式人生 > 程式設計 >Python PIL庫圖片灰化處理

Python PIL庫圖片灰化處理

2020年4月4日,是個特殊的日子,我們看到朋友圈很多灰化的圖片.今天我們就聊聊圖片灰度處理這事兒.

PIL的基本概念:

PIL中所涉及的基本概念有如下幾個:通道(bands)、模式(mode)、尺寸(size)、座標系統(coordinate system)、調色盤(palette)、資訊(info)和濾波器(filters)。

PIL(Python Image Library)是python的第三方影象處理庫,但是由於其強大的功能與眾多的使用人數,幾乎已經被認為是python官方影象處理庫了。其官方主頁為:[PIL](http://pythonware.com/products/pil/)。 PIL歷史悠久,原來是隻支援python2.x的版本的,後來出現了移植到python3的庫[pillow](http://python-pillow.org/),pillow號稱是`friendly fork for PIL`,其功能和PIL差不多,但是支援python3。

Python可以處理圖片的庫很多:Matplotlib,OpenCV,TensorFlow,PIL等.我們今天的主角是:PIL(Python Imaging Library).我們的環境是Python3.8.2

安裝

pip install Pillow

編碼

import os
try:
 from PIL import Image
except ImportError as e:
 print(e)
 print('pip install Pillow')
 os._exit(0)
img_url = '/Users/rainbird/Desktop/a.jpg'
img_out = img_url.replace('.jpg','_gray.jpg')
if not os.path.exists(img_url):
 print(f'file not found: {img_url}')
 os._exit(0)
print(f'''
image in:{img_url}
image out:{img_out}
'''.strip())
img_org = Image.open(img_url)
img_gray= img_org.convert('L') 
img_gray.save(img_out)
print('done')

程式碼不長,主要是:

匯入庫並判斷了異常;

指定處理的檔案,個人執行的時候要修改一下;

轉換完會產生同名_gray的檔案

目前只處理了.jpg

執行

image in:/Users/rainbird/Desktop/a.jpg
image out:/Users/rainbird/Desktop/a_gray.jpg
done

效果

Python PIL庫圖片灰化處理

總結

到此這篇關於Python PIL庫圖片灰化處理的文章就介紹到這了,更多相關Python 圖片灰化內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!