1from __future__ import print_function
2from __future__ import division
3import cv2 as cv
4import numpy as np
5import argparse
6
7def Hist_and_Backproj(val):
8    ## [initialize]
9    bins = val
10    histSize = max(bins, 2)
11    ranges = [0, 180] # hue_range
12    ## [initialize]
13
14    ## [Get the Histogram and normalize it]
15    hist = cv.calcHist([hue], [0], None, [histSize], ranges, accumulate=False)
16    cv.normalize(hist, hist, alpha=0, beta=255, norm_type=cv.NORM_MINMAX)
17    ## [Get the Histogram and normalize it]
18
19    ## [Get Backprojection]
20    backproj = cv.calcBackProject([hue], [0], hist, ranges, scale=1)
21    ## [Get Backprojection]
22
23    ## [Draw the backproj]
24    cv.imshow('BackProj', backproj)
25    ## [Draw the backproj]
26
27    ## [Draw the histogram]
28    w = 400
29    h = 400
30    bin_w = int(round(w / histSize))
31    histImg = np.zeros((h, w, 3), dtype=np.uint8)
32
33    for i in range(bins):
34        cv.rectangle(histImg, (i*bin_w, h), ( (i+1)*bin_w, h - int(np.round( hist[i]*h/255.0 )) ), (0, 0, 255), cv.FILLED)
35
36    cv.imshow('Histogram', histImg)
37    ## [Draw the histogram]
38
39## [Read the image]
40parser = argparse.ArgumentParser(description='Code for Back Projection tutorial.')
41parser.add_argument('--input', help='Path to input image.', default='home.jpg')
42args = parser.parse_args()
43
44src = cv.imread(cv.samples.findFile(args.input))
45if src is None:
46    print('Could not open or find the image:', args.input)
47    exit(0)
48## [Read the image]
49
50## [Transform it to HSV]
51hsv = cv.cvtColor(src, cv.COLOR_BGR2HSV)
52## [Transform it to HSV]
53
54## [Use only the Hue value]
55ch = (0, 0)
56hue = np.empty(hsv.shape, hsv.dtype)
57cv.mixChannels([hsv], [hue], ch)
58## [Use only the Hue value]
59
60## [Create Trackbar to enter the number of bins]
61window_image = 'Source image'
62cv.namedWindow(window_image)
63bins = 25
64cv.createTrackbar('* Hue  bins: ', window_image, bins, 180, Hist_and_Backproj )
65Hist_and_Backproj(bins)
66## [Create Trackbar to enter the number of bins]
67
68## [Show the image]
69cv.imshow(window_image, src)
70cv.waitKey()
71## [Show the image]
72