PyTorch – torchvision.transforms – GaussianBlur()
torchvision.transforms 模組提供了許多重要的轉換,可用於對影像資料執行不同型別的操作。GaussianBlur() 轉換用於使用隨機選擇的 Gaussian 模糊來模糊影像。
GaussianBlur() 轉換接受 PIL 和張量影像或一批張量影像。張量影像是一個形狀為 [3, H, W] 的 PyTorch 張量,其中 H 是影像高度,W 是影像寬度。一批張量影像也是一個 torch 張量,形狀為 [B, 3, H, W],其中 B 是批次中的影像數量。
語法
torchvision.transforms.GaussianBlur(kernel_size, sigma=(0.1,.2))(img)
kernel_size – 高斯核的大小。它必須是兩個整數的列表或元組。
sigma – 用於建立高斯核的標準差。
img – 要模糊的 PIL 影像或張量影像。
它返回一個高斯模糊影像。
步驟
我們可以使用以下步驟使用隨機選擇的高斯模糊來模糊影像:
匯入所需的庫。在以下所有示例中,所需的 Python 庫為 torch、Pillow 和 torchvision。確保您已安裝它們。
import torch import torchvision import torchvision.transforms as T from PIL import Image
讀取輸入影像。輸入影像是 PIL 影像或 torch 張量。
img = Image.open('spice.jpg')定義一個轉換,以使用隨機選擇的高斯模糊來模糊輸入影像。
transform = T.GaussianBlur(kernel_size=(7, 13), sigma=(0.1, 0.2))
將上面定義的轉換應用於輸入影像以模糊輸入影像。
blurred_img = transform(img)
顯示模糊的影像。
blurred_img.show()
輸入影像
此影像用作以下所有示例中的輸入檔案。

示例 1
此示例演示如何使用隨機選擇的高斯模糊來模糊輸入影像。
# import required libraries
import torch
import torchvision.transforms as T
from PIL import Image
# read the input image
img = Image.open('spice.jpg')
# define the transform to blur image
transform = T.GaussianBlur(kernel_size=(7, 13), sigma=(9, 11))
# blur the input image using the above defined transform
img = transform(img)
# display the blurred image
img.show()輸出
它將產生以下輸出:
.jpg)
以上輸出是原始輸入影像的模糊影像。
示例 2
讓我們再舉一個例子:
import torch
import torchvision.transforms as T
from PIL import Image
import matplotlib.pyplot as plt
# read the input image
img = Image.open('spice.jpg')
# define a transform with kernel size and sigma
transform = T.GaussianBlur(kernel_size=(19, 23), sigma=(20, 25))
# apply the above transform on input image
blurred_imgs = [transform(img) for _ in range(4)]
fig = plt.figure(figsize=(7,4))
rows, cols = 2,2
for j in range(0, len(blurred_imgs)):
fig.add_subplot(rows, cols, j+1)
plt.imshow(blurred_imgs[j])
plt.xticks([])
plt.yticks([])
plt.show()輸出
它將產生以下輸出:
.jpg)
每個輸出影像都使用從給定範圍內隨機選擇的高斯模糊進行模糊。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP