File size: 15,036 Bytes
b9e72b4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 | from __future__ import division #This ensures true division (i.e., division results in floating-point numbers) in Python 2 otherwise we get //
import math
import random
import kornia #for computer vision operations in PyTorch.
import torch
from PIL import Image
try:
import accimage #third-party Python library designed to provide accelerated image loading and processing capabilities, primarily intended for use with the PyTorch deep learning framework.Alternative of PIL/pillow
except ImportError:
accimage = None
import numpy as np
import scipy.stats as st
import cv2
import collections
import torchvision.transforms as transforms # for common image transformations.
import util.util as util
from scipy.signal import convolve2d
# utility
#
# PIL and accimage for loading
def _is_pil_image(img): #if accimage is not supported in environment
if accimage is not None:
return isinstance(img, (Image.Image, accimage.Image))
else:
return isinstance(img, Image.Image)
#in transformation step for augmentation and feeding into a model.
def _is_tensor_image(img): #to handle different types of image representations that might be encountered in various stages of image processing
return torch.is_tensor(img) and img.ndimension() == 3 # is 3D tensor
# for certain preprocessing steps.
def _is_numpy_image(img): #to handle different types of image representations that might be encountered in various stages of image processing
return isinstance(img, np.ndarray) and (img.ndim in {2, 3}) #is numpy array of 2 or 3 dimension
def arrshow(arr):
Image.fromarray(arr.astype(np.uint8)).show()#converts a NumPy array to a PIL image and then displays it.
#arr.astype(np.uint8) converts the NumPy array arr to have a data type of np.uint8
# PIL images expect pixel values to be in the range [0, 255],
#Image.fromarray() function is a method provided by the PIL (Pillow) library to convert a pixel values to a PIL image.
#.show() is a method of the PIL Image class to open image in image viewer of system
'''"transformations" refer to a series of operations applied to the images to preprocess or augment them. These transformations can include resizing, cropping, flipping, rotating, and many others. They help in normalizing the data, enhancing certain features, or augmenting the dataset to improve the robustness and performance of the model.'''
def get_transform(opt): #based on option given, a list of transformations are generated
transform_list = []
osizes = util.parse_args(opt.loadSize)
fineSize = util.parse_args(opt.fineSize)
if opt.resize_or_crop == 'resize_and_crop':
transform_list.append(
transforms.RandomChoice([
transforms.Resize([osize, osize], Image.BICUBIC) for osize in osizes
]))
transform_list.append(transforms.RandomCrop(fineSize))
elif opt.resize_or_crop == 'crop':
transform_list.append(transforms.RandomCrop(fineSize))
elif opt.resize_or_crop == 'scale_width':
transform_list.append(transforms.Lambda(
lambda img: __scale_width(img, fineSize)))
elif opt.resize_or_crop == 'scale_width_and_crop':
transform_list.append(transforms.Lambda(
lambda img: __scale_width(img, opt.loadSize)))
transform_list.append(transforms.RandomCrop(opt.fineSize))
if opt.isTrain and not opt.no_flip:
transform_list.append(transforms.RandomHorizontalFlip())
return transforms.Compose(transform_list)
to_norm_tensor = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(
(0.5, 0.5, 0.5),
(0.5, 0.5, 0.5)
)
])
to_tensor = transforms.ToTensor()
def __scale_width(img, target_width):
ow, oh = img.size
if (ow == target_width):
return img
w = target_width
h = int(target_width * oh / ow)
h = math.ceil(h / 2.) * 2 # round up to even
return img.resize((w, h), Image.BICUBIC)
# functional
def gaussian_blur(img, kernel_size, sigma):
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
img = np.asarray(img)
# the 3rd dimension (i.e. inter-band) would be filtered which is unwanted for our purpose
# new = gaussian_filter(img, sigma=sigma, truncate=truncate)
if isinstance(kernel_size, int):
kernel_size = (kernel_size, kernel_size)
elif isinstance(kernel_size, collections.Sequence):
assert len(kernel_size) == 2
new = cv2.GaussianBlur(img, kernel_size, sigma) # apply gaussian filter band by band
return Image.fromarray(new)
# transforms
class GaussianBlur(object):
def __init__(self, kernel_size=11, sigma=3):
self.kernel_size = kernel_size
self.sigma = sigma
def __call__(self, img):
return gaussian_blur(img, self.kernel_size, self.sigma)
class ReflectionSythesis_0(object):
"""Reflection image data synthesis for weakly-supervised learning
of ICCV 2017 paper *"A Generic Deep Architecture for Single Image Reflection Removal and Image Smoothing"*
"""
def __init__(self, kernel_sizes=None, low_sigma=2, high_sigma=5, low_gamma=1.3,
high_gamma=1.3, low_delta=0.4, high_delta=1.8):
self.kernel_sizes = kernel_sizes or [11]
self.low_sigma = low_sigma
self.high_sigma = high_sigma
self.low_gamma = low_gamma
self.high_gamma = high_gamma
self.low_delta = low_delta
self.high_delta = high_delta
print('[i] reflection sythesis model: {}'.format({
'kernel_sizes': kernel_sizes, 'low_sigma': low_sigma, 'high_sigma': high_sigma,
'low_gamma': low_gamma, 'high_gamma': high_gamma}))
def __call__(self, B, R):
if not _is_pil_image(B):
raise TypeError('B should be PIL Image. Got {}'.format(type(B)))
if not _is_pil_image(R):
raise TypeError('R should be PIL Image. Got {}'.format(type(R)))
B_ = np.asarray(B, np.float32)
if random.random() < 0.4:
B_ = np.tile(np.random.uniform(0, 30, (1, 1, 1)), B_.shape) / 255.
else:
B_ = np.tile(np.random.normal(50, 50, (1, 1, 3)), (B_.shape[0], B_.shape[1], 1)).clip(0, 255) / 255.
R_ = np.asarray(R, np.float32) / 255.
kernel_size = np.random.choice(self.kernel_sizes)
sigma = np.random.uniform(self.low_sigma, self.high_sigma)
gamma = np.random.uniform(self.low_gamma, self.high_gamma)
delta = np.random.uniform(self.low_delta, self.high_delta)
R_blur = R_
kernel = cv2.getGaussianKernel(11, sigma)
kernel2d = np.dot(kernel, kernel.T)
for i in range(3):
R_blur[..., i] = convolve2d(R_blur[..., i], kernel2d, mode='same')
R_blur = np.clip(R_blur - np.mean(R_blur) * gamma, 0, 1)
R_blur = np.clip(R_blur * delta, 0, 1)
M_ = np.clip(R_blur + B_, 0, 1)
return B_, R_blur, M_
class ReflectionSythesis_1(object):
"""Reflection image data synthesis for weakly-supervised learning
of ICCV 2017 paper *"A Generic Deep Architecture for Single Image Reflection Removal and Image Smoothing"*
"""
def __init__(self, kernel_sizes=None, low_sigma=2, high_sigma=5, low_gamma=1.3, high_gamma=1.3):
self.kernel_sizes = kernel_sizes or [11]
self.low_sigma = low_sigma
self.high_sigma = high_sigma
self.low_gamma = low_gamma
self.high_gamma = high_gamma
print('[i] reflection sythesis model: {}'.format({
'kernel_sizes': kernel_sizes, 'low_sigma': low_sigma, 'high_sigma': high_sigma,
'low_gamma': low_gamma, 'high_gamma': high_gamma}))
def __call__(self, B, R):
if not _is_pil_image(B):
raise TypeError('B should be PIL Image. Got {}'.format(type(B)))
if not _is_pil_image(R):
raise TypeError('R should be PIL Image. Got {}'.format(type(R)))
B_ = np.asarray(B, np.float32) / 255.
R_ = np.asarray(R, np.float32) / 255.
kernel_size = np.random.choice(self.kernel_sizes)
sigma = np.random.uniform(self.low_sigma, self.high_sigma)
gamma = np.random.uniform(self.low_gamma, self.high_gamma)
R_blur = R_
kernel = cv2.getGaussianKernel(11, sigma)
kernel2d = np.dot(kernel, kernel.T)
for i in range(3):
R_blur[..., i] = convolve2d(R_blur[..., i], kernel2d, mode='same')
M_ = B_ + R_blur
if np.max(M_) > 1:
m = M_[M_ > 1]
m = (np.mean(m) - 1) * gamma
R_blur = np.clip(R_blur - m, 0, 1)
M_ = np.clip(R_blur + B_, 0, 1)
return B_, R_blur, M_
class NoiseReflectionSythesis(object):
"""Reflection image data synthesis for weakly-supervised learning
of ICCV 2017 paper *"A Generic Deep Architecture for Single Image Reflection Removal and Image Smoothing"*
"""
def __init__(self, kernel_sizes=None, low_sigma=2, high_sigma=5, low_gamma=1.3, high_gamma=1.3):
self.kernel_sizes = kernel_sizes or [11]
self.low_sigma = low_sigma
self.high_sigma = high_sigma
self.low_gamma = low_gamma
self.high_gamma = high_gamma
print('[i] reflection sythesis model: {}'.format({
'kernel_sizes': kernel_sizes, 'low_sigma': low_sigma, 'high_sigma': high_sigma,
'low_gamma': low_gamma, 'high_gamma': high_gamma}))
def __call__(self, B, R, N):
if not _is_pil_image(B):
raise TypeError('B should be PIL Image. Got {}'.format(type(B)))
if not _is_pil_image(R):
raise TypeError('R should be PIL Image. Got {}'.format(type(R)))
B_ = np.asarray(B, np.float32) / 255. + N
R_ = np.asarray(R, np.float32) / 255.
kernel_size = np.random.choice(self.kernel_sizes)
sigma = np.random.uniform(self.low_sigma, self.high_sigma)
gamma = np.random.uniform(self.low_gamma, self.high_gamma)
R_blur = R_
kernel = cv2.getGaussianKernel(11, sigma)
kernel2d = np.dot(kernel, kernel.T)
for i in range(3):
R_blur[..., i] = convolve2d(R_blur[..., i], kernel2d, mode='same')
M_ = B_ * 0.5 + R_blur * 0.5
return B_.astype(np.float32), R_blur.astype(np.float32), M_.astype(np.float32)
class NoiseReflectionSythesisTorch(object):
"""Reflection image data synthesis for weakly-supervised learning
of ICCV 2017 paper *"A Generic Deep Architecture for Single Image Reflection Removal and Image Smoothing"*
"""
def __init__(self, kernel_sizes=None, low_sigma=2, high_sigma=5, low_gamma=1.3, high_gamma=1.3):
self.kernel_sizes = kernel_sizes or [11]
self.low_sigma = low_sigma
self.high_sigma = high_sigma
self.low_gamma = low_gamma
self.high_gamma = high_gamma
print('[i] reflection sythesis model: {}'.format({
'kernel_sizes': kernel_sizes, 'low_sigma': low_sigma, 'high_sigma': high_sigma,
'low_gamma': low_gamma, 'high_gamma': high_gamma}))
def __call__(self, B, R):
stdN = np.random.uniform(15, 55)
noise = torch.zeros(B.size()).normal_(mean=0, std=stdN / 255.)
B = B + noise
sigma = np.random.uniform(self.low_sigma, self.high_sigma)
R = kornia.gaussian_blur2d(R.unsqueeze(0), (11, 11), (sigma, sigma), border_type='replicate').squeeze(0)
M = B * 0.5 + R * 0.5
return B, R, M
class Sobel(object):
def __call__(self, img):
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
gray_img = np.array(img.convert('L'))
x = cv2.Sobel(gray_img, cv2.CV_16S, 1, 0)
y = cv2.Sobel(gray_img, cv2.CV_16S, 0, 1)
absX = cv2.convertScaleAbs(x)
absY = cv2.convertScaleAbs(y)
dst = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
return Image.fromarray(dst)
class ReflectionSythesis_2(object):
"""Reflection image data synthesis for weakly-supervised learning
of CVPR 2018 paper *"Single Image Reflection Separation with Perceptual Losses"*
"""
def __init__(self, kernel_sizes=None):
self.kernel_sizes = kernel_sizes or np.linspace(1, 5, 80)
@staticmethod
def gkern(kernlen=100, nsig=1):
"""Returns a 2D Gaussian kernel array."""
interval = (2 * nsig + 1.) / (kernlen)
x = np.linspace(-nsig - interval / 2., nsig + interval / 2., kernlen + 1)
kern1d = np.diff(st.norm.cdf(x))
kernel_raw = np.sqrt(np.outer(kern1d, kern1d))
kernel = kernel_raw / kernel_raw.sum()
kernel = kernel / kernel.max()
return kernel
def __call__(self, t, r):
t = np.float32(t) / 255.
r = np.float32(r) / 255.
ori_t = t
# create a vignetting mask
g_mask = self.gkern(560, 3)
g_mask = np.dstack((g_mask, g_mask, g_mask))
sigma = self.kernel_sizes[np.random.randint(0, len(self.kernel_sizes))]
t = np.power(t, 2.2)
r = np.power(r, 2.2)
sz = int(2 * np.ceil(2 * sigma) + 1)
r_blur = cv2.GaussianBlur(r, (sz, sz), sigma, sigma, 0)
blend = r_blur + t
att = 1.08 + np.random.random() / 10.0
for i in range(3):
maski = blend[:, :, i] > 1
mean_i = max(1., np.sum(blend[:, :, i] * maski) / (maski.sum() + 1e-6))
r_blur[:, :, i] = r_blur[:, :, i] - (mean_i - 1) * att
r_blur[r_blur >= 1] = 1
r_blur[r_blur <= 0] = 0
h, w = r_blur.shape[0:2]
neww = np.random.randint(0, 560 - w - 10)
newh = np.random.randint(0, 560 - h - 10)
alpha1 = g_mask[newh:newh + h, neww:neww + w, :]
alpha2 = 1 - np.random.random() / 5.0
r_blur_mask = np.multiply(r_blur, alpha1)
blend = r_blur_mask + t * alpha2
t = np.power(t, 1 / 2.2)
r_blur_mask = np.power(r_blur_mask, 1 / 2.2)
blend = np.power(blend, 1 / 2.2)
blend[blend >= 1] = 1
blend[blend <= 0] = 0
return np.float32(ori_t), np.float32(r_blur_mask), np.float32(blend)
# Examples
if __name__ == '__main__':
"""cv2 imread"""
# img = cv2.imread('testdata_reflection_real/19-input.png')
# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# img2 = cv2.GaussianBlur(img, (11,11), 3)
"""Sobel Operator"""
# img = np.array(Image.open('datasets/VOC224/train/B/2007_000250.png').convert('L'))
"""Reflection Sythesis"""
b = Image.open('')
r = Image.open('')
G = ReflectionSythesis_0()
m, r = G(b, r)
r.show()
|