def createInstallerSourceDir(): message = "create installer source directory" try: config = Project.Config() Functions.createFile(path=config['installer']['config_xml_path'], content=installerConfigXml()) Functions.copyFile( source=config['installer']['config_control_script']['path'], destination=config['installer']['config_dir_path']) Functions.createFile(path=config['installer']['package_xml_path'], content=installerPackageXml()) Functions.copyFile( source=config['installer']['package_install_script']['path'], destination=config['installer']['packages_meta_path']) Functions.copyFile( source=config['app']['license']['file_path'], destination=config['installer']['packages_meta_path']) Functions.createDir(config['installer']['packages_data_path']) Functions.moveDir( source=config['app']['freezed']['path'], destination=config['installer']['packages_data_path']) Functions.moveDir( source=config['project']['subdirs']['examples']['path'], destination=config['installer']['packages_data_path']) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message)
def sharpen(img, k=11, lo_pass=True, min_diff=0.05, alpha=1.0): """ Sharpens the input image with unsharp masking. See Wikipedia (http://en.wikipedia.org/wiki/Unsharp_masking) for details. Note that this function only changes pixel values by a maximum of max_difference at each iteration. Optionally applies a low-pass Gaussian filter at the end, to reduce the effect of high frequency noise. """ # sharpen each color channel separately out = np.zeros(img.shape) sharp_mask = bf.gauss_mask(k) blur_mask = bf.gauss_mask(2 * int(1.0 + (k - 1) / 4.0) + 1) for i in range(0, img.shape[2]): blurred = convolve2d(img[:, :, i], sharp_mask, mode="same", boundary="symm") diff = img[:, :, i] - blurred scaled = alpha * diff if lo_pass: # if necessary, blur each color channel separately diff = convolve2d(diff, blur_mask, mode="same", boundary="symm") diff[np.abs(diff) < min_diff] = 0.0 out[:, :, i] = img[:, :, i] + scaled # truncate to [0, 1] out = bf.truncate(out) return out
def compare(self, y, x, e, v, n): if BasicFunctions.fast_modulo_exponentiation( y, 2, n) == x % n * BasicFunctions.fast_modulo_exponentiation( v, e, n) % n: return True else: return False pass
def turnLeft(): fct.goForward() time.sleep(0.4) fct.stop(9) fct.turn90Left() fct.goForward() time.sleep(0.5) fct.stop(9)
def turnRight(): fct.goForward() time.sleep(1.3) fct.stop(9) fct.turn90Right() fct.goForward() time.sleep(0.5) fct.stop(9)
def __init__(self): self._config_dir = os.getcwd() self._config_name = 'Project.yml' self._release_dir = os.path.join(self._config_dir, 'App') self._release_name = 'Release.yml' # load external config self.__dict__ = self._loadYaml([self._config_dir, self._release_dir], [self._config_name, self._release_name]) # project self.__dict__['project']['dir_path'] = os.getcwd() # ??? self._config_dir self.__dict__['project']['subdirs']['app']['path'] = self._absolutePath(self.__dict__['project']['subdirs']['app']['name']) self.__dict__['project']['subdirs']['distribution']['path'] = self._absolutePath(self.__dict__['project']['subdirs']['distribution']['name']) self.__dict__['project']['subdirs']['scripts']['path'] = self._absolutePath(self.__dict__['project']['subdirs']['scripts']['name']) self.__dict__['project']['subdirs']['certificates']['path'] = self._absolutePath(self.__dict__['project']['subdirs']['certificates']['name']) self.__dict__['project']['subdirs']['examples']['path'] = self._absolutePath(self.__dict__['project']['subdirs']['examples']['name']) self.__dict__['os']['name'] = BasicFunctions.osName() # scripts self.__dict__['scripts']['silent_install'] = os.path.join(self.__dict__['project']['subdirs']['scripts']['path'], 'SilentInstall.js') # scripts self.__dict__['certificate']['path'] = os.path.join(self.__dict__['project']['subdirs']['certificates']['path'], self.__dict__['certificate']['name'][BasicFunctions.osName()]) self.__dict__['certificate']['zip_path'] = os.path.join(self.__dict__['project']['subdirs']['certificates']['path'], 'codesigning.zip') # user self.__dict__['user']['home_dir'] = os.path.expanduser('~') # freeze self.__dict__['pyinstaller']['lib_path']['cryspy'] = cryspy.__path__[0] self.__dict__['pyinstaller']['lib_path']['easyInterface'] = easyInterface.__path__[0] self.__dict__['pyinstaller']['lib_path']['shiboken2'] = shiboken2.__path__[0] self.__dict__['pyinstaller']['lib_path']['pyside2'] = PySide2.__path__[0] self.__dict__['pyinstaller']['lib_path']['dictdiffer'] = dictdiffer.__path__[0] # freezed app self.__dict__['app']['freezed']['path'] = os.path.join(self.__dict__['project']['subdirs']['distribution']['path'], self.__dict__['app']['name'] + self.__dict__['app']['freezed']['ext'][BasicFunctions.osName()]) # installer framework self.__dict__['qtifw']['setup']['name'] = '{0}.{1}'.format(self.__dict__['qtifw']['setup']['base'][BasicFunctions.osName()], self.__dict__['qtifw']['setup']['ext'][BasicFunctions.osName()]) self.__dict__['qtifw']['setup']['download_url'] = 'https://download.qt.io/official_releases/qt-installer-framework/{0}/{1}'.format(self.__dict__['qtifw']['version'], self.__dict__['qtifw']['setup']['name']) self.__dict__['qtifw']['setup']['download_path'] = os.path.join(self.__dict__['project']['dir_path'], '.soft', self.__dict__['qtifw']['setup']['name']) self.__dict__['qtifw']['setup']['exe_path'] = self._qtifwExe(BasicFunctions.osName()) self.__dict__['qtifw']['bin_dir_path'] = self._qtifwBinDirPath(BasicFunctions.osName()) self.__dict__['qtifw']['dir_path'] = self._qtifwDirPath(BasicFunctions.osName()) self.__dict__['qtifw']['binarycreator_path'] = os.path.join(self.__dict__['qtifw']['bin_dir_path'], 'binarycreator') self.__dict__['qtifw']['installerbase_path'] = os.path.join(self.__dict__['qtifw']['bin_dir_path'], 'installerbase') # installer scripts self.__dict__['installer']['config_control_script']['path'] = os.path.join(self.__dict__['project']['subdirs']['scripts']['path'], self.__dict__['installer']['config_control_script']['name']) self.__dict__['installer']['package_install_script']['path'] = os.path.join(self.__dict__['project']['subdirs']['scripts']['path'], self.__dict__['installer']['package_install_script']['name']) # app installer structure self.__dict__['installer']['dir_name'] = self.__dict__['app']['installer']['name_suffix'] + 'Tmp' self.__dict__['installer']['dir_path'] = os.path.join(self.__dict__['project']['subdirs']['distribution']['path'], self.__dict__['installer']['dir_name']) self.__dict__['installer']['config_dir_path'] = os.path.join(self.__dict__['installer']['dir_path'], 'config') self.__dict__['installer']['config_xml_path'] = os.path.join(self.__dict__['installer']['config_dir_path'], 'config.xml') self.__dict__['installer']['packages_dir_path'] = os.path.join(self.__dict__['installer']['dir_path'], 'packages') self.__dict__['installer']['packages_url_path'] = os.path.join(self.__dict__['installer']['packages_dir_path'], 'org.easydiffraction') self.__dict__['installer']['packages_data_path'] = os.path.join(self.__dict__['installer']['packages_url_path'], 'data') self.__dict__['installer']['packages_meta_path'] = os.path.join(self.__dict__['installer']['packages_url_path'], 'meta') self.__dict__['installer']['package_xml_path'] = os.path.join(self.__dict__['installer']['packages_meta_path'], 'package.xml') # app installer self.__dict__['app']['installer']['name'] = self.__dict__['app']['name'] + self.__dict__['app']['installer']['name_suffix'] self.__dict__['app']['installer']['exe_name'] = self.__dict__['app']['installer']['name'] + self.__dict__['os']['gui_exe_ext'][BasicFunctions.osName()] self.__dict__['app']['installer']['dir_path'] = self.__dict__['project']['subdirs']['distribution']['path'] self.__dict__['app']['installer']['exe_path'] = os.path.join(self.__dict__['app']['installer']['dir_path'], self.__dict__['app']['installer']['exe_name']) self.__dict__['app']['license']['file_path'] = os.path.join(self.__dict__['project']['dir_path'], self.__dict__['app']['license']['file_name'])
def moveDir(source, destination): message = "move dir to '{0}'".format(source, os.path.join(os.path.basename(source), destination)) try: shutil.move(source, destination) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message)
def copyFile(source, destination): message = "copy file to '{0}'".format(source, os.path.join(os.path.basename(source), destination)) try: shutil.copy2(source, destination, follow_symlinks=True) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message)
def createDir(path): message = "create dir '{0}'".format(path) try: os.mkdir(path) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message)
def setEnvVariable(name, value): message = "set environment variable '{0}' to '{1}'".format(name, value) try: os.environ[name] = value except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message)
def downloadFile(url, destination): message = "download from '{0}'".format(url) try: file = requests.get(url, allow_redirects=True) open(destination, 'wb').write(file.content) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message)
def loadDockerImage(downloaded_image_path): message = "load docker image from '{}'".format(downloaded_image_path) try: #os.system('docker load < .soft/snap.tar.gz') os.system('gzip -dc {} | docker load'.format(downloaded_image_path)) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message)
def createFile(path, content): message = "create file '{0}'".format(path) try: dir = os.path.dirname(path) os.makedirs(dir, exist_ok=True) with open(path, "w") as file: file.write(content) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message)
def fetchFrame(cam): """ Fetch new frame from camera and preprocess. """ ret, frame = cam.read() # handle invalid return value if not ret: print "Error. Invalid return value." sys.exit() # convert to grayscale img = bf.rescale(bf.bgr2gray(frame)) return img, frame
def osDependentPreparation(): config = Project.Config() binarycreator_path = config['qtifw']['binarycreator_path'] if os.path.exists(binarycreator_path): return () os_name = config['os']['name'] message = "prepare for os '{0}'".format(os_name) if os_name == 'osx': try: Functions.attachDmg(config['qtifw']['setup']['download_path']) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message) elif os_name == 'linux': try: Functions.setEnvVariable("QT_QPA_PLATFORM", "minimal") Functions.addReadPermission(config['qtifw']['setup']['exe_path']) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message) else: message = "* No preparation needed for os '{0}'".format(os_name) print(message)
def get_features(self): sentence_words_pos = dict() with open('Data\\train.labeled', 'r') as f: for line in f: if line == '\n': arches = [] words_pos = dict() data_for_full_graph = set() for counter in sentence_words_pos: word_tuple = sentence_words_pos[counter] # dependency_arch= (head, head_pos, child, child_pos) if word_tuple[2] == 0: dependency_arch = ('root', 'root', word_tuple[0], word_tuple[1]) else: dependency_arch = ( sentence_words_pos[word_tuple[2]][0], sentence_words_pos[word_tuple[2]][1], word_tuple[0], word_tuple[1]) if self.is_improved: ImprovedFunctions.add_features_to_dicts( self, dependency_arch) else: BasicFunctions.add_features_to_dicts( self, dependency_arch) arches.append( (dependency_arch, word_tuple[2], counter)) data_for_full_graph.add( (dependency_arch[2], dependency_arch[3], counter)) words_pos[counter] = word_tuple[1] words_pos[0] = 'root' sentence_words_pos[0] = ('root', 'root', 0) if self.is_improved: ImprovedFunctions.add_improved_features_to_dicts( self, sentence_words_pos) arches.append(('root', 'root', 0)) data_for_full_graph.add(('root', 'root', 0)) self.arches_data_list.append( (arches, list(data_for_full_graph))) self.sentence_tags.append(words_pos) sentence_words_pos = dict() else: split_line = line.split('\t') # (counter)->(token,pos,head) sentence_words_pos[int( split_line[0])] = (split_line[1], split_line[3], int(split_line[6])) f.close()
def installerPackageXml(): message = "create package.xml content" try: config = Project.Config() pydict = { 'Package': { 'DisplayName': config['app']['name'], 'Description': config['app']['description'], 'Version': config['release']['version'], 'ReleaseDate': datetime.datetime.strptime(config['release']['date'], "%d %b %Y").strftime("%Y-%m-%d"), 'Default': 'true', 'Essential': 'true', 'ForcedInstallation': 'true', #'RequiresAdminRights': 'true', 'Licenses': '_LICENCE_STR', #{ # 'License': { # 'name': "GNU Lesser General Public License v3.0", # 'file': "LICENSE" # } ## <License name="GNU Lesser General Public License v3.0" file="LICENSE" /> # SHOULD BE IN THIS FORMAT #}, 'Script': config['installer']['package_install_script']['name'], } } raw_xml = Functions.dict2xml(pydict) pretty_xml = raw_xml # xml.dom.minidom.parseString(raw_xml).toprettyxml() #pretty_xml = xml.dom.minidom.parseString(raw_xml).toprettyxml() pretty_xml = pretty_xml.replace( '_LICENCE_STR', '<License name="GNU Lesser General Public License v3.0" file="LICENSE" />' ) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message) return pretty_xml
def saveDockerImage(docker_image, downloaded_image_path): message = "save docker image '{}'".format(docker_image) if os.path.exists(downloaded_image_path): message = "* Docker image '{0}' for snapcraft is already downloaded to '{1}'".format( docker_image, downloaded_image_path) print(message) return () try: os.system('docker pull {}'.format(docker_image)) os.system('docker save {0} | gzip > {1}'.format( docker_image, downloaded_image_path)) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message)
def osDependentDeploy(): config = Project.Config() os_name = config['os']['name'] project_dir_path = config['project']['dir_path'] branch = BasicFunctions.environmentVariable('TRAVIS_BRANCH') if os_name == 'linux': if branch == 'develop' or branch == 'examples': snapcraft_dir_name = '.snapcraft' docker_image = 'cibuilds/snapcraft:core18' downloaded_image_path = '.soft/snap.tar.gz' createSnapcraftDir(snapcraft_dir_name) decryptCertificates() extractCertificates() moveCertificates(snapcraft_dir_name) saveDockerImage(docker_image, downloaded_image_path) loadDockerImage(downloaded_image_path) runDockerImage(docker_image, project_dir_path, branch) else: message = "* No deployment for branch '{}' is implemented".format( branch) print(message) else: message = "* No deployment for '{}' App Store is implemented".format( os_name) print(message)
def drawWayPart(part): cmd = part.split("(")[0] params = int(part.split("(")[1].split(")")[0].split(",")[0].split(".")[0]) if cmd == 'f' or cmd == 'b': params = bf.map(params, 0, 3000, 0, 500) drawLine(ca, params) else: newDir(part)
def overlapsEye(tl, eye_centers, eye_shape): for ctr in eye_centers: eye_tl = bf.center2tl(ctr, eye_shape) if not (((tl[0] < eye_tl[0]-eye_shape[0]) or (tl[0] > eye_tl[0]+eye_shape[0])) and ((tl[1] < eye_tl[1]-eye_shape[1]) or (tl[1] > eye_tl[1]+eye_shape[1]))): return True return False
def downloadQtInstallerFramework(): config = Project.Config() download_path = config['qtifw']['setup']['download_path'] if os.path.exists(download_path): message = "* QtInstallerFramework was already downloaded to {}".format( download_path) print(message) return () message = "download QtInstallerFramework" try: config = Project.Config() Functions.downloadFile( url=config['qtifw']['setup']['download_url'], destination=config['qtifw']['setup']['download_path']) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message)
def toGame(self): sample_profile = self.profile_dict.keys()[0] g_roles = sample_profile.keys() g_players = {role: sum(strategies.values()) for role, strategies in sample_profile.items()} g_strategies = {role: BasicFunctions.flatten([profile[role].keys() for profile in self.profile_dict.keys()]) for role in g_roles} g_payoff_data = [{role: [PayoffData(strategy, profile[role][strategy], observations) for strategy, observations in strategies.items()] for role, strategies in role_strategies.items()} for profile, role_strategies in self.profile_dict.items()] return SampleGame(g_roles, g_players, g_strategies, g_payoff_data)
def installQtInstallerFramework(): config = Project.Config() dir_path = config['qtifw']['dir_path'] bin_dir_path = config['qtifw']['bin_dir_path'] if os.path.exists(bin_dir_path): message = "* QtInstallerFramework was already installed to {}".format( bin_dir_path) print(message) return () message = "install QtInstallerFramework to '{}'".format(dir_path) try: Functions.installSilently( installer=config['qtifw']['setup']['exe_path'], silent_script=config['scripts']['silent_install']) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message)
def react(c): if c in [ord('q'), 27, 32]: stop() return elif c == curses.KEY_LEFT: fct.goFullSpeedLeft() elif c == curses.KEY_RIGHT: fct.goFullSpeedRight() elif c == curses.KEY_UP: fct.goForward() elif c == curses.KEY_DOWN: fct.goBackward()
def perceptron(self, n): w = np.zeros(self.feature_num, dtype=int) for i in range(0, n): iteration_time = datetime.now() scored_graph_index = list(range(0, len(self.scored_graphs), 1)) shuffled_scored_graph_index = sorted(scored_graph_index, key=lambda k: random.random()) for index in shuffled_scored_graph_index: data = self.scored_graphs[index] weighted_full_graph = AuxFunctions.get_weighted_graph( data[2], data[3], w) g_tag = edmonds.mst(('root', 'root', 0), weighted_full_graph) if True: # For better performance w = w + self.get_saved_f_vector( data[0], data[4]) - self.get_f_vector(g_tag, data[4]) print('Done ' + str(i + 1) + ' iteration at ' + str(datetime.now() - iteration_time)) if self.is_improved: ImprovedFunctions.save_w(w, i + 1) else: BasicFunctions.save_w(w, i + 1)
def round_(self): x = self.usrA.calcX(self.tc.n) e = self.ursB.coinToss() y = self.usrA.calcY(e, self.tc.n) if self.compare(y, x, e, self.usrA.open, self.tc.n): print("Left = ", BasicFunctions.fast_modulo_exponentiation(y, 2, self.tc.n), "Right =", (x % self.tc.n) * BasicFunctions.fast_modulo_exponentiation( self.usrA.open, e, self.tc.n) % self.tc.n) print("e = ", e) return True elif not self.compare(y, x, e, self.usrA.open, self.tc.n): print("Left = ", BasicFunctions.fast_modulo_exponentiation(y, 2, self.tc.n), "Right =", (x % self.tc.n) * BasicFunctions.fast_modulo_exponentiation( self.usrA.open, e, self.tc.n) % self.tc.n) print("e = ", e) return False pass
def plot_different_distances(modelClass): """ Plot the distribution of different distances. Helps for construction of the network. :param modelClass: A Network model that has PC elements. :type modelClass: Either ThresholdModel or FairhallModel """ n = modelClass.p['rows'] * modelClass.p['cols'] list1 = [] list2 = [] for j in range(n): list1.append(2 - 2 * exp(-((modelClass.PC.x[50] - modelClass.PC.x[j])**2 + (modelClass.PC.y[50] - modelClass.PC.y[j])**2) / ((60 * meter)**2))) list2.append((((modelClass.PC.x[50] - modelClass.PC.x[j])**2 + (modelClass.PC.y[50] - modelClass.PC.y[j])**2) / ((2 * 15 * meter)**2)) / 10) BasicFunctions.plot_distrib(list1, "2 - 2 * exp(-||n1 - n2||_2)") BasicFunctions.plot_distrib(list2, "||n1 - n2||_2")
def osDependentAddons(): config = Project.Config() os_name = config['os']['name'] app_name = config['app']['name'] distribution_dir_path = config['project']['subdirs']['distribution'][ 'path'] if os_name == 'osx': message = "add hidpi support ({0})".format(os_name) try: BasicFunctions.run( 'plutil', '-insert', 'NSHighResolutionCapable', '-bool', 'YES', '{0}/{1}.app/Contents/Info.plist'.format( distribution_dir_path, app_name)) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message) elif os_name == 'linux': message = "copy missing EGL and GLX plugins ({0})".format(os_name) try: missing_plugins = config['pyinstaller']['missing_plugins'][os_name] pyside2_path = config['pyinstaller']['lib_path']['pyside2'] app_plugins_path = os.path.join(distribution_dir_path, app_name, 'PySide2', 'plugins') for relative_dir_path in missing_plugins: src_dir_name = os.path.basename(relative_dir_path) src_dir_path = os.path.join(pyside2_path, relative_dir_path) dst_dir_path = os.path.join(app_plugins_path, src_dir_name) print("< src:", src_dir_path) print("> dst:", app_plugins_path) dir_util.copy_tree(src_dir_path, dst_dir_path) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message) else: message = "* No addons needed for os '{0}'".format(os_name) print(message)
def decryptCertificates(): message = "decrypt certificates" try: BasicFunctions.run( 'openssl', 'aes-256-cbc', '-K', BasicFunctions.environmentVariable('encrypted_d23b8f89b93f_key'), '-iv', BasicFunctions.environmentVariable('encrypted_d23b8f89b93f_iv'), '-in', 'Certificates/snapCredentials.tar.enc', '-out', 'Certificates/snapCredentials.tar', '-d') except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message)
def installerConfigXml(): message = "create config.xml content" try: config = Project.Config() os_name = config['os']['name'] app_name = config['app']['name'] if os_name == 'osx': target_dir = '/Applications/{0}'.format( app_name ) # macOS returns $HOME/Applications instead of /Applications for @ApplicationsDir@: https://bugreports.qt.io/browse/QTIFW-1011 elif os_name == 'windows': target_dir = '@ApplicationsDir@\\{0}'.format(app_name) elif os_name == 'linux': target_dir = '@ApplicationsDir@/{0}'.format(app_name) else: BasicFunctions.printFailMessage( "Unsupported os '{0}'".format(os_name)) sys.exit() pydict = { 'Installer': { 'Name': config['app']['name'], 'Version': config['release']['version'], 'Title': config['app']['name'], 'Publisher': config['app']['name'], 'ProductUrl': config['app']['url'], #'Logo': 'logo.png', #'WizardStyle': 'Classic',#'Aero', 'StartMenuDir': config['app']['name'], 'TargetDir': target_dir, 'MaintenanceToolName': '{0}{1}'.format(config['app']['name'], 'Uninstaller'), 'AllowNonAsciiCharacters': 'true', 'AllowSpaceInPath': 'true', 'InstallActionColumnVisible': 'false', 'ControlScript': config['installer']['config_control_script']['name'], } } raw_xml = Functions.dict2xml(pydict) pretty_xml = raw_xml #xml.dom.minidom.parseString(raw_xml).toprettyxml() #raw_xml = html.fromstring(raw_xml) #raw_xml = etree.tostring(raw_xml, xml_declaration=False, encoding='unicode', pretty_print=True)#.decode() except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message) return pretty_xml
def backwardsimulationOpti(self,graph): ##Initialization : bsGraph = graph["Graph"] ## Sons of all visited states StatesIndex = graph["Element"] ## All visited states separation= graph["Separation"] ## Index of the newest states at each period NbStates = len(StatesIndex) UtilityAfter = np.ndarray((NbStates,), dtype=float, order='F') OptimalStrategy = np.ndarray((NbStates,), dtype=np.dtype((str,2*(self.nbIter+1))), order='F') for i in range(NbStates): DeltaT = self.nbIter*self.TimeStep qsame = (StatesIndex[i][0]+StatesIndex[i][1]) ; qopp = StatesIndex[i][2] ; Exec = StatesIndex[i][3] ; changePrice = StatesIndex[i][4] ; [qdisc,qins] = self.DiscQtyFunc(qopp,qsame) UtilityAfter[i] = self.FinalConstraint(qsame,qopp,self.P0,Exec,qdisc,qins,changePrice,DeltaT) OptimalStrategy[i] = "1" UtilityBefore=copy.copy(UtilityAfter) # General Backward Routine for i in range(self.nbIter): sep = separation[self.nbIter-(i+1)] UtilityAfter = copy.copy(UtilityBefore) for j in range(sep): ExecState = StatesIndex[j][3] # When Order not executed if (ExecState==0) : qsame = (StatesIndex[j][0]+StatesIndex[j][1]) qopp = StatesIndex[j][2] lambdaPlusOpp= self.IntensFunc(qsame, qopp,'OppPlus') # intensité insertion Ask lambdaMoinsOpp= self.IntensFunc(qsame, qopp,'OppMoins') # intensité annulation Ask lambdaPlusSame= self.IntensFunc(qsame, qopp,'SamePlus') # intensité insertion Bid lambdaMoinsSame= self.IntensFunc(qsame, qopp,'SameMoins') # intensité annulation Bid [q1,q2,q3,q4,q5]=BasicFunctions.ProbTrans(lambdaPlusSame,lambdaMoinsSame,lambdaPlusOpp,lambdaMoinsOpp,self.TimeStep) # control 'c' u1 = q5*UtilityAfter[bsGraph[j][0][4]]+q4*UtilityAfter[bsGraph[j][0][3]]+q3*UtilityAfter[bsGraph[j][0][2]]+q2*UtilityAfter[bsGraph[j][0][1]]+q1*UtilityAfter[bsGraph[j][0][0]] UtilityBefore[j]=u1 ctrl='0' if (len(OptimalStrategy[j])<=(i+1)): OptimalStrategy[j] = ctrl + OptimalStrategy[j] # When order Executed if (ExecState==1) : DeltaT= (self.nbIter-(i+1))*self.TimeStep qsame = (StatesIndex[j][0]+StatesIndex[j][1]) ; qopp = StatesIndex[j][2] ; Exec = StatesIndex[j][3] ; changePrice = StatesIndex[j][4] ; [qdisc,qins] = self.DiscQtyFunc(qopp,qsame) UtilityBefore[j] = self.FinalConstraint(qsame,qopp,self.P0,Exec,qdisc,qins,changePrice,DeltaT) OptimalStrategy[j] = "1" UtilityAfter = pd.DataFrame(UtilityAfter) UtilityBefore = pd.DataFrame(UtilityBefore) OptimalStrategy = pd.DataFrame(OptimalStrategy) Results=pd.concat([UtilityBefore,UtilityAfter,OptimalStrategy],axis=1) Results.columns = ["UtilityBefore","UtilityAfter","OptiStrategy"] return({"Element":StatesIndex,"Graph":bsGraph,"Results":Results})
def visualizeEyes(raw, found, filtered, eye_locations, eye_shape): """ Display found eyes, and save. """ # save data eye_locations["raw"].append(found) eye_locations["filtered"].append(filtered) # display bf.drawRectangle(raw, found[0], eye_shape, (0, 0, 255)) bf.drawRectangle(raw, found[1], eye_shape, (0, 0, 255)) bf.drawRectangle(raw, (int(filtered[0][0]), int(filtered[0][1])), eye_shape, (255, 0, 0)) bf.drawRectangle(raw, (int(filtered[1][0]), int(filtered[1][1])), eye_shape, (255, 0, 0)) cv2.imshow("camera", raw)
def upgradePip(): message = "upgrade PIP" try: BasicFunctions.run('python', '-m', 'pip', 'install', '--upgrade', 'pip') except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message)
def createSnapcraftDir(dir_name): message = "create snapcraft dir '{}'".format(dir_name) try: BasicFunctions.run('mkdir', dir_name) except Exception as exception: BasicFunctions.printFailMessage(message, exception) sys.exit() else: BasicFunctions.printSuccessMessage(message)
def blur(img, mode="gaussian", k=11): """ Blurs image with a kernel mask of the given type. Supports the following modes, each of which can have varying size k: (1) gaussian: can also provide variance var (2) box: no additional parameters needed """ if mode == "gaussian": mask = bf.gauss_mask(k) elif mode == "box": mask = bf.box_mask(k) else: raise Exception("Mode %s not supported." % mode) # blur each color channel separately out = np.zeros(img.shape) for i in range(0, img.shape[2]): out[:, :, i] = convolve2d(img[:, :, i], mask, mode="same", boundary="symm") return out
def visualizeBlockwiseSparsity(blocks, sparsity, original_shape): """ Visualize blockwise sparsity.""" blocks = np.array(blocks) sparsity = np.array(sparsity) new_image = np.zeros(original_shape) k = blocks[0].shape[0] n_vert = original_shape[0] / k n_horiz = original_shape[1] / k # Iterate through the image and append to 'blocks.' for i in range(n_vert): for j in range(n_horiz): new_image[i * k : (i + 1) * k, j * k : (j + 1) * k] = bf.adjustExposure( blocks[n_horiz * i + j], 1.0 - 0.01 * sparsity[n_horiz * i + j] ) return new_image
import numpy as np import matplotlib.pyplot as plt from scipy import misc import BasicFunctions as bf import Sketching as sketch # Parameters. IMAGE_PATH = "../../data/" IMAGE_NAME = "lenna.png" SIZE = (50, 50) ALPHA = 100.0 BASIS_OVERSAMPLING = 1.0 # Import the image. img = misc.imresize(bf.rgb2gray(bf.imread(IMAGE_PATH + IMAGE_NAME)), SIZE).astype(np.float32) # Obtain Fourier basis. basis, coefficients = sketch.basisCompressedSenseImgL1(img, ALPHA, BASIS_OVERSAMPLING) # Compute reconstruction. reconstruction = (basis * coefficients).reshape(img.shape) # print estimate of sparsity print np.median(np.asarray(coefficients.T)) # Plot. max_value = np.absolute(coefficients).max() plt.figure(1) plt.subplot(121) plt.imshow(reconstruction, cmap="gray")
""" import numpy as np import BasicFunctions as bf from Sharpening import sharpen from Blurring import blur from FindEyes import searchForEyesSVM, createSVM import time, os import cPickle as pickle from TrackEyes import trackEyes # import image #img = bf.imread("lotr.JPG") #img = bf.imread("eye.png") #img = bf.imread("obama.jpg") img = bf.imread("me.jpg") # test blurring #blurred = blur(img, mode="gaussian", k=5) #bf.imshow(blurred) # test sharpening #sharpened = sharpen(img, k=21, lo_pass=True, min_diff=0.01, alpha=3.0) #bf.imshow(sharpened) # test exposure adjustment # darker = bf.adjustExposure(img, gamma=1.5) # bf.imshow(darker) # lighter = bf.adjustExposure(img, gamma=0.5) # bf.imshow(lighter)
import numpy as np import matplotlib.pyplot as plt from scipy import misc import BasicFunctions as bf import Sketching as sketch # Parameters. IMAGE_PATH = "../../data/" IMAGE_NAME = "lenna.png" SIZE = (50, 50) ALPHA = 2 BASIS_OVERSAMPLING = 1.0 # Import the image. img = misc.imresize(bf.rgb2gray(bf.imread(IMAGE_PATH + IMAGE_NAME)), SIZE) # Obtain Fourier basis. basis, coefficients = sketch.basisSketchL1(img, ALPHA, BASIS_OVERSAMPLING) # Compute reconstruction. reconstruction = (basis * coefficients).reshape(img.shape) # Plot. plt.figure(1) plt.subplot(121) plt.imshow(reconstruction, cmap="gray") max_value = np.absolute(coefficients).max() plt.title("Reconstruction using random basis \n in image domain \n %.2f%% sparsity" % (100.0-((np.absolute(coefficients) > 0.01 * max_value).sum()*100.0/(SIZE[0]*SIZE[1]))))
def getListOfDefects(im, debug): passholeCounter = 0 listOfDefects = [] basicFunctions = BasicFunctions() morpher = ImageMorpher() copyimage = deepcopy(im) redWhiteEdges = basicFunctions.detectEdgesInColorPlanes(copyimage) edges = morpher.closeWithSquare(redWhiteEdges, 20) edgesMask = basicFunctions.reduceNoise(edges, getMask=False) mask, precontours, hierarchy = cv2.findContours(edgesMask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for j in range(len(precontours)): cnt = precontours[j] area = cv2.contourArea(cnt) parent = hierarchy[0, j, 3] # if contour is too small or has more than two holes in the image, crop is corrupt, hence return empty list if (area >= 300) and (parent != -1): passholeCounter = passholeCounter + 1 if passholeCounter >= 2: return listOfDefects # If crop is valid, get gear shape from cropped candy im2 = gear.getGearShape(im) imgray = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY) # Find contours in gear shape image im3, contours, hierarchy = cv2.findContours(imgray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Draw the contours for debugging if debug: cv2.drawContours(im2, contours, -1, (0, 255, 0), 1) if len(contours) > 0: mask = np.zeros(imgray.shape, np.uint8) if debug: cv2.drawContours(mask, [contours[0]], 0, 255, -1) pixelpoints = np.transpose(np.nonzero(mask)) # print pixelpoints if passholeCounter < 2: for i in range(len(contours)): cnt = contours[i] area = cv2.contourArea(cnt) if area > 2000: hull = cv2.convexHull(cnt, returnPoints=False) defects = cv2.convexityDefects(cnt, hull) x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(im2, (x, y), (x + w, y + h), (0, 255, 0), 2) if defects != None: for j in range(defects.shape[0]): s, e, f, d = defects[j, 0] start = tuple(cnt[s][0]) end = tuple(cnt[e][0]) far = tuple(cnt[f][0]) if debug: print "Depth of Defect", d cv2.line(im, start, end, [0, 255, 0], 2) if d > 800 and d < 10000: if debug: cv2.circle(im, far, 5, [255, 0, 0], -1) listOfDefects.append(far) if debug: plt.subplot(121), plt.imshow(im, cmap="gray") plt.title("Original Image"), plt.xticks([]), plt.yticks([]) plt.subplot(122), plt.imshow(im2, cmap="gray") plt.title("Edge Image"), plt.xticks([]), plt.yticks([]) plt.show() array = np.array([tuple(i) for i in listOfDefects]) ellipse = np.asarray(array) # Fit an ellipse on the list of defect points if len(ellipse) > 5: circle = cv2.fitEllipse(ellipse) cv2.ellipse(im, circle, (0, 0, 255), 2) cv2.imshow("ellipse fitting", im) cv2.waitKey(0) return listOfDefects else: return listOfDefects
def createSVM(training, eye_centers, eye_shape): """ Create SVM model for eye detection. Inputs are as follows: * training -- old image used for generating an svm model * eyes_centers -- list of eye_centers used for generating an svm * eye_shape -- shape of eye patch """ print "Building SVM classifier..." training_gray = bf.rgb2gray(training) eyes = [] for ctr in eye_centers: eye_gray = extractTL(training_gray, bf.center2tl(ctr, eye_shape), eye_shape) eyes.append(eye_gray) # negative exemplars from rest of image print "Constructing negative exemplars..." negs = [] num_negs = 0 while num_negs < 999: tl = (np.random.randint(0, training_gray.shape[0]), np.random.randint(0, training_gray.shape[1])) if (isValid(training_gray, tl, eye_shape) and not overlapsEye(tl, eye_centers, eye_shape)): num_negs += 1 negs.append(extractTL(training_gray, tl, eye_shape)) # create more positive exemplars by applying random small 3D rotations print "Constructing positive exemplars..." num_eyes = len(eyes) patches = deque([eye2patch(training_gray, bf.center2tl(ctr, eye_shape), eye_shape) for ctr in eye_centers]) while num_eyes < 999: patch = patches.popleft() jittered = jitter(patch, eye_shape) patches.append(patch) new_eye = patch2eye(jittered, eye_shape) eyes.append(new_eye) num_eyes += 1 # change lighting conditions eyes.append(bf.adjustExposure(new_eye, 0.5)) eyes.append(bf.adjustExposure(new_eye, 1.5)) num_eyes += 2 # compute HOG for eyes and negs eyes_hog = [] for eye in eyes: eyes_hog.append(bf.getHog(eye)) negs_hog = [] for neg in negs: negs_hog.append(bf.getHog(neg)) # set up training dataset (eyes = -1, negs = +1) training_set = np.vstack((negs_hog, eyes_hog)) training_labels = np.ones(num_eyes + num_negs) training_labels[num_negs:] = -1 scaler = preprocessing.StandardScaler().fit(training_set) training_set = scaler.transform(training_set) # train SVM print "Training SVM..." weights = {-1 : 1.0, 1 : 1.0} svm = SVM.SVC(C=1.0, gamma=0.01, kernel="rbf", class_weight=weights) svm.fit(training_set, training_labels) return svm, scaler
def __init__(self): self.basicFunctions = BasicFunctions() self.morpher = ImageMorpher()
def filter2( image, debug ): ##### #Filter out image wrapperBool = False basicFunctions = BasicFunctions() img = image original = deepcopy(image) maskLogo = deepcopy(img) maskWrapper = deepcopy(img) height, width, channels = img.shape counter = 0 pixcounter = 0 ########## #LOGO MASK for x in range(0,height): for y in range(0,width): pxR = img[x,y,2] pxG = img[x,y,1] pxB = img[x,y,0] if ~((pxR == 0) and (pxB == 0) and (pxG == 0)): pixcounter = pixcounter + 1 if (isPurple(pxR,pxG,pxB)): counter = counter + 1 if ( (isPink(pxR,pxG,pxB)) | (isPurple(pxR,pxG,pxB)) ): maskLogo[x,y] = [255,255,255] else: maskLogo[x,y] = [0,0,0] ##Get the logo score from the amount of purple in the image logoperc = float(counter)/(pixcounter) print "Logo Percentage = %s" % logoperc if (logoperc >= 0.01) and (logoperc <= 0.50): wrapperBool = True morpher = ImageMorpher() maskLogo = morpher.closeWithSquare(maskLogo,1) maskLogo = morpher.dilateWithSquare(maskLogo,1) for x in range(0,height): for y in range(0,width): pxR = img[x,y,2] pxG = img[x,y,1] pxB = img[x,y,0] pxRl = maskLogo[x,y,2] pxGl = maskLogo[x,y,1] pxBl = maskLogo[x,y,0] if ((pxRl != 0) and (pxGl != 0) and (pxBl != 0)): if ((pxR != 0) and (pxG != 0) and (pxB != 0)): img[x,y] = maskLogo[x,y] ############# #WRAPPER MASK for x in range(0,height): for y in range(0,width): pxR = img[x,y,2] pxG = img[x,y,1] pxB = img[x,y,0] if (isWrapper(pxR,pxG,pxB) or isSomethingElse(pxR,pxG,pxB)): maskWrapper[x,y] = [255,255,255] else: maskWrapper[x,y] = [0,0,0] maskWrapper = morpher.closeWithSquare(maskWrapper,2) maskWrapper = morpher.dilateWithSquare(maskWrapper,2) for x in range(0,height): for y in range(0,width): #print img pxR = img[x,y,2] pxG = img[x,y,1] pxB = img[x,y,0] pxRw = maskWrapper[x,y,2] pxGw = maskWrapper[x,y,1] pxBw = maskWrapper[x,y,0] if ((pxRw != 0) and (pxGw != 0) and (pxBw != 0)): if ((pxR != 0) and (pxG != 0) and (pxB != 0)): img[x,y] = [0,0,0] ######################## #Final Pass for contours temp = deepcopy(img) tempgray = deepcopy(img) tempgray = cv2.cvtColor(tempgray,cv2.COLOR_BGR2GRAY) thresh = deepcopy(img) for x in range(0,height): for y in range(0,width): pxR = img[x,y,2] pxG = img[x,y,1] pxB = img[x,y,0] if ((pxR != 0) and (pxG != 0) and (pxB != 0)): thresh[x,y] = [255,255,255] thresh = cv2.cvtColor(thresh,cv2.COLOR_BGR2GRAY) removing = True removalpass = 1 while(removing): contoured_img = deepcopy(thresh) contoured_img, contours, hierarchy = cv2.findContours(contoured_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) removing = False for j in range(0,len(contours)): cnt = contours[j] area = cv2.contourArea(cnt) parent = hierarchy[0,j,3] if ((area <= 3000)): removing = True if (removing == False): break removalpass = removalpass + 1 for i in range(0, len(contours)): cnt = contours[i] area = cv2.contourArea(cnt) parent = hierarchy[0,i,3] if ((area <= 3000) and (parent == -1)): cv2.drawContours(thresh,cnt,-1,0,thickness=cv2.FILLED) cv2.drawContours(img,cnt,-1,(0,0,0),thickness=cv2.FILLED) if ((area <= 3000) and (parent != -1)): thresh = basicFunctions.fillContourGray(thresh,cnt,255) img = basicFunctions.fillContourColor(img,cnt,255,255,255) if (debug): plt.subplot(161), plt.imshow(original) plt.subplot(162), plt.imshow(maskLogo) plt.subplot(163), plt.imshow(maskWrapper) plt.subplot(164), plt.imshow(temp) plt.subplot(165), plt.imshow(thresh) plt.subplot(166), plt.imshow(img) plt.show() return img, logoperc
def testWindow(hog, svm, scaler, eye_cells, tl): window = hog[tl[0]:tl[0]+eye_cells[0], tl[1]:tl[1]+eye_cells[1], :] window = scaler.transform(bf.normalizeHog(window).ravel()) score = svm.decision_function(window) return score
MAX_RMS_ERROR = 0.25 ERROR_CUTOFF = 50.0 OUTLIER_MAX_DIST = 10.0 PERCENT_OUTLIERS = 2.0 NOISE_SD = 0.05 ADJUST_FREQ = 3 # set up IMPATH = "../Images/TestSeriesCampanile/" files = [f for f in os.listdir(IMPATH) if (not f.startswith(".") and not f == PLYFILE and not f == PKLFILE)] frames = {} frames["files"] = np.array(files) frames["images"] = [] frames["focal_length"] = RATIO * 4100.0 / 1.4 frames["K"] = bf.f2K(frames["focal_length"]) frames["num_images"] = len(files) # graph dictionary # -- motion is the frame-to-frame estimate of [R|t] # -- 3Dmatches maps 3D points to 2D points in specific frames via a dictionary # whose keys are the tuple (kp_idx, most_recent_frame) and values are # the dict ([previous_frames], [xy_positions], [3D_estimates]) graph = {} graph["motion"] = [bf.basePose()] graph["3Dmatches"] = {} graph["frameOffset"] = 0 # make an ORB detector orb = cv2.ORB(nfeatures=50000)
""" Test script. """ import numpy as np import BasicFunctions as bf f = 5.0 K = bf.f2K(f) Rt1 = bf.basePose() R21 = bf.fromAxisAngle(np.array([0, 0, np.pi/2.0])) C21 = np.matrix([[f], [0], [0]]) Rt21 = np.hstack([R21, -R21 * C21]) """ x1 = np.matrix([[2.0*f],[0]]) x2 = np.matrix([[0],[f]]) print "x1 = " + str(x1.T) print "x2 = " + str(x2.T) p = bf.triangulateLM(Rt1, Rt2, x1, x2, K) print "p = " + str(p.T) px1 = bf.fromHomogenous(K * Rt1 * bf.toHomogenous(p)) px2 = bf.fromHomogenous(K * Rt2 * bf.toHomogenous(p)) print "px1 = " + str(px1.T) print "px2 = " + str(px2.T)
from functools import partial import sys import cvxpy as cvx # Parameters. IMAGE_PATH = "../../data/" IMAGE_NAME = "lenna.png" BLOCK_SIZE = 30 RHO = 1.0 ALPHA = 1.0 BASIS_OVERSAMPLING = 1.0 if __name__ == "__main__": # Import the image. img = misc.imresize(bf.rgb2gray(bf.imread(IMAGE_PATH + IMAGE_NAME)), (60, 60)).astype(np.float32) # Get blocks. blocks = sketch.getBlocks(img, BLOCK_SIZE) print "Got %d blocks." % len(blocks) # Compress each block. print "Running CS on each block..." basis, block_coefficients = sketch.basisCompressedSenseDCTHuber(blocks, RHO, ALPHA, BASIS_OVERSAMPLING) # Get sparsity.
def cellTLs2ctrs(cellTLs, eye_shape): ctrs = [] for cellTL in cellTLs: ctrs.append(bf.tl2center(bf.cell2px(cellTL), eye_shape)) return ctrs
def searchForEyesSVM(gray, svm, scaler, eye_shape, locs): """ Explore image on the cell level, reducing HOG calculations. Inputs are as follows (besides the obvious) * svm -- sklearn svm model; may be provided if it exists * scaler -- sklearn preprocessing scaler * locs -- list of approximate centers of eyes * eye_shape -- size of eye template in pixels (rows, columns) """ tracker = MatchTracker() pq = PriorityQueue() eye_cells = (eye_shape[0] // 8, eye_shape[1] // 8) hog_computed = np.zeros((gray.shape[0] // 8, gray.shape[1] // 8), dtype=np.bool) # distribution parameters blind_skip = 3 # adjust locs locs[0] = (int(locs[0][0]), int(locs[0][1])) locs[1] = (int(locs[1][0]), int(locs[1][1])) print locs # only compute HOG on subset of image at first min_x = min(bf.center2tl(locs[0], eye_shape)[1], bf.center2tl(locs[1], eye_shape)[1]) max_x = max(bf.center2tl(locs[0], eye_shape)[1], bf.center2tl(locs[1], eye_shape)[1]) min_y = min(bf.center2tl(locs[0], eye_shape)[0], bf.center2tl(locs[1], eye_shape)[0]) max_y = max(bf.center2tl(locs[0], eye_shape)[0], bf.center2tl(locs[1], eye_shape)[0]) tl = (min_y - 4*eye_shape[0], min_x - 4*eye_shape[1]) br = (max_y + 4*eye_shape[0], max_x + 4*eye_shape[1]) tl_cell = bf.px2cell(tl) br_cell = bf.px2cell(br) tl = bf.cell2px(tl_cell) br = bf.cell2px(br_cell) indices = np.index_exp[tl_cell[0]:br_cell[0], tl_cell[1]:br_cell[1], :] indices_computed = np.index_exp[tl_cell[0]:br_cell[0], tl_cell[1]:br_cell[1]] hog = np.empty((gray.shape[0] // 8, gray.shape[1] // 8, 9), dtype=np.float) hog[indices] = bf.getHog(gray[tl[0]:br[0], tl[1]:br[1]], normalize=False, flatten=False) hog_computed[indices_computed] = True # create visited array visited = np.zeros((hog.shape[0]-eye_cells[0]+1, hog.shape[1]-eye_cells[1]+1), dtype=np.bool) # insert provided locations and begin exploration around each one for loc in locs: tl = bf.center2tl(loc, eye_shape) tl = bf.px2cell(tl) # only proceed if valid if not isValid(hog, tl, eye_cells): continue # handle this point visited[tl[0], tl[1]] = True score = testWindow(hog, svm, scaler, eye_cells, tl)[0] pq.put_nowait((score, tl)) if score <= 0: tracker.insert(score, tl) # search greedySearch(hog, hog_computed, svm, scaler, eye_cells, visited, tracker, pq) if tracker.isDone(): tracker.printClusterScores() clusters, scores = tracker.getBigClusters() centers = cellTLs2ctrs(clusters, eye_shape) return centers, scores # # if needed, repeat above search technique, but with broader scope # print "Searching blindly." # hog = bf.getHog(gray, normalize=False, flatten=False) # hog_computed[:, :] = True # for i in range(20, visited.shape[0]-20, blind_skip): # for j in range(20, visited.shape[1]-20, blind_skip): # test = (i, j) # # only proceed if valid and not visited # if (not isValid(hog, test, eye_cells)) or visited[i, j]: # continue # # handle this point # visited[i, j] = True # score = testWindow(hog, svm, scaler, eye_cells, test)[0] # pq.put_nowait((score, test)) # if score <= 0: # tracker.insert(score, test) # greedySearch(hog, hog_computed, svm, scaler, # eye_cells, visited, tracker, pq) # if tracker.isDone(): # tracker.printClusterScores() # clusters, scores = tracker.getBigClusters() # centers = cellTLs2ctrs(clusters, eye_shape) # return centers, scores print "Did not find two good matches." clusters, scores = tracker.getTwoBestClusters() if len(clusters) == 2: centers = cellTLs2ctrs(clusters, eye_shape) return centers, scores else: return locs, [-0.1, -0.1]
class LabelRecognizer: # constants for letters B_FROM_LABEL = 1 R_FROM_LABEL = 2 A_FROM_LABEL = 3 C_FROM_LABEL = 4 H_FROM_LABEL = 5 S_FROM_LABEL = 6 whRatioCutoff = 6 perimAreaCutoff = 3 correlationCutoff = 1 CONTOUR_MATCHING = 1 # may add other letter matching methods later def __init__(self): self.basicFunctions = BasicFunctions() self.morpher = ImageMorpher() def findLetterFromLabel(self, searchImage, letterEnum, matchMethod=CONTOUR_MATCHING): self.searchImage = searchImage print letterEnum self.initializeLetterTemplate(letterEnum) self.getContours(searchImage) return self.findMatchingContours() def initializeLetterTemplate(self, letterEnum): if letterEnum == LabelRecognizer.B_FROM_LABEL: fileName = "letterTemplates/Bcrop.JPG" elif letterEnum == LabelRecognizer.R_FROM_LABEL: # retake Rcrop (wrinkle in wrapper) fileName = "letterTemplates/Rcrop.JPG" elif letterEnum == LabelRecognizer.A_FROM_LABEL: fileName = "letterTemplates/Acrop.JPG" elif letterEnum == LabelRecognizer.C_FROM_LABEL: fileName = "letterTemplates/Ccrop.JPG" elif letterEnum == LabelRecognizer.H_FROM_LABEL: fileName = "letterTemplates/Hcrop.JPG" elif letterEnum == LabelRecognizer.S_FROM_LABEL: fileName = "letterTemplates/Scrop.JPG" img = self.basicFunctions.readColorImageFromFile(fileName) gray = self.basicFunctions.convertColorToGrayscale(img) if letterEnum == LabelRecognizer.R_FROM_LABEL: gray = cv2.equalizeHist(gray) blurred = cv2.GaussianBlur(gray, (101, 101), 3) else: blurred = cv2.GaussianBlur(gray, (7, 7), 3) edges = cv2.Canny(blurred, 50, 100) edges = self.morpher.dilateWithSquare(edges, 2) edges = self.morpher.closeWithSquare(edges, 3) self.basicFunctions.showImage(edges) contours = self.basicFunctions.findContours(edges) drawnOn = self.basicFunctions.drawContours(img, contours[1]) drawOn = self.basicFunctions.drawContours(img, contours[1], contourIdx=(len(contours[1]) - 1)) self.basicFunctions.showImage(drawOn) print type(contours[1]) if letterEnum == LabelRecognizer.R_FROM_LABEL: self.letterContour = contours[1][len(contours[1]) - 2] else: self.letterContour = contours[1][len(contours[1]) - 1] self.basicFunctions.showImage(self.basicFunctions.drawContours(img, [self.letterContour])) self.letterWHRatio = calcBoundingRectRatio(self.letterContour) self.letterPerimAreaRatio = calculatePerimAreaRatio(self.letterContour) def findMatchingContours(self): matchingContours = [] for i in range(len(self.imgContours)): result = cv2.matchShapes(self.letterContour, self.imgContours[i], 2, 0) if result <= self.correlationCutoff: if abs(self.letterPerimAreaRatio - calculatePerimAreaRatio(self.imgContours[i]) < self.perimAreaCutoff): if abs(self.letterWHRatio - calcBoundingRectRatio(self.imgContours[i]) < self.whRatioCutoff): matchingContours.append(self.imgContours[i]) print len(matchingContours) return tuple(matchingContours) def getContours(self, searchImage): # search image assumed to be color image """ gray2 = self.basicFunctions.convertColorToGrayscale(searchImage) blurred = cv2.GaussianBlur(gray2, (5, 5), 3) edges2 = cv2.Canny(blurred, 50, 100) edges = self.morpher.dilateWithSquare(edges2, 4) edges = self.morpher.closeWithSquare(edges2, 5) self.basicFunctions.showImage(edges2) """ gray = self.basicFunctions.convertColorToGrayscale(searchImage) blurred = cv2.GaussianBlur(gray, (5, 5), 3) edges = cv2.Canny(blurred, 50, 100) edges = self.morpher.dilateWithSquare(edges, 2) edges = self.morpher.closeWithSquare(edges, 3) contours = self.basicFunctions.findContours(edges) self.imgContours = contours[1] self.basicFunctions.showImage(self.basicFunctions.drawContours(searchImage, contours[1])) print len(self.imgContours)