使用PIL模塊中的ImageEnhance進行圖片數據增強

使用此方法將圖片進行數據增強,具體增強圖片的形式是如下幾種:

"""
1、對比度:白色畫面(最亮時)下的亮度除以黑色畫面(最暗時)下的亮度;
2、色彩飽和度::彩度除以明度,指色彩的鮮豔程度,也稱色彩的純度;
3、色調:向負方向調節會顯現紅色,正方向調節則增加黃色。適合對膚色對象進行微調;
4、銳度:是反映圖像平面清晰度和圖像邊緣銳利程度的一個指標。
"""

代碼如下:
 

import os
from PIL import Image
from PIL import ImageEnhance
 
 
"""
1、對比度:白色畫面(最亮時)下的亮度除以黑色畫面(最暗時)下的亮度;
2、色彩飽和度::彩度除以明度,指色彩的鮮豔程度,也稱色彩的純度;
3、色調:向負方向調節會顯現紅色,正方向調節則增加黃色。適合對膚色對象進行微調;
4、銳度:是反映圖像平面清晰度和圖像邊緣銳利程度的一個指標。
"""
 
def augument(image_path, parent):
     #讀取圖片
     image = Image.open(image_path)
 
     image_name = os.path.split(image_path)[1]
     name = os.path.splitext(image_name)[0]
 
     #變亮
     #亮度增強,增強因子爲0.0將產生黑色圖像;爲1.0將保持原始圖像。
     enh_bri = ImageEnhance.Brightness(image)
     brightness = 1.5
     image_brightened1 = enh_bri.enhance(brightness)
     image_brightened1.save(os.path.join(parent, '{}_bri1.jpg'.format(name)))
 
     #變暗
     enh_bri = ImageEnhance.Brightness(image)
     brightness = 0.8
     image_brightened2 = enh_bri.enhance(brightness)
     image_brightened2.save(os.path.join(parent, '{}_bri2.jpg'.format(name)))
 
     #色度,增強因子爲1.0是原始圖像
     # 色度增強
     enh_col = ImageEnhance.Color(image)
     color = 1.5
     image_colored1 = enh_col.enhance(color)
     image_colored1.save(os.path.join(parent, '{}_col1.jpg'.format(name)))
 
     # 色度減弱
     enh_col = ImageEnhance.Color(image)
     color = 0.8
     image_colored1 = enh_col.enhance(color)
     image_colored1.save(os.path.join(parent, '{}_col2.jpg'.format(name)))
 
     #對比度,增強因子爲1.0是原始圖片
     # 對比度增強
     enh_con = ImageEnhance.Contrast(image)
     contrast = 1.5
     image_contrasted1 = enh_con.enhance(contrast)
     image_contrasted1.save(os.path.join(parent, '{}_con1.jpg'.format(name)))
 
     # 對比度減弱
     enh_con = ImageEnhance.Contrast(image)
     contrast = 0.8
     image_contrasted2 = enh_con.enhance(contrast)
     image_contrasted2.save(os.path.join(parent, '{}_con2.jpg'.format(name)))
 
     # 銳度,增強因子爲1.0是原始圖片
     # 銳度增強
     enh_sha = ImageEnhance.Sharpness(image)
     sharpness = 3.0
     image_sharped1 = enh_sha.enhance(sharpness)
     image_sharped1.save(os.path.join(parent, '{}_sha1.jpg'.format(name)))
 
     # 銳度減弱
     enh_sha = ImageEnhance.Sharpness(image)
     sharpness = 0.8
     image_sharped2 = enh_sha.enhance(sharpness)
     image_sharped2.save(os.path.join(parent, '{}_sha2.jpg'.format(name)))
 
dir = 'E:/4/'
for parent, dirnames, filenames in os.walk(dir):
     for filename in filenames:
          fullpath = os.path.join(parent + '/', filename)
          if 'jpg' in fullpath:
               print(fullpath, parent)
               augument(fullpath, parent)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章