code
stringlengths
1
1.49M
vector
listlengths
0
7.38k
snippet
listlengths
0
7.38k
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Code for sampling from various distributions, including some very specific situations involving Dirichlet processes... sampling_code = start_cpp() + """ #ifndef SAMPLING_CODE #define SAMPLING_CODE #include <stdlib.h> #include <math.h> const double gamma_approx = 32.0; // Threshold between the two methods of doing a gamma draw. // Returns a sample from the natural numbers [0,n)... int sample_nat(int n) { return lrand48()%n; } // Returns a sample from [0.0,1.0)... double sample_uniform() { return drand48(); //return double(random())/(double(RAND_MAX)+1.0); } // Samples from a normal distribution with a mean of 0 and a standard deviation of 1... double sample_standard_normal() { double u = 1.0-sample_uniform(); double v = 1.0-sample_uniform(); return sqrt(-2.0*log(u)) * cos(2.0*M_PI*v); } // Samples from a normal distribution with the given mean and standard deviation... double sample_normal(double mean, double sd) { return mean + sd*sample_standard_normal(); } // Samples from the Gamma distribution, base version that has no scaling parameter... /*double sample_gamma(double alpha) { // Check if the alpha value is high enough to approximate via a normal distribution... if (alpha>gamma_approx) { while (true) { double ret = sample_normal(alpha, sqrt(alpha)); if (ret<0.0) continue; return ret; } } // First do the integer part of gamma(alpha)... double ret = 0.0; // 1.0 while (alpha>=1.0) { alpha -= 1.0; //ret /= 1.0 - sample_uniform(); ret -= log(1.0-sample_uniform()); } //ret = log(ret); // Now do the remaining fractional part and sum it in - uses rejection sampling... if (alpha>1e-4) { while (true) { double u1 = 1.0 - sample_uniform(); double u2 = 1.0 - sample_uniform(); double u3 = 1.0 - sample_uniform(); double frac, point; if (u1<=(M_E/(M_E+alpha))) { frac = pow(u2,1.0/alpha); point = u3*pow(frac,alpha-1.0); } else { frac = 1.0 - log(u2); point = u3*exp(-frac); } if (point<=(pow(frac,alpha-1.0)*exp(-frac))) { ret += frac; break; } } } // Finally return... return ret; }*/ // As above, but faster... double sample_gamma(double alpha) { // Check if the alpha value is high enough to approximate via a normal distribution... if (alpha>gamma_approx) { while (true) { double ret = sample_normal(alpha, sqrt(alpha)); if (ret<0.0) continue; return ret; } } // If alpha is one, within tolerance, just use an exponential distribution... if (fabs(alpha-1.0)<1e-4) { return -log(1.0-sample_uniform()); } if (alpha>1.0) { // If alpha is 1 or greater use the Cheng/Feast method... while (true) { double u1 = sample_uniform(); double u2 = sample_uniform(); double v = ((alpha - 1.0/(6.0*alpha))*u1) / ((alpha-1.0)*u2); double lt2 = 2.0*(u2-1.0)/(alpha-1) + v + 1.0/v; if (lt2<=2.0) { return (alpha-1.0)*v; } double lt1 = 2.0*log(u2)/(alpha-1.0) - log(v) + v; if (lt1<=1.0) { return (alpha-1.0)*v; } } } else { // If alpha is less than 1 use a rejection sampling method... while (true) { double u1 = 1.0 - sample_uniform(); double u2 = 1.0 - sample_uniform(); double u3 = 1.0 - sample_uniform(); double frac, point; if (u1<=(M_E/(M_E+alpha))) { frac = pow(u2,1.0/alpha); point = u3*pow(frac,alpha-1.0); } else { frac = 1.0 - log(u2); point = u3*exp(-frac); } if (point<=(pow(frac,alpha-1.0)*exp(-frac))) { return frac; break; } } } } // Samples from the Gamma distribution, version that has a scaling parameter... double sample_gamma(double alpha, double beta) { return sample_gamma(alpha)/beta; } // Samples from the Beta distribution... double sample_beta(double alpha, double beta) { double g1 = sample_gamma(alpha); double g2 = sample_gamma(beta); return g1 / (g1 + g2); } #endif """
[ [ 1, 0, 0.0653, 0.005, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5452, 0.9146, 0, 0.66, 1, 31, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "sampling_code = start_cpp() + \"\"\"\n#ifndef SAMPLING_CODE\n#define SAMPLING_CODE\n\n#include <stdlib.h>\n#include <math.h>\n\nconst double gamma_approx = 32.0; // Threshold between the two methods of doing a gamma draw." ]
# Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp conc_code = start_cpp() + """ // This funky little function is used to resample the concentration parameter of a Dirichlet process, using the previous parameter - allows this parameter to be Gibbs sampled. Also works for any level of a HDP, due to the limited interactions. // Parameters are: // pcp - previous concentration parameter. // n - number of samples taken from the Dirichlet process // k - number of discretly different samples, i.e. table count in the Chinese restaurant process. // prior_alpha - alpha value of the Gamma prior on the concentration parameter. // prior_beta - beta value of the Gamma prior on the concentration parameter. double sample_dirichlet_proc_conc(double pcp, double n, double k, double prior_alpha = 1.01, double prior_beta = 0.01) { if ((n<(1.0-1e-6))||(k<(2.0-1e-6))) { return pcp; // Doesn't work in this case, so just repeat. } double nn = sample_beta(pcp+1.0, n); double log_nn = log(nn); double f_alpha = prior_alpha + k; double f_beta = prior_beta - log_nn; double pi_n_mod = (f_alpha - 1.0) / (n * f_beta); double r = sample_uniform(); double r_mod = r / (1.0 - r); if (r_mod>=pi_n_mod) f_alpha -= 1.0; double ret = sample_gamma(f_alpha, f_beta); if (ret<1e-3) ret = 1e-3; return ret; } // Class to represent the concentration parameter associated with a DP - consists of the prior and the previous/current value... struct Conc { float alpha; // Parameter for Gamma prior. float beta; // " float conc; // Previously sampled concentration value - needed for next sample, and for output/use. // Resamples the concentration value, assuming only a single DP is using it. n = number of samples from DP, k = number of unique samples, i.e. respectivly RefTotal() and Size() for a ListRef. void ResampleConc(int n, int k) { conc = sample_dirichlet_proc_conc(conc, n, k, alpha, beta); if (conc<1e-3) conc = 1e-3; } }; // This class is the generalisation of the above for when multiple Dirichlet processes share a single concentration parameter - again allows a new concentration parameter to be drawn given the previous one and a Gamma prior, but takes multiple pairs of sample count/discrete sample counts, hence the class interface to allow it to accumilate the relevant information. class SampleConcDP { public: SampleConcDP():f_alpha(1.0),f_beta(1.0),prev_conc(1.0) {} ~SampleConcDP() {} // Sets the prior and resets the entire class.... void SetPrior(double alpha, double beta) { f_alpha = alpha; f_beta = beta; } // Set the previous concetration parameter - must be called before any DP stats are added... void SetPrevConc(double prev) { prev_conc = prev; } // Call once for each DP that is using the concentration parameter... // (n is the number of samples drawn, k the number of discretly different samples.) void AddDP(double n, double k) { if (k>1.0) { double s = 0.0; if (sample_uniform()>(1.0/(1.0+n/prev_conc))) s = 1.0; double w = sample_beta(prev_conc+1.0,n); f_alpha += k - s; f_beta -= log(w); } } // Once all DP have been added call this to draw a new concentration value... double Sample() { double ret = sample_gamma(f_alpha, f_beta); if (ret<1e-3) ret = 1e-3; return ret; } private: double f_alpha; double f_beta; double prev_conc; }; """
[ [ 1, 0, 0.1121, 0.0086, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5733, 0.8621, 0, 0.66, 1, 983, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "conc_code = start_cpp() + \"\"\"\n\n// This funky little function is used to resample the concentration parameter of a Dirichlet process, using the previous parameter - allows this parameter to be Gibbs sampled. Also works for any level of a HDP, due to the limited intera...
# Copyright 2011 Tom SF Haines # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import numpy class FlagIndexArray: """Provides a register for flag lists - given a list of true/false flags gives a unique number for each combination. Requesting the numebr associated with a combination that has already been entered will always return the same number. All flag lists should be the same length and you can obtain a numpy matrix of {0,1} valued unsigned chars where each row corresponds to the flag list with that index. Also has a function to add the flags for each case of only one flag being on, which if called before anything else puts them so the index of the flag and the index of the flag list correspond - a trick required by the rest of the system.""" def __init__(self, length, addSingles = False): """Requires the length of the flag lists. Alternativly it can clone another FlagIndexArray. Will call the addSingles method for you if the flag is set.""" if isinstance(length, FlagIndexArray): self.length = length.length self.flags = dict(length.flags) else: self.length = length self.flags = dict() # Dictionary from flag lists to integers. Flag lists are represented with tuples of {0,1}. if addSingles: self.addSingles() def getLength(self): """Return the length that all flag lists should be.""" return self.length def addSingles(self): """Adds the entries where only a single flag is set, with the index of the flag list set to match the index of the flag that is set. Must be called first, before flagIndex is ever called.""" for i in xrange(self.length): t = tuple([0]*i + [1] + [0]*(self.length-(i+1))) self.flags[t] = i def flagIndex(self, flags, create = True): """Given a flag list returns its index - if it has been previously supplied then it will be the same index, otherwise a new one. Can be passed any entity that can be indexed via [] to get the integers {0,1}. Returns a natural. If the create flag is set to False in the event of a previously unseen flag list it will raise an exception instead of assigning it a new natural.""" f = [0]*self.length for i in xrange(self.length): if flags[i]!=0: f[i] = 1 f = tuple(f) if f in self.flags: return self.flags[f] if create==False: raise Exception('Unrecognised flag list') index = len(self.flags) self.flags[f] = index return index def addFlagIndexArray(self, fia, remap = None): """Given a flag index array this merges its flags into the new flags, returning a dictionary indexed by fia's indices that converts them to the new indices in self. remap is optionally a dictionary converting flag indices in fia to flag indexes in self - remap[fia index] = self index.""" def adjust(fi): fo = [0]*self.length for i in xrange(fia.length): fo[remap[i]] = fi[i] return tuple(fo) ret = dict() for f, index in fia.flags.iteritems(): if remap: f = adjust(f) ret[index] = self.flagIndex(f) return ret def flagCount(self): """Returns the number of flag lists that are in the system.""" return len(self.flags) def getFlagMatrix(self): """Returns a 2D numpy array of type numpy.uint8 containing {0,1}, indexed by [flag index,flag entry] - basically all the flags stacked into a single matrix and indexed by the entries returned by flagIndex. Often refered to as a 'flag index array' (fia).""" ret = numpy.zeros((len(self.flags),self.length), dtype=numpy.uint8) for flags,row in self.flags.iteritems(): for col in xrange(self.length): if flags[col]!=0: ret[row,col] = 1 return ret
[ [ 1, 0, 0.2143, 0.0119, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 3, 0, 0.631, 0.75, 0, 0.66, 1, 828, 0, 8, 0, 0, 0, 0, 21 ], [ 8, 1, 0.2738, 0.0119, 1, 0.38, ...
[ "import numpy", "class FlagIndexArray:\n \"\"\"Provides a register for flag lists - given a list of true/false flags gives a unique number for each combination. Requesting the numebr associated with a combination that has already been entered will always return the same number. All flag lists should be the same ...
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import math import random import numpy import numpy.linalg import numpy.random import scipy.special class Wishart: """Simple Wishart distribution class, quite basic really, but has caching to avoid duplicate computation.""" def __init__(self, dims): """dims is the number of dimensions - it initialises with the dof set to 1 and the scale set to the identity matrix. Has copy constructor support.""" if isinstance(dims, Wishart): self.dof = dims.dof self.scale = dims.scale.copy() self.invScale = dims.invScale.copy() if dims.invScale!=None else None self.norm = dims.norm self.cholesky = dims.cholesky.copy() if dims.cholesky!=None else None else: self.dof = 1.0 self.scale = numpy.identity(dims, dtype=numpy.float32) self.invScale = None self.norm = None self.cholesky = None def setDof(self, dof): """Sets the degrees of freedom of the distribution.""" self.dof = dof self.norm = None def setScale(self, scale): """Sets the scale matrix, must be symmetric positive definite""" ns = numpy.array(scale, dtype=numpy.float32) assert(ns.shape==self.scale.shape) self.scale = ns self.invScale = None self.norm = None self.cholesky = None def getDof(self): """Returns the degrees of freedom.""" return self.dof def getScale(self): """Returns the scale matrix.""" return self.scale def getInvScale(self): """Returns the inverse of the scale matrix.""" if self.invScale==None: self.invScale = numpy.linalg.inv(self.scale) return self.invScale def getNorm(self): """Returns the normalising constant of the distribution, typically not used by users.""" if self.norm==None: d = self.scale.shape[0] self.norm = math.pow(2.0,-0.5*self.dof*d) self.norm *= math.pow(numpy.linalg.det(self.scale),-0.5*self.dof) self.norm *= math.pow(math.pi,-0.25*d*(d-1)) for i in xrange(d): self.norm /= scipy.special.gamma(0.5*(n-i)) return self.norm def prob(self, mat): """Returns the probability of the provided matrix, which must be the same shape as the scale matrix and also symmetric and positive definite.""" d = self.scale.shape[0] val = math.pow(numpy.linalg.det(mat),0.5*(n-1-d)) val *= math.exp(-0.5 * numpy.linalg.trace(numpy.dot(mat,self.getInvScale()))) return self.getNorm() * val def sample(self): """Returns a draw from the distribution - will be a symmetric positive definite matrix.""" if self.cholesky==None: self.cholesky = numpy.linalg.cholesky(self.scale) d = self.scale.shape[0] a = numpy.zeros((d,d),dtype=numpy.float32) for r in xrange(d): if r!=0: a[r,:r] = numpy.random.normal(size=(r,)) a[r,r] = math.sqrt(random.gammavariate(0.5*(self.dof-d+1),2.0)) return numpy.dot(numpy.dot(numpy.dot(self.cholesky,a),a.T),self.cholesky.T) def __str__(self): return '{dof:%f, scale:%s}'%(self.dof, str(self.scale))
[ [ 1, 0, 0.13, 0.01, 0, 0.66, 0, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 1, 0, 0.14, 0.01, 0, 0.66, 0.1667, 715, 0, 1, 0, 0, 715, 0, 0 ], [ 1, 0, 0.15, 0.01, 0, 0.66, 0....
[ "import math", "import random", "import numpy", "import numpy.linalg", "import numpy.random", "import scipy.special", "class Wishart:\n \"\"\"Simple Wishart distribution class, quite basic really, but has caching to avoid duplicate computation.\"\"\"\n def __init__(self, dims):\n \"\"\"dims is the ...
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import math import numpy import numpy.linalg import scipy.special class StudentT: """A feature incomplete multivariate student-t distribution object - at this time it only supports calculating the probability of a sample, and not the ability to make a draw.""" def __init__(self, dims): """dims is the number of dimensions - initalises it to default values with the degrees of freedom set to 1, the location as the zero vector and the identity matrix for the scale. Suports copy construction.""" if isinstance(dims, StudentT): self.dof = dims.dof self.loc = dims.loc.copy() self.scale = dims.scale.copy() if dims.scale!=None else None self.invScale = dims.invScale.copy() if dims.invScale!=None else None self.norm = dims.norm.copy() if dims.norm!=None else None else: self.dof = 1.0 self.loc = numpy.zeros(dims, dtype=numpy.float32) self.scale = numpy.identity(dims, dtype=numpy.float32) self.invScale = None self.norm = None # Actually the log of the normalising constant. def setDOF(self, dof): """Sets the degrees of freedom.""" self.dof = dof self.norm = None def setLoc(self, loc): """Sets the location vector.""" l = numpy.array(loc, dtype=numpy.float32) assert(l.shape==self.loc.shape) self.loc = l def setScale(self, scale): """Sets the scale matrix.""" s = numpy.array(scale, dtype=numpy.float32) assert(s.shape==(self.loc.shape[0],self.loc.shape[0])) self.scale = s self.invScale = None self.norm = None def setInvScale(self, invScale): """Sets the scale matrix by providing its inverse.""" i = numpy.array(invScale, dtype=numpy.float32) assert(i.shape==(self.loc.shape[0],self.loc.shape[0])) self.scale = None self.invScale = i self.norm = None def getDOF(self): """Returns the degrees of freedom.""" return self.dof def getLoc(self): """Returns the location vector.""" return self.loc def getScale(self): """Returns the scale matrix.""" if self.scale==None: self.scale = numpy.linalg.inv(self.invScale) return self.scale def getInvScale(self): """Returns the inverse of the scale matrix.""" if self.invScale==None: self.invScale = numpy.linalg.inv(self.scale) return self.invScale def getLogNorm(self): """Returns the logarithm of the normalising constant of the distribution. Typically for internal use only.""" if self.norm==None: d = self.loc.shape[0] self.norm = scipy.special.gammaln(0.5*(self.dof+d)) self.norm -= scipy.special.gammaln(0.5*self.dof) self.norm -= math.log(self.dof*math.pi)*(0.5*d) self.norm += 0.5*math.log(numpy.linalg.det(self.getInvScale())) return self.norm def prob(self, x): """Given a vector x evaluates the density function at that point.""" x = numpy.asarray(x) d = self.loc.shape[0] delta = x - self.loc val = numpy.dot(delta,numpy.dot(self.getInvScale(),delta)) val = 1.0 + val/self.dof return math.exp(self.getLogNorm() + math.log(val)*(-0.5*(self.dof+d))) def logProb(self, x): """Returns the logarithm of prob - faster than a straight call to prob.""" x = numpy.asarray(x) d = self.loc.shape[0] delta = x - self.loc val = numpy.dot(delta,numpy.dot(self.getInvScale(),delta)) val = 1.0 + val/self.dof return self.getLogNorm() + math.log(val)*(-0.5*(self.dof+d)) def batchProb(self, dm): """Given a data matrix evaluates the density function for each entry and returns the resulting array of probabilities.""" d = self.loc.shape[0] delta = dm - self.loc.reshape((1,d)) if hasattr(numpy, 'einsum'): # Can go away when scipy older than 1.6 is no longer in use. val = numpy.einsum('kj,ij,ik->i', self.getInvScale(), delta, delta) else: val = ((self.getInvScale().reshape(1,d,d) * delta.reshape(dm.shape[0],1,d)).sum(axis=2) * delta).sum(axis=1) val = 1.0 + val/self.dof return numpy.exp(self.getLogNorm() + numpy.log(val)*(-0.5*(self.dof+d))) def batchLogProb(self, dm): """Same as batchProb, but returns the logarithm of the probability instead.""" d = self.loc.shape[0] delta = dm - self.loc.reshape((1,d)) if hasattr(numpy, 'einsum'): # Can go away when scipy older than 1.6 is no longer in use. val = numpy.einsum('kj,ij,ik->i', self.getInvScale(), delta, delta) else: val = ((self.getInvScale().reshape(1,d,d) * delta.reshape(dm.shape[0],1,d)).sum(axis=2) * delta).sum(axis=1) val = 1.0 + val/self.dof return self.getLogNorm() + numpy.log(val)*(-0.5*(self.dof+d)) def __str__(self): return '{dof:%f, location:%s, scale:%s}'%(self.getDOF(), str(self.getLoc()), str(self.getScale()))
[ [ 1, 0, 0.0909, 0.007, 0, 0.66, 0, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 1, 0, 0.0979, 0.007, 0, 0.66, 0.25, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.1049, 0.007, 0, 0.66,...
[ "import math", "import numpy", "import numpy.linalg", "import scipy.special", "class StudentT:\n \"\"\"A feature incomplete multivariate student-t distribution object - at this time it only supports calculating the probability of a sample, and not the ability to make a draw.\"\"\"\n def __init__(self, dim...
# -*- coding: utf-8 -*- # Copyright 2011 Tom SF Haines # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. import numpy import numpy.linalg from gaussian import Gaussian class GaussianInc: """Allows you to incrimentally calculate a Gaussian distribution by providing lots of samples.""" def __init__(self, dims): """You provide the number of dimensions - you must add at least dims samples before there is the possibility of extracting a gaussian from this. Can also act as a copy constructor.""" if isinstance(dims, GaussianInc): self.n = dims.n self.mean = dims.mean.copy() self.scatter = dims.scatter.copy() else: self.n = 0 self.mean = numpy.zeros(dims, dtype=numpy.float32) self.scatter = numpy.zeros((dims,dims), dtype=numpy.float32) def add(self, sample, weight=1.0): """Updates the state given a new sample - sample can have a weight, which obviously defaults to 1, but can be set to other values to indicate repetition of a single point, including fractional.""" sample = numpy.asarray(sample) # Sample count goes up... self.n += weight # Update mean vector... delta = sample - self.mean self.mean += delta*(weight/float(self.n)) # Update scatter matrix (Yes, there is duplicated calculation here as it is symmetric, but who cares?)... self.scatter += weight * numpy.outer(delta, sample - self.mean) def safe(self): """Returns True if it has enough data to provide an actual Gaussian, False if it does not.""" return math.fabs(numpy.linalg.det(self.scatter)) > 1e-6 def makeSafe(self): """Bodges the internal representation so it can provide a non-singular covariance matrix - obviously a total hack, but potentially useful when insufficient information exists. Works by taking the svd, nudging zero entrys away from 0 in the diagonal matrix, then multiplying the terms back together again. End result is arbitary, but won't be inconsistant with the data provided.""" u, s, v = numpy.linalg.svd(self.scatter) epsilon = 1e-5 for i in xrange(s.shape[0]): if math.fabs(s[i])<epsilon: s[i] = math.copysign(epsilon, s[i]) self.scatter[:,:] = numpy.dot(u, numpy.dot(numpy.diag(s), v)) def fetch(self): """Returns the Gaussian distribution calculated so far.""" ret = Gaussian(self.mean.shape[0]) ret.setMean(self.mean) ret.setCovariance(self.scatter/float(self.n)) return ret
[ [ 1, 0, 0.1884, 0.0145, 0, 0.66, 0, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 1, 0, 0.2029, 0.0145, 0, 0.66, 0.3333, 796, 0, 1, 0, 0, 796, 0, 0 ], [ 1, 0, 0.2319, 0.0145, 0, ...
[ "import numpy", "import numpy.linalg", "from gaussian import Gaussian", "class GaussianInc:\n \"\"\"Allows you to incrimentally calculate a Gaussian distribution by providing lots of samples.\"\"\"\n def __init__(self, dims):\n \"\"\"You provide the number of dimensions - you must add at least dims sampl...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...
# Copyright (c) 2012, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp # Some basic matrix operations that come in use... matrix_code = start_cpp() + """ #ifndef MATRIX_CODE #define MATRIX_CODE template <typename T> inline void MemSwap(T * lhs, T * rhs, int count = 1) { while(count!=0) { T t = *lhs; *lhs = *rhs; *rhs = t; ++lhs; ++rhs; --count; } } // Calculates the determinant - you give it a pointer to the first elment of the array, and its size (It must be square), plus its stride, which would typically be identical to size, which is the default. template <typename T> inline T Determinant(T * pos, int size, int stride = -1) { if (stride==-1) stride = size; if (size==1) return pos[0]; else { if (size==2) return pos[0]*pos[stride+1] - pos[1]*pos[stride]; else { T ret = 0.0; for (int i=0; i<size; i++) { if (i!=0) MemSwap(&pos[0], &pos[stride*i], size-1); T sub = Determinant(&pos[stride], size-1, stride) * pos[stride*i + size-1]; if ((i+size)%2) ret += sub; else ret -= sub; } for (int i=1; i<size; i++) { MemSwap(&pos[(i-1)*stride], &pos[i*stride], size-1); } return ret; } } } // Inverts a square matrix, will fail on singular and very occasionally on // non-singular matrices, returns true on success. Uses Gauss-Jordan elimination // with partial pivoting. // in is the input matrix, out the output matrix, just be aware that the input matrix is trashed. // You have to provide its size (Its square, obviously.), and optionally a stride if different from size. template <typename T> inline bool Inverse(T * in, T * out, int size, int stride = -1) { if (stride==-1) stride = size; for (int r=0; r<size; r++) { for (int c=0; c<size; c++) { out[r*stride + c] = (c==r)?1.0:0.0; } } for (int r=0; r<size; r++) { // Find largest pivot and swap in, fail if best we can get is 0... T max = in[r*stride + r]; int index = r; for (int i=r+1; i<size; i++) { if (fabs(in[i*stride + r])>fabs(max)) { max = in[i*stride + r]; index = i; } } if (index!=r) { MemSwap(&in[index*stride], &in[r*stride], size); MemSwap(&out[index*stride], &out[r*stride], size); } if (fabs(max-0.0)<1e-6) return false; // Divide through the entire row... max = 1.0/max; in[r*stride + r] = 1.0; for (int i=r+1; i<size; i++) in[r*stride + i] *= max; for (int i=0; i<size; i++) out[r*stride + i] *= max; // Row subtract to generate 0's in the current column, so it matches an identity matrix... for (int i=0; i<size; i++) { if (i==r) continue; T factor = in[i*stride + r]; in[i*stride + r] = 0.0; for (int j=r+1; j<size; j++) in[i*stride + j] -= factor * in[r*stride + j]; for (int j=0; j<size; j++) out[i*stride + j] -= factor * out[r*stride + j]; } } return true; } #endif """
[ [ 1, 0, 0.1, 0.0077, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 14, 0, 0.5692, 0.8692, 0, 0.66, 1, 974, 4, 0, 0, 0, 0, 0, 1 ] ]
[ "from utils.start_cpp import start_cpp", "matrix_code = start_cpp() + \"\"\"\n#ifndef MATRIX_CODE\n#define MATRIX_CODE\n\ntemplate <typename T>\ninline void MemSwap(T * lhs, T * rhs, int count = 1)\n{\n while(count!=0)" ]
# -*- coding: utf-8 -*- # Copyright (c) 2011, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from utils.start_cpp import start_cpp from utils.numpy_help_cpp import numpy_util_code # Provides various functions to assist with manipulating python objects from c++ code. python_obj_code = numpy_util_code + start_cpp() + """ #ifndef PYTHON_OBJ_CODE #define PYTHON_OBJ_CODE // Extracts a boolean from an object... bool GetObjectBoolean(PyObject * obj, const char * name) { PyObject * b = PyObject_GetAttrString(obj, name); bool ret = b!=Py_False; Py_DECREF(b); return ret; } // Extracts an int from an object... int GetObjectInt(PyObject * obj, const char * name) { PyObject * i = PyObject_GetAttrString(obj, name); int ret = PyInt_AsLong(i); Py_DECREF(i); return ret; } // Extracts a float from an object... float GetObjectFloat(PyObject * obj, const char * name) { PyObject * f = PyObject_GetAttrString(obj, name); float ret = PyFloat_AsDouble(f); Py_DECREF(f); return ret; } // Extracts an array from an object, returning it as a new[] unsigned char array. You can also pass in a pointer to an int to have the size of the array stored... unsigned char * GetObjectByte1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); unsigned char * ret = new unsigned char[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Byte1D(nao,i); Py_DECREF(nao); return ret; } // Extracts an array from an object, returning it as a new[] float array. You can also pass in a pointer to an int to have the size of the array stored... float * GetObjectFloat1D(PyObject * obj, const char * name, int * size = 0) { PyArrayObject * nao = (PyArrayObject*)PyObject_GetAttrString(obj, name); float * ret = new float[nao->dimensions[0]]; if (size) *size = nao->dimensions[0]; for (int i=0;i<nao->dimensions[0];i++) ret[i] = Float1D(nao,i); Py_DECREF(nao); return ret; } #endif """
[ [ 1, 0, 0.1875, 0.0125, 0, 0.66, 0, 972, 0, 1, 0, 0, 972, 0, 0 ], [ 1, 0, 0.2, 0.0125, 0, 0.66, 0.5, 884, 0, 1, 0, 0, 884, 0, 0 ], [ 14, 0, 0.6312, 0.75, 0, 0.66, ...
[ "from utils.start_cpp import start_cpp", "from utils.numpy_help_cpp import numpy_util_code", "python_obj_code = numpy_util_code + start_cpp() + \"\"\"\n#ifndef PYTHON_OBJ_CODE\n#define PYTHON_OBJ_CODE\n\n// Extracts a boolean from an object...\nbool GetObjectBoolean(PyObject * obj, const char * name)\n{\n PyObj...
# -*- coding: utf-8 -*- # Copyright (c) 2010, Tom SF Haines # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time class ProgBar: """Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.""" def __init__(self, width = 60, onCallback = None): self.start = time.time() self.fill = 0 self.width = width self.onCallback = onCallback sys.stdout.write(('_'*self.width)+'\n') sys.stdout.flush() def __del__(self): self.end = time.time() self.__show(self.width) sys.stdout.write('\nDone - '+str(self.end-self.start)+' seconds\n\n') sys.stdout.flush() def callback(self, nDone, nToDo): """Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo).""" if self.onCallback: self.onCallback() n = int(float(self.width)*float(nDone)/float(nToDo)) n = min((n,self.width)) if n>self.fill: self.__show(n) def __show(self,n): sys.stdout.write('|'*(n-self.fill)) sys.stdout.flush() self.fill = n
[ [ 1, 0, 0.2941, 0.0196, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.3137, 0.0196, 0, 0.66, 0.5, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 3, 0, 0.6863, 0.6078, 0, 0.6...
[ "import sys", "import time", "class ProgBar:\n \"\"\"Simple console progress bar class. Note that object creation and destruction matter, as they indicate when processing starts and when it stops.\"\"\"\n def __init__(self, width = 60, onCallback = None):\n self.start = time.time()\n self.fill = 0\n ...
# -*- coding: utf-8 -*- # Code copied from http://opencv.willowgarage.com/wiki/PythonInterface - license unknown, but presumed to be at least as liberal as bsd (The license for opencv.). import cv import numpy as np def cv2array(im): """Converts a cv array to a numpy array.""" depth2dtype = { cv.IPL_DEPTH_8U: 'uint8', cv.IPL_DEPTH_8S: 'int8', cv.IPL_DEPTH_16U: 'uint16', cv.IPL_DEPTH_16S: 'int16', cv.IPL_DEPTH_32S: 'int32', cv.IPL_DEPTH_32F: 'float32', cv.IPL_DEPTH_64F: 'float64', } arrdtype=im.depth a = np.fromstring( im.tostring(), dtype=depth2dtype[im.depth], count=im.width*im.height*im.nChannels) a.shape = (im.height,im.width,im.nChannels) return a def array2cv(a): """Converts a numpy array to a cv array, if possible.""" dtype2depth = { 'uint8': cv.IPL_DEPTH_8U, 'int8': cv.IPL_DEPTH_8S, 'uint16': cv.IPL_DEPTH_16U, 'int16': cv.IPL_DEPTH_16S, 'int32': cv.IPL_DEPTH_32S, 'float32': cv.IPL_DEPTH_32F, 'float64': cv.IPL_DEPTH_64F, } try: nChannels = a.shape[2] except: nChannels = 1 cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]), dtype2depth[str(a.dtype)], nChannels) cv.SetData(cv_im, a.tostring(), a.dtype.itemsize*nChannels*a.shape[1]) return cv_im
[ [ 1, 0, 0.1296, 0.0185, 0, 0.66, 0, 492, 0, 1, 0, 0, 492, 0, 0 ], [ 1, 0, 0.1481, 0.0185, 0, 0.66, 0.3333, 954, 0, 1, 0, 0, 954, 0, 0 ], [ 2, 0, 0.3889, 0.3519, 0, ...
[ "import cv", "import numpy as np", "def cv2array(im):\n \"\"\"Converts a cv array to a numpy array.\"\"\"\n depth2dtype = {\n cv.IPL_DEPTH_8U: 'uint8',\n cv.IPL_DEPTH_8S: 'int8',\n cv.IPL_DEPTH_16U: 'uint16',\n cv.IPL_DEPTH_16S: 'int16',\n cv.IPL_DEPTH_32S: 'int32',", " \...