hist.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. #!/usr/bin/env python
  2. ''' This is a sample for histogram plotting for RGB images and grayscale images for better understanding of colour distribution
  3. Benefit : Learn how to draw histogram of images
  4. Get familier with cv.calcHist, cv.equalizeHist,cv.normalize and some drawing functions
  5. Level : Beginner or Intermediate
  6. Functions : 1) hist_curve : returns histogram of an image drawn as curves
  7. 2) hist_lines : return histogram of an image drawn as bins ( only for grayscale images )
  8. Usage : python hist.py <image_file>
  9. Abid Rahman 3/14/12 debug Gary Bradski
  10. '''
  11. # Python 2/3 compatibility
  12. from __future__ import print_function
  13. import numpy as np
  14. import cv2 as cv
  15. bins = np.arange(256).reshape(256,1)
  16. def hist_curve(im):
  17. h = np.zeros((300,256,3))
  18. if len(im.shape) == 2:
  19. color = [(255,255,255)]
  20. elif im.shape[2] == 3:
  21. color = [ (255,0,0),(0,255,0),(0,0,255) ]
  22. for ch, col in enumerate(color):
  23. hist_item = cv.calcHist([im],[ch],None,[256],[0,256])
  24. cv.normalize(hist_item,hist_item,0,255,cv.NORM_MINMAX)
  25. hist=np.int32(np.around(hist_item))
  26. pts = np.int32(np.column_stack((bins,hist)))
  27. cv.polylines(h,[pts],False,col)
  28. y=np.flipud(h)
  29. return y
  30. def hist_lines(im):
  31. h = np.zeros((300,256,3))
  32. if len(im.shape)!=2:
  33. print("hist_lines applicable only for grayscale images")
  34. #print("so converting image to grayscale for representation"
  35. im = cv.cvtColor(im,cv.COLOR_BGR2GRAY)
  36. hist_item = cv.calcHist([im],[0],None,[256],[0,256])
  37. cv.normalize(hist_item,hist_item,0,255,cv.NORM_MINMAX)
  38. hist = np.int32(np.around(hist_item))
  39. for x,y in enumerate(hist):
  40. cv.line(h,(x,0),(x,y[0]),(255,255,255))
  41. y = np.flipud(h)
  42. return y
  43. def main():
  44. import sys
  45. if len(sys.argv)>1:
  46. fname = sys.argv[1]
  47. else :
  48. fname = 'lena.jpg'
  49. print("usage : python hist.py <image_file>")
  50. im = cv.imread(cv.samples.findFile(fname))
  51. if im is None:
  52. print('Failed to load image file:', fname)
  53. sys.exit(1)
  54. gray = cv.cvtColor(im,cv.COLOR_BGR2GRAY)
  55. print(''' Histogram plotting \n
  56. Keymap :\n
  57. a - show histogram for color image in curve mode \n
  58. b - show histogram in bin mode \n
  59. c - show equalized histogram (always in bin mode) \n
  60. d - show histogram for gray image in curve mode \n
  61. e - show histogram for a normalized image in curve mode \n
  62. Esc - exit \n
  63. ''')
  64. cv.imshow('image',im)
  65. while True:
  66. k = cv.waitKey(0)
  67. if k == ord('a'):
  68. curve = hist_curve(im)
  69. cv.imshow('histogram',curve)
  70. cv.imshow('image',im)
  71. print('a')
  72. elif k == ord('b'):
  73. print('b')
  74. lines = hist_lines(im)
  75. cv.imshow('histogram',lines)
  76. cv.imshow('image',gray)
  77. elif k == ord('c'):
  78. print('c')
  79. equ = cv.equalizeHist(gray)
  80. lines = hist_lines(equ)
  81. cv.imshow('histogram',lines)
  82. cv.imshow('image',equ)
  83. elif k == ord('d'):
  84. print('d')
  85. curve = hist_curve(gray)
  86. cv.imshow('histogram',curve)
  87. cv.imshow('image',gray)
  88. elif k == ord('e'):
  89. print('e')
  90. norm = cv.normalize(gray, gray, alpha = 0,beta = 255,norm_type = cv.NORM_MINMAX)
  91. lines = hist_lines(norm)
  92. cv.imshow('histogram',lines)
  93. cv.imshow('image',norm)
  94. elif k == 27:
  95. print('ESC')
  96. cv.destroyAllWindows()
  97. break
  98. print('Done')
  99. if __name__ == '__main__':
  100. print(__doc__)
  101. main()
  102. cv.destroyAllWindows()