首頁 > 軟體

Python imgaug庫安裝與使用教學(圖片加模糊光雨雪霧等特效)

2022-11-13 14:00:46

簡介

imgaug:機器學習實驗中的影象增強庫,特別是折積神經網路。支援以多種不同方式增強影象、關鍵點/地標、邊界框、熱圖和分割圖。

安裝

在anaconda prompt裡進行

 pip install imgaug

看了幾篇文章,出錯的話可以先安裝依賴庫shapely

Overview

特效

官網網址

Project 結構

程式

圖片放入input

參考的原始碼(來源於網路)

main.py

# ###################原始碼####################
# !usr/bin/python
# -*- coding: utf-8 -*-
import cv2
from imgaug import augmenters as iaa
import os

# Sometimes(0.5, ...) 所有情況的 50% 中應用給定的增強器
# e.g. Sometimes(0.5, GaussianBlur(0.3)) would blur roughly every second image.
sometimes = lambda aug: iaa.Sometimes(0.5, aug)

# 定義一組變換方法.
seq = iaa.Sequential([

    # 選擇0到5種方法做變換
    iaa.SomeOf((0, 5),
               [
                   iaa.Fliplr(0.5),  # 對50%的圖片進行水平映象翻轉
                   iaa.Flipud(0.5),  # 對50%的圖片進行垂直映象翻轉

                   # superpixel representation 將一些影象轉換為它們的超畫素表示,每張影象取樣 20 到 200 個超畫素,但不要用它們的平均值替換所有超畫素,只替換其中的一些(p_replace)。
                   sometimes(
                       iaa.Superpixels(
                           p_replace=(0, 1.0),
                           n_segments=(20, 200)
                       )
                   ),

                   # Blur each image with varying strength using
                   # gaussian blur (sigma between 0 and 3.0),
                   # average/uniform blur (kernel size between 2x2 and 7x7)
                   # median blur (kernel size between 3x3 and 11x11).
                   iaa.OneOf([
                       iaa.GaussianBlur((0, 3.0)),
                       iaa.AverageBlur(k=(2, 7)),
                       iaa.MedianBlur(k=(3, 11)),
                   ]),

                   # Sharpen each image, overlay the result with the original
                   # image using an alpha between 0 (no sharpening) and 1
                   # (full sharpening effect).
                   iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5)),

                   # Same as sharpen, but for an embossing effect.
                   iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)),

                   # Add gaussian noise to some images.
                   # In 50% of these cases, the noise is randomly sampled per
                   # channel and pixel.
                   # In the other 50% of all cases it is sampled once per
                   # pixel (i.e. brightness change).
                   iaa.AdditiveGaussianNoise(
                       loc=0, scale=(0.0, 0.05 * 255)
                   ),

                   # Invert each image's chanell with 5% probability.
                   # This sets each pixel value v to 255-v.
                   iaa.Invert(0.05, per_channel=True),  # invert color channels

                   # Add a value of -10 to 10 to each pixel.
                   iaa.Add((-10, 10), per_channel=0.5),

                   # Add random values between -40 and 40 to images, with each value being sampled per pixel:
                   iaa.AddElementwise((-40, 40)),

                   # Change brightness of images (50-150% of original value).
                   iaa.Multiply((0.5, 1.5)),

                   # Multiply each pixel with a random value between 0.5 and 1.5.
                   iaa.MultiplyElementwise((0.5, 1.5)),

                   # Improve or worsen the contrast of images.
                   iaa.ContrastNormalization((0.5, 2.0)),
                   iaa.imgcorruptlike.Saturate(severity=3),

               ],
               # do all of the above augmentations in random order
               random_order=True
               )

], random_order=True)  # apply augmenters in random order

# 圖片檔案相關路徑
path = './input/'
savedpath = './output/'

imglist = []
filelist = os.listdir(path)

# 遍歷要增強的資料夾,把所有的圖片儲存在imglist中
for item in filelist:
    img = cv2.imread(path + item)
    # print('item is ',item)
    # print('img is ',img)
    # images = load_batch(batch_idx)
    imglist.append(img)
# print('imglist is ' ,imglist)
print('all the picture have been appent to imglist')

# 對資料夾中的圖片進行增強操作,迴圈10次
for count in range(10):
    images_aug = seq.augment_images(imglist)
    for index in range(len(images_aug)):
        filename = str(count) + str(index) + '.jpg'
        # 儲存圖片
        cv2.imwrite(savedpath + filename, images_aug[index])
        print('image of count%s index%s has been writen' % (count, index))

簡易變換 試效果

test01.py

# ##############簡易變換#################

# https://imgaug.readthedocs.io/en/latest/source/overview_of_augmenters.html
import cv2
from imgaug import augmenters as iaa
import os

# Sometimes(0.5, ...) applies the given augmenter in 50% of all cases,
# e.g. Sometimes(0.5, GaussianBlur(0.3)) would blur roughly every second image.
# sometimes = lambda aug: iaa.Sometimes(0.5, aug)

# 定義一組變換方法.
seq = iaa.Sequential([
    iaa.MotionBlur(k=15),  # 運動模糊
    # iaa.Clouds(),  # 雲霧
    # iaa.imgcorruptlike.Fog(severity=1),  # 多霧/霜
    # iaa.imgcorruptlike.Snow(severity=2),  # 下雨、大雪
    # iaa.Rain(drop_size=(0.10, 0.20), speed=(0.2, 0.3)),  # 雨
    # iaa.Rain(speed=(0.3, 0.5)),  # 雨
    # iaa.Snowflakes(flake_size=(0.6, 0.7), speed=(0.02, 0.03)), # 雪點
    # iaa.imgcorruptlike.Spatter(severity=2),  # 濺 123水滴、45泥
    # iaa.contrast.LinearContrast((0.5, 2.0), per_channel=0.5),# 對比度變為原來的一半或者二倍
    # iaa.imgcorruptlike.Brightness(severity=2),  # 亮度增加
    # iaa.imgcorruptlike.Saturate(severity=3),  # 色彩飽和度
    # iaa.FastSnowyLandscape(lightness_threshold=(100, 255),lightness_multiplier=(1.5, 2.0)), # 雪地   亮度閾值是從 uniform(100, 255)(每張影象)和來自 uniform(1.5, 2.0)(每張影象)的乘數取樣的。
    # iaa.Cartoon(blur_ksize=3, segmentation_size=1.0, saturation=2.0, edge_prevalence=1.0), # 卡通

])

# 圖片檔案相關路徑
path = './input/'
savedpath = './output_show/'

imglist = []
filelist = os.listdir(path)

# 遍歷要增強的資料夾,把所有的圖片儲存在imglist中
for item in filelist:
    img = cv2.imread(path + item)
    # print('item is ',item)
    # print('img is ',img)
    # images = load_batch(batch_idx)
    imglist.append(img)
# print('imglist is ' ,imglist)
print('all the picture have been appent to imglist')

# 對資料夾中的圖片進行增強操作,迴圈1次
for count in range(1):
    images_aug = seq.augment_images(imglist)
    for index in range(len(images_aug)):
        # filename = str(count) + str(index) + '.jpg'
        # 儲存圖片
        filename = str(filelist[index])
        cv2.imwrite(savedpath + filename, images_aug[index])
        print('image of count%s index%s has been writen' % (count, index))

使用 模糊光雨雪霧

運動模糊+雨雪霧天氣 2-3種
&
對比度 亮度 飽和度 選其一

my_augmentation.py

import cv2
from imgaug import augmenters as iaa
import os

# sometimes = lambda aug: iaa.Sometimes(0.5, aug)   # 所有情況的 50% 中應用給定的增強器

seq = iaa.Sequential([
    # 選擇2到3種方法做變換
    iaa.SomeOf((2, 3),
               [
                   iaa.imgcorruptlike.MotionBlur(severity=(1, 2)),  # 運動模糊
                   # iaa.Clouds(),  # 雲霧
                   iaa.imgcorruptlike.Fog(severity=1),  # 多霧/霜
                   # iaa.imgcorruptlike.Snow(severity=2),  # 下雨、大雪
                   iaa.Rain(drop_size=(0.10, 0.15), speed=(0.1, 0.2)),  # 雨
                   iaa.Snowflakes(flake_size=(0.1, 0.4), speed=(0.01, 0.03)), # 雪點
                   # iaa.FastSnowyLandscape(lightness_threshold=(100, 255),lightness_multiplier=(1.5, 2.0)), # 雪地   亮度閾值是從 uniform(100, 255)(每張影象)和來自 uniform(1.5, 2.0)(每張影象)的乘數取樣的。 這似乎產生了良好而多樣的結果。
                   # iaa.imgcorruptlike.Spatter(severity=5),  # 濺 123水滴、45泥

                   # 對比度 亮度 飽和度 選其一
                   iaa.SomeOf((1, 1),
                       [
                           iaa.imgaug.augmenters.contrast.LinearContrast((0.5, 2.0), per_channel=0.5),  # 對比度變為原來的一半或者二倍
                           iaa.imgcorruptlike.Brightness(severity=(1, 2)),  # 亮度增加
                           iaa.imgcorruptlike.Saturate(severity=(1, 3)),  # 色彩飽和度
                       ]
                   )
               ],
               # 隨機順序執行augmentations
               random_order=True
               )
], random_order=True)  # 隨機執行augmenters數量

# 圖片檔案相關路徑
path = './input/'
savedpath = './output/'

imglist = []
filelist = os.listdir(path)

# 遍歷要增強的資料夾,把所有的圖片儲存在imglist中
for item in filelist:
    img = cv2.imread(path + item)
    # print('item is ',item)
    # print('img is ',img)
    # images = load_batch(batch_idx)
    imglist.append(img)
# print('imglist is ' ,imglist)
print('all the picture have been appent to imglist')


for count in range(1):
    images_aug = seq.augment_images(imglist)
    for index in range(len(images_aug)):
        # 儲存圖片 檔名和原始檔相同
        filename = str(filelist[index])
        cv2.imwrite(savedpath + filename, images_aug[index])
        print('image of count%s index%s has been writen' % (count, index))

else

對input裡的原影象重新命名:00001.jpg或者1.jpg

重新命名00001.jpg

Rename0001.py

# ###################檔案重新命名#################

import os
import re
import sys

path = r"./input"
filelist = os.listdir(path)
filetype = '.jpg'
for file in filelist:
    print(file)
for file in filelist:
    Olddir = os.path.join(path, file)
    print(Olddir)
    if os.path.isdir(Olddir):
        continue

    # os.path.splitext("path"):分離檔名與擴充套件名
    filename = os.path.splitext(file)[0]
    filetype = os.path.splitext(file)[1]

    # zfill() 方法返回指定長度的字串,原字串右對齊,前面填充0
    Newdir = os.path.join(path, filename.zfill(5) + filetype)  # 數位5是定義為5位數,可隨意修改需要的
    os.rename(Olddir, Newdir)

重新命名1.jpg

Rename1.py

# ###################檔案重新命名################
import os
class BatchRename():

    def __init__(self):
        self.path = './input/'  # 圖片的路徑

    def rename(self):
        filelist = os.listdir(self.path)
        filelist.sort()
        total_num = len(filelist)  # 獲取檔案中有多少圖片
        i = 0  # 檔案命名從哪裡開始(即命名從哪裡開始)
        for item in filelist:
            if item.endswith('.png'):
                src = os.path.join(self.path, item)
                dst = os.path.join(os.path.abspath(self.path), str(i) + '.png')

                try:
                    os.rename(src, dst)
                    print('converting %s to %s ...' % (src, dst))
                    i = i + 1
                except Exception as e:
                    print(e)
                    print('rename dir failrn')

        print('total %d to rename & converted %d jpgs' % (total_num, i))


if __name__ == '__main__':
    demo = BatchRename()  # 建立物件
    demo.rename()  # 呼叫物件的方法

效果圖

input範例 00001.jpg

output範例 00001.jpg

input範例 00005.jpg

output範例 00005.jpg

到此這篇關於Python imgaug庫 安裝與使用教學(圖片加模糊光雨雪霧等特效)的文章就介紹到這了,更多相關Python imgaug庫安裝使用內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com