texture_flow.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env python
  2. '''
  3. Texture flow direction estimation.
  4. Sample shows how cv.cornerEigenValsAndVecs function can be used
  5. to estimate image texture flow direction.
  6. Usage:
  7. texture_flow.py [<image>]
  8. '''
  9. # Python 2/3 compatibility
  10. from __future__ import print_function
  11. import numpy as np
  12. import cv2 as cv
  13. def main():
  14. import sys
  15. try:
  16. fn = sys.argv[1]
  17. except:
  18. fn = 'starry_night.jpg'
  19. img = cv.imread(cv.samples.findFile(fn))
  20. if img is None:
  21. print('Failed to load image file:', fn)
  22. sys.exit(1)
  23. gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
  24. h, w = img.shape[:2]
  25. eigen = cv.cornerEigenValsAndVecs(gray, 15, 3)
  26. eigen = eigen.reshape(h, w, 3, 2) # [[e1, e2], v1, v2]
  27. flow = eigen[:,:,2]
  28. vis = img.copy()
  29. vis[:] = (192 + np.uint32(vis)) / 2
  30. d = 12
  31. points = np.dstack( np.mgrid[d/2:w:d, d/2:h:d] ).reshape(-1, 2)
  32. for x, y in np.int32(points):
  33. vx, vy = np.int32(flow[y, x]*d)
  34. cv.line(vis, (x-vx, y-vy), (x+vx, y+vy), (0, 0, 0), 1, cv.LINE_AA)
  35. cv.imshow('input', img)
  36. cv.imshow('flow', vis)
  37. cv.waitKey()
  38. print('Done')
  39. if __name__ == '__main__':
  40. print(__doc__)
  41. main()
  42. cv.destroyAllWindows()