inpaint.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import numpy as np
  2. import cv2 as cv
  3. import sys
  4. # OpenCV Utility Class for Mouse Handling
  5. class Sketcher:
  6. def __init__(self, windowname, dests, colors_func):
  7. self.prev_pt = None
  8. self.windowname = windowname
  9. self.dests = dests
  10. self.colors_func = colors_func
  11. self.dirty = False
  12. self.show()
  13. cv.setMouseCallback(self.windowname, self.on_mouse)
  14. def show(self):
  15. cv.imshow(self.windowname, self.dests[0])
  16. cv.imshow(self.windowname + ": mask", self.dests[1])
  17. # onMouse function for Mouse Handling
  18. def on_mouse(self, event, x, y, flags, param):
  19. pt = (x, y)
  20. if event == cv.EVENT_LBUTTONDOWN:
  21. self.prev_pt = pt
  22. elif event == cv.EVENT_LBUTTONUP:
  23. self.prev_pt = None
  24. if self.prev_pt and flags & cv.EVENT_FLAG_LBUTTON:
  25. for dst, color in zip(self.dests, self.colors_func()):
  26. cv.line(dst, self.prev_pt, pt, color, 5)
  27. self.dirty = True
  28. self.prev_pt = pt
  29. self.show()
  30. def main():
  31. print("Usage: python inpaint <image_path>")
  32. print("Keys: ")
  33. print("t - inpaint using FMM")
  34. print("n - inpaint using NS technique")
  35. print("r - reset the inpainting mask")
  36. print("ESC - exit")
  37. # Read image in color mode
  38. img = cv.imread(sys.argv[1], cv.IMREAD_COLOR)
  39. # If image is not read properly, return error
  40. if img is None:
  41. print('Failed to load image file: {}'.format(args["image"]))
  42. return
  43. # Create a copy of original image
  44. img_mask = img.copy()
  45. # Create a black copy of original image
  46. # Acts as a mask
  47. inpaintMask = np.zeros(img.shape[:2], np.uint8)
  48. # Create sketch using OpenCV Utility Class: Sketcher
  49. sketch = Sketcher('image', [img_mask, inpaintMask], lambda : ((255, 255, 255), 255))
  50. while True:
  51. ch = cv.waitKey()
  52. if ch == 27:
  53. break
  54. if ch == ord('t'):
  55. # Use Algorithm proposed by Alexendra Telea: Fast Marching Method (2004)
  56. # Reference: https://pdfs.semanticscholar.org/622d/5f432e515da69f8f220fb92b17c8426d0427.pdf
  57. res = cv.inpaint(src=img_mask, inpaintMask=inpaintMask, inpaintRadius=3, flags=cv.INPAINT_TELEA)
  58. cv.imshow('Inpaint Output using FMM', res)
  59. if ch == ord('n'):
  60. # Use Algorithm proposed by Bertalmio, Marcelo, Andrea L. Bertozzi, and Guillermo Sapiro: Navier-Stokes, Fluid Dynamics, and Image and Video Inpainting (2001)
  61. res = cv.inpaint(src=img_mask, inpaintMask=inpaintMask, inpaintRadius=3, flags=cv.INPAINT_NS)
  62. cv.imshow('Inpaint Output using NS Technique', res)
  63. if ch == ord('r'):
  64. img_mask[:] = img
  65. inpaintMask[:] = 0
  66. sketch.show()
  67. print('Completed')
  68. if __name__ == '__main__':
  69. main()
  70. cv.destroyAllWindows()