Background-Removal.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. from torchvision import models
  2. from PIL import Image
  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 background array to hold white pixels
  36. # with the same size as RGB output map
  37. background = 255 * np.ones_like(rgb).astype(np.uint8)
  38. # Convert uint8 to float
  39. foreground = foreground.astype(float)
  40. background = background.astype(float)
  41. # Create a binary mask of the RGB output map using the threshold value 0
  42. th, alpha = cv2.threshold(np.array(rgb),0,255, cv2.THRESH_BINARY)
  43. # Apply a slight blur to the mask to soften edges
  44. alpha = cv2.GaussianBlur(alpha, (7,7),0)
  45. # Normalize the alpha mask to keep intensity between 0 and 1
  46. alpha = alpha.astype(float)/255
  47. # Multiply the foreground with the alpha matte
  48. foreground = cv2.multiply(alpha, foreground)
  49. # Multiply the background with ( 1 - alpha )
  50. background = cv2.multiply(1.0 - alpha, background)
  51. # Add the masked foreground and background
  52. outImage = cv2.add(foreground, background)
  53. # Return a normalized output image for display
  54. return outImage/255
  55. def segment(net, path, show_orig=True, dev='cuda'):
  56. img = Image.open(path)
  57. if show_orig: plt.imshow(img); plt.axis('off'); plt.show()
  58. # Comment the Resize and CenterCrop for better inference results
  59. trf = T.Compose([T.Resize(450),
  60. #T.CenterCrop(224),
  61. T.ToTensor(),
  62. T.Normalize(mean = [0.485, 0.456, 0.406],
  63. std = [0.229, 0.224, 0.225])])
  64. inp = trf(img).unsqueeze(0).to(dev)
  65. out = net.to(dev)(inp)['out']
  66. om = torch.argmax(out.squeeze(), dim=0).detach().cpu().numpy()
  67. rgb = decode_segmap(om, path)
  68. plt.imshow(rgb); plt.axis('off'); plt.show()
  69. dlab = models.segmentation.deeplabv3_resnet101(pretrained=1).eval()
  70. segment(dlab, './images/bgremoval/red-car.png', show_orig=False)