hist.py 3.54 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 cv2 as cv
22 23 24 25 26 27 28 29 30 31 32
import numpy as np

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 56 57 58 59 60
    y = np.flipud(h)
    return y


if __name__ == '__main__':

    import sys

    if len(sys.argv)>1:
61
        fname = sys.argv[1]
62
    else :
Dmitriy Anisimov's avatar
Dmitriy Anisimov committed
63
        fname = '../data/lena.jpg'
64
        print("usage : python hist.py <image_file>")
65

66
    im = cv.imread(fname)
67

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

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


75
    print(''' Histogram plotting \n
76 77 78 79 80 81 82
    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
83
    ''')
84

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