seeds.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/env python
  2. '''
  3. This sample demonstrates SEEDS Superpixels segmentation
  4. Use [space] to toggle output mode
  5. Usage:
  6. seeds.py [<video source>]
  7. '''
  8. import numpy as np
  9. import cv2 as cv
  10. # relative module
  11. import video
  12. # built-in module
  13. import sys
  14. if __name__ == '__main__':
  15. print __doc__
  16. try:
  17. fn = sys.argv[1]
  18. except:
  19. fn = 0
  20. def nothing(*arg):
  21. pass
  22. cv.namedWindow('SEEDS')
  23. cv.createTrackbar('Number of Superpixels', 'SEEDS', 400, 1000, nothing)
  24. cv.createTrackbar('Iterations', 'SEEDS', 4, 12, nothing)
  25. seeds = None
  26. display_mode = 0
  27. num_superpixels = 400
  28. prior = 2
  29. num_levels = 4
  30. num_histogram_bins = 5
  31. cap = video.create_capture(fn)
  32. while True:
  33. flag, img = cap.read()
  34. converted_img = cv.cvtColor(img, cv.COLOR_BGR2HSV)
  35. height,width,channels = converted_img.shape
  36. num_superpixels_new = cv.getTrackbarPos('Number of Superpixels', 'SEEDS')
  37. num_iterations = cv.getTrackbarPos('Iterations', 'SEEDS')
  38. if not seeds or num_superpixels_new != num_superpixels:
  39. num_superpixels = num_superpixels_new
  40. seeds = cv.ximgproc.createSuperpixelSEEDS(width, height, channels,
  41. num_superpixels, num_levels, prior, num_histogram_bins)
  42. color_img = np.zeros((height,width,3), np.uint8)
  43. color_img[:] = (0, 0, 255)
  44. seeds.iterate(converted_img, num_iterations)
  45. # retrieve the segmentation result
  46. labels = seeds.getLabels()
  47. # labels output: use the last x bits to determine the color
  48. num_label_bits = 2
  49. labels &= (1<<num_label_bits)-1
  50. labels *= 1<<(16-num_label_bits)
  51. mask = seeds.getLabelContourMask(False)
  52. # stitch foreground & background together
  53. mask_inv = cv.bitwise_not(mask)
  54. result_bg = cv.bitwise_and(img, img, mask=mask_inv)
  55. result_fg = cv.bitwise_and(color_img, color_img, mask=mask)
  56. result = cv.add(result_bg, result_fg)
  57. if display_mode == 0:
  58. cv.imshow('SEEDS', result)
  59. elif display_mode == 1:
  60. cv.imshow('SEEDS', mask)
  61. else:
  62. cv.imshow('SEEDS', labels)
  63. ch = cv.waitKey(1)
  64. if ch == 27:
  65. break
  66. elif ch & 0xff == ord(' '):
  67. display_mode = (display_mode + 1) % 3
  68. cv.destroyAllWindows()