BayesOpt
demo_cam.py
1 #!/usr/bin/env python
2 # -------------------------------------------------------------------------
3 # This file is part of BayesOpt, an efficient C++ library for
4 # Bayesian optimization.
5 #
6 # Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>
7 #
8 # BayesOpt is free software: you can redistribute it and/or modify it
9 # under the terms of the GNU Affero General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # BayesOpt is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU Affero General Public License for more details.
17 #
18 # You should have received a copy of the GNU Affero General Public License
19 # along with BayesOpt. If not, see <http://www.gnu.org/licenses/>.
20 # ------------------------------------------------------------------------
21 
22 import sys
23 from SimpleCV import Camera
24 import numpy as np
25 import bayesopt
26 from time import sleep
27 
28 # Python3 compat
29 if sys.version_info[0] == 3:
30  raw_input = input
31 
32 # Initialize the camera
33 cam = Camera()
34 cost = np.zeros(256)
35 
36 #Load images
37 img = cam.getImage().scale(400,400)
38 img2 = img.binarize()
39 
40 
41 def costImage(i):
42  # Make image black and white
43  img1 = img.binarize(int(i))
44  mat = img1.getNumpy()
45  countW = np.count_nonzero(mat);
46  countB = mat.size-countW
47  return ((countW-countB)/float(mat.size))**2
48 
49 params = {} #bayesopt.initialize_params()
50 params['n_iterations'] = 15
51 params['n_init_samples'] = 5
52 
53 valid_values = np.transpose(np.array(range(256), dtype=float, ndmin=2))
54 mvalue, x_out, error = bayesopt.optimize_discrete(costImage,
55  valid_values, params)
56 
57 x_out = int(x_out)
58 print(x_out)
59 img1 = img.binarize(x_out)
60 
61 img1 = img.sideBySide(img1).sideBySide(img2)
62 img1.drawText("Threshold: "+str(x_out))
63 img1.show()
64 
65 foo = raw_input('Press any key')