image_proc.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import random
  2. from PIL import Image, ImageEnhance
  3. import numpy as np
  4. import cv2
  5. import torch
  6. from torchvision import transforms
  7. ## CPU version refinement
  8. def FB_blur_fusion_foreground_estimator_cpu(image, FG, B, alpha, r=90):
  9. if isinstance(image, Image.Image):
  10. image = np.array(image) / 255.0
  11. blurred_alpha = cv2.blur(alpha, (r, r))[:, :, None]
  12. blurred_FGA = cv2.blur(FG * alpha, (r, r))
  13. blurred_FG = blurred_FGA / (blurred_alpha + 1e-5)
  14. blurred_B1A = cv2.blur(B * (1 - alpha), (r, r))
  15. blurred_B = blurred_B1A / ((1 - blurred_alpha) + 1e-5)
  16. FG = blurred_FG + alpha * (image - alpha * blurred_FG - (1 - alpha) * blurred_B)
  17. FG = np.clip(FG, 0, 1)
  18. return FG, blurred_B
  19. def FB_blur_fusion_foreground_estimator_cpu_2(image, alpha, r=90):
  20. # Thanks to the source: https://github.com/Photoroom/fast-foreground-estimation
  21. alpha = alpha[:, :, None]
  22. FG, blur_B = FB_blur_fusion_foreground_estimator_cpu(image, image, image, alpha, r)
  23. return FB_blur_fusion_foreground_estimator_cpu(image, FG, blur_B, alpha, r=6)[0]
  24. ## GPU version refinement
  25. def mean_blur(x, kernel_size):
  26. """
  27. equivalent to cv.blur
  28. x: [B, C, H, W]
  29. """
  30. if kernel_size % 2 == 0:
  31. pad_l = kernel_size // 2 - 1
  32. pad_r = kernel_size // 2
  33. pad_t = kernel_size // 2 - 1
  34. pad_b = kernel_size // 2
  35. else:
  36. pad_l = pad_r = pad_t = pad_b = kernel_size // 2
  37. x_padded = torch.nn.functional.pad(x, (pad_l, pad_r, pad_t, pad_b), mode='replicate')
  38. return torch.nn.functional.avg_pool2d(x_padded, kernel_size=(kernel_size, kernel_size), stride=1, count_include_pad=False)
  39. def FB_blur_fusion_foreground_estimator_gpu(image, FG, B, alpha, r=90):
  40. as_dtype = lambda x, dtype: x.to(dtype) if x.dtype != dtype else x
  41. input_dtype = image.dtype
  42. # convert image to float to avoid overflow
  43. image = as_dtype(image, torch.float32)
  44. FG = as_dtype(FG, torch.float32)
  45. B = as_dtype(B, torch.float32)
  46. alpha = as_dtype(alpha, torch.float32)
  47. blurred_alpha = mean_blur(alpha, kernel_size=r)
  48. blurred_FGA = mean_blur(FG * alpha, kernel_size=r)
  49. blurred_FG = blurred_FGA / (blurred_alpha + 1e-5)
  50. blurred_B1A = mean_blur(B * (1 - alpha), kernel_size=r)
  51. blurred_B = blurred_B1A / ((1 - blurred_alpha) + 1e-5)
  52. FG_output = blurred_FG + alpha * (image - alpha * blurred_FG - (1 - alpha) * blurred_B)
  53. FG_output = torch.clamp(FG_output, 0, 1)
  54. return as_dtype(FG_output, input_dtype), as_dtype(blurred_B, input_dtype)
  55. def FB_blur_fusion_foreground_estimator_gpu_2(image, alpha, r=90):
  56. # Thanks to the source: https://github.com/ZhengPeng7/BiRefNet/issues/226#issuecomment-3016433728
  57. FG, blur_B = FB_blur_fusion_foreground_estimator_gpu(image, image, image, alpha, r)
  58. return FB_blur_fusion_foreground_estimator_gpu(image, FG, blur_B, alpha, r=6)[0]
  59. def refine_foreground(image, mask, r=90, device='cuda'):
  60. """both image and mask are in range of [0, 1]"""
  61. if mask.size != image.size:
  62. mask = mask.resize(image.size)
  63. if device == 'cuda':
  64. image = transforms.functional.to_tensor(image).float().cuda()
  65. mask = transforms.functional.to_tensor(mask).float().cuda()
  66. image = image.unsqueeze(0)
  67. mask = mask.unsqueeze(0)
  68. estimated_foreground = FB_blur_fusion_foreground_estimator_gpu_2(image, mask, r=r)
  69. estimated_foreground = estimated_foreground.squeeze()
  70. estimated_foreground = (estimated_foreground.mul(255.0)).to(torch.uint8)
  71. estimated_foreground = estimated_foreground.permute(1, 2, 0).contiguous().cpu().numpy().astype(np.uint8)
  72. else:
  73. image = np.array(image, dtype=np.float32) / 255.0
  74. mask = np.array(mask, dtype=np.float32) / 255.0
  75. estimated_foreground = FB_blur_fusion_foreground_estimator_cpu_2(image, mask, r=r)
  76. estimated_foreground = (estimated_foreground * 255.0).astype(np.uint8)
  77. estimated_foreground = Image.fromarray(np.ascontiguousarray(estimated_foreground))
  78. return estimated_foreground
  79. def preproc(image, label, preproc_methods=['flip']):
  80. if 'flip' in preproc_methods:
  81. image, label = cv_random_flip(image, label)
  82. if 'crop' in preproc_methods:
  83. image, label = random_crop(image, label)
  84. if 'rotate' in preproc_methods:
  85. image, label = random_rotate(image, label)
  86. if 'enhance' in preproc_methods:
  87. image = color_enhance(image)
  88. if 'pepper' in preproc_methods:
  89. image = random_pepper(image)
  90. return image, label
  91. def cv_random_flip(img, label):
  92. if random.random() > 0.5:
  93. img = img.transpose(Image.FLIP_LEFT_RIGHT)
  94. label = label.transpose(Image.FLIP_LEFT_RIGHT)
  95. return img, label
  96. def random_crop(image, label):
  97. border = 30
  98. image_width = image.size[0]
  99. image_height = image.size[1]
  100. border = int(min(image_width, image_height) * 0.1)
  101. crop_win_width = np.random.randint(image_width - border, image_width)
  102. crop_win_height = np.random.randint(image_height - border, image_height)
  103. random_region = (
  104. (image_width - crop_win_width) >> 1, (image_height - crop_win_height) >> 1, (image_width + crop_win_width) >> 1,
  105. (image_height + crop_win_height) >> 1)
  106. return image.crop(random_region), label.crop(random_region)
  107. def random_rotate(image, label, angle=15):
  108. mode = Image.BICUBIC
  109. if random.random() > 0.8:
  110. random_angle = np.random.randint(-angle, angle)
  111. image = image.rotate(random_angle, mode)
  112. label = label.rotate(random_angle, mode)
  113. return image, label
  114. def color_enhance(image):
  115. bright_intensity = random.randint(5, 15) / 10.0
  116. image = ImageEnhance.Brightness(image).enhance(bright_intensity)
  117. contrast_intensity = random.randint(5, 15) / 10.0
  118. image = ImageEnhance.Contrast(image).enhance(contrast_intensity)
  119. color_intensity = random.randint(0, 20) / 10.0
  120. image = ImageEnhance.Color(image).enhance(color_intensity)
  121. sharp_intensity = random.randint(0, 30) / 10.0
  122. image = ImageEnhance.Sharpness(image).enhance(sharp_intensity)
  123. return image
  124. def random_gaussian(image, mean=0.1, sigma=0.35):
  125. def gaussianNoisy(im, mean=mean, sigma=sigma):
  126. for _i in range(len(im)):
  127. im[_i] += random.gauss(mean, sigma)
  128. return im
  129. img = np.asarray(image)
  130. width, height = img.shape
  131. img = gaussianNoisy(img[:].flatten(), mean, sigma)
  132. img = img.reshape([width, height])
  133. return Image.fromarray(np.uint8(img))
  134. def random_pepper(img, N=0.0015):
  135. img = np.array(img)
  136. noiseNum = int(N * img.shape[0] * img.shape[1])
  137. for i in range(noiseNum):
  138. randX = random.randint(0, img.shape[0] - 1)
  139. randY = random.randint(0, img.shape[1] - 1)
  140. img[randX, randY] = random.randint(0, 1) * 255
  141. return Image.fromarray(img)