hist.py 3.61 KB
Newer Older
1
#!/usr/bin/env python
2

3 4 5
''' This is a sample for histogram plotting for RGB images and grayscale images for better understanding of colour distribution

Benefit : Learn how to draw histogram of images
6
          Get familier with cv.calcHist, cv.equalizeHist,cv.normalize and some drawing functions
7 8 9 10 11 12 13 14 15 16 17

Level : Beginner or Intermediate

Functions : 1) hist_curve : returns histogram of an image drawn as curves
            2) hist_lines : return histogram of an image drawn as bins ( only for grayscale images )

Usage : python hist.py <image_file>

Abid Rahman 3/14/12 debug Gary Bradski
'''

18 19 20
# Python 2/3 compatibility
from __future__ import print_function

21
import numpy as np
22
import cv2 as cv
23 24 25 26 27 28 29 30 31 32

bins = np.arange(256).reshape(256,1)

def hist_curve(im):
    h = np.zeros((300,256,3))
    if len(im.shape) == 2:
        color = [(255,255,255)]
    elif im.shape[2] == 3:
        color = [ (255,0,0),(0,255,0),(0,0,255) ]
    for ch, col in enumerate(color):
33 34
        hist_item = cv.calcHist([im],[ch],None,[256],[0,256])
        cv.normalize(hist_item,hist_item,0,255,cv.NORM_MINMAX)
35 36
        hist=np.int32(np.around(hist_item))
        pts = np.int32(np.column_stack((bins,hist)))
37
        cv.polylines(h,[pts],False,col)
38 39 40 41 42 43
    y=np.flipud(h)
    return y

def hist_lines(im):
    h = np.zeros((300,256,3))
    if len(im.shape)!=2:
44 45
        print("hist_lines applicable only for grayscale images")
        #print("so converting image to grayscale for representation"
46 47 48
        im = cv.cvtColor(im,cv.COLOR_BGR2GRAY)
    hist_item = cv.calcHist([im],[0],None,[256],[0,256])
    cv.normalize(hist_item,hist_item,0,255,cv.NORM_MINMAX)
49 50
    hist=np.int32(np.around(hist_item))
    for x,y in enumerate(hist):
51
        cv.line(h,(x,0),(x,y),(255,255,255))
52 53 54 55
    y = np.flipud(h)
    return y


56
def main():
57 58 59
    import sys

    if len(sys.argv)>1:
60
        fname = sys.argv[1]
61
    else :
62
        fname = 'lena.jpg'
63
        print("usage : python hist.py <image_file>")
64

65
    im = cv.imread(cv.samples.findFile(fname))
66

67
    if im is None:
68
        print('Failed to load image file:', fname)
69
        sys.exit(1)
70

71
    gray = cv.cvtColor(im,cv.COLOR_BGR2GRAY)
72 73


74
    print(''' Histogram plotting \n
75 76 77 78 79 80 81
    Keymap :\n
    a - show histogram for color image in curve mode \n
    b - show histogram in bin mode \n
    c - show equalized histogram (always in bin mode) \n
    d - show histogram for color image in curve mode \n
    e - show histogram for a normalized image in curve mode \n
    Esc - exit \n
82
    ''')
83

84
    cv.imshow('image',im)
85
    while True:
86
        k = cv.waitKey(0)
87 88
        if k == ord('a'):
            curve = hist_curve(im)
89 90
            cv.imshow('histogram',curve)
            cv.imshow('image',im)
91
            print('a')
92
        elif k == ord('b'):
93
            print('b')
94
            lines = hist_lines(im)
95 96
            cv.imshow('histogram',lines)
            cv.imshow('image',gray)
97
        elif k == ord('c'):
98
            print('c')
99
            equ = cv.equalizeHist(gray)
100
            lines = hist_lines(equ)
101 102
            cv.imshow('histogram',lines)
            cv.imshow('image',equ)
103
        elif k == ord('d'):
104
            print('d')
105
            curve = hist_curve(gray)
106 107
            cv.imshow('histogram',curve)
            cv.imshow('image',gray)
108
        elif k == ord('e'):
109
            print('e')
110
            norm = cv.normalize(gray, gray, alpha = 0,beta = 255,norm_type = cv.NORM_MINMAX)
111
            lines = hist_lines(norm)
112 113
            cv.imshow('histogram',lines)
            cv.imshow('image',norm)
114
        elif k == 27:
115
            print('ESC')
116
            cv.destroyAllWindows()
117
            break
118 119 120 121 122 123 124

    print('Done')


if __name__ == '__main__':
    print(__doc__)
    main()
125
    cv.destroyAllWindows()