定义一个添加随机遮罩的函数,将输入的tensor格式图片加上不规则的掩膜
时间: 2024-05-08 07:19:48 浏览: 162
好的,以下是一个Python函数,可以将输入的tensor格式图片添加不规则的随机掩膜:
```
import torch
import numpy as np
from torchvision import transforms
def add_random_mask(tensor_img, mask_size=(256, 256), value_range=(0, 1), max_vertex=20, max_angle=20, max_scale=0.1, max_trans=0.1):
# Convert tensor to numpy array
np_img = tensor_img.numpy().transpose(1, 2, 0)
# Generate random polygon mask
vertices = np.random.randint(0, max(mask_size) // 2, [max_vertex, 2])
angles = np.deg2rad(np.random.rand(max_vertex) * max_angle)
scales = 1 - np.random.rand(max_vertex) * max_scale
trans = np.random.rand(max_vertex, 2) * max_trans
from PIL import Image, ImageDraw
img = Image.new('L', mask_size, 0)
ImageDraw.Draw(img).polygon([(x, y) for x, y in vertices], outline=1, fill=1)
mask = np.array(img)
mask = np.dstack([mask, mask, mask])
for i in range(max_vertex):
M_rot = np.array([[np.cos(angles[i]), -np.sin(angles[i])], [np.sin(angles[i]), np.cos(angles[i])]])
M_scale = np.array([[np.sqrt(scales[i]), 0], [0, np.sqrt(scales[i])]])
M_trans = np.array([[trans[i][0] * mask_size[0], trans[i][1] * mask_size[1]]])
M_affine = M_rot.dot(M_scale).dot(np.hstack([np.eye(2), M_trans.T]))
mask = cv2.warpAffine(mask, M_affine, mask_size[::-1], borderMode=cv2.BORDER_CONSTANT, borderValue=tuple([int(x) for x in value_range]))
# Add mask to image
masked_img = np_img * mask
# Convert back to tensor
trans = transforms.ToTensor()
tensor_masked_img = trans(masked_img)
return tensor_masked_img
```
这个函数使用了OpenCV和Pillow库,需要先安装。
使用方法如下:
```
import cv2
# Load image
img_path = 'test.png'
tensor_img = transforms.ToTensor()(Image.open(img_path))
# Add random mask
tensor_masked_img = add_random_mask(tensor_img)
# Save masked image
masked_img = tensor_masked_img.numpy().transpose(1, 2, 0)
cv2.imwrite('masked_test.png', masked_img * 255)
```
这个函数会生成一些随机的多边形掩膜,并将其应用于输入的图片。你可以通过调整函数的参数来控制掩膜的大小和形状。
阅读全文