Background-Blurring.py 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from torchvision import models
  2. from PIL import Image, ImageFilter
  3. import matplotlib.pyplot as plt
  4. import torch
  5. import numpy as np
  6. import cv2
  7. # Apply the transformations needed
  8. import torchvision.transforms as T
  9. # Define the helper function
  10. def decode_segmap(image, source, nc=21):
  11. label_colors = np.array([(0, 0, 0), # 0=background
  12. # 1=aeroplane, 2=bicycle, 3=bird, 4=boat, 5=bottle
  13. (128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (128, 0, 128),
  14. # 6=bus, 7=car, 8=cat, 9=chair, 10=cow
  15. (0, 128, 128), (128, 128, 128), (64, 0, 0), (192, 0, 0), (64, 128, 0),
  16. # 11=dining table, 12=dog, 13=horse, 14=motorbike, 15=person
  17. (192, 128, 0), (64, 0, 128), (192, 0, 128), (64, 128, 128), (192, 128, 128),
  18. # 16=potted plant, 17=sheep, 18=sofa, 19=train, 20=tv/monitor
  19. (0, 64, 0), (128, 64, 0), (0, 192, 0), (128, 192, 0), (0, 64, 128)])
  20. r = np.zeros_like(image).astype(np.uint8)
  21. g = np.zeros_like(image).astype(np.uint8)
  22. b = np.zeros_like(image).astype(np.uint8)
  23. for l in range(0, nc):
  24. idx = image == l
  25. r[idx] = label_colors[l, 0]
  26. g[idx] = label_colors[l, 1]
  27. b[idx] = label_colors[l, 2]
  28. rgb = np.stack([r, g, b], axis=2)
  29. # Load the foreground input image
  30. foreground = cv2.imread(source)
  31. # Change the color of foreground image to RGB
  32. # and resize image to match shape of R-band in RGB output map
  33. foreground = cv2.cvtColor(foreground, cv2.COLOR_BGR2RGB)
  34. foreground = cv2.resize(foreground,(r.shape[1],r.shape[0]))
  35. # Create a Gaussian blur of kernel size 7 for the background image
  36. blurredImage = cv2.GaussianBlur(foreground, (7,7), 0)
  37. # Convert uint8 to float
  38. foreground = foreground.astype(float)
  39. blurredImage = blurredImage.astype(float)
  40. # Create a binary mask of the RGB output map using the threshold value 0
  41. th, alpha = cv2.threshold(np.array(rgb),0,255, cv2.THRESH_BINARY)
  42. # Apply a slight blur to the mask to soften edges
  43. alpha = cv2.GaussianBlur(alpha, (7,7),0)
  44. # Normalize the alpha mask to keep intensity between 0 and 1
  45. alpha = alpha.astype(float)/255
  46. # Multiply the foreground with the alpha matte
  47. foreground = cv2.multiply(alpha, foreground)
  48. # Multiply the background with ( 1 - alpha )
  49. background = cv2.multiply(1.0 - alpha, blurredImage)
  50. # Add the masked foreground and background
  51. outImage = cv2.add(foreground, background)
  52. # Return a normalized output image for display
  53. return outImage/255
  54. def segment(net, path, show_orig=True, dev='cuda'):
  55. img = Image.open(path)
  56. if show_orig: plt.imshow(img); plt.axis('off'); plt.show()
  57. # Comment the Resize and CenterCrop for better inference results
  58. trf = T.Compose([T.Resize(450),
  59. #T.CenterCrop(224),
  60. T.ToTensor(),
  61. T.Normalize(mean = [0.485, 0.456, 0.406],
  62. std = [0.229, 0.224, 0.225])])
  63. inp = trf(img).unsqueeze(0).to(dev)
  64. out = net.to(dev)(inp)['out']
  65. om = torch.argmax(out.squeeze(), dim=0).detach().cpu().numpy()
  66. rgb = decode_segmap(om, path)
  67. plt.imshow(rgb); plt.axis('off'); plt.show()
  68. dlab = models.segmentation.deeplabv3_resnet101(pretrained=1).eval()
  69. segment(dlab, './images/blur/girl.png', show_orig=False)
  70. segment(dlab, './images/blur/boy.png', show_orig=False)