Esempio n. 1
0
		def __loadConfFile(self):
			if(not os.path.exists(os.path.expanduser(self.confFilePath))):
				self.GenerateBlankConf()
			self.btXML = bt.bind_file(os.path.expanduser(self.confFilePath))
			if self.btXML.tipsOfTheDay.version != TIPS_VER:
				self.btXML = None
				self.GenerateBlankConf()
				self.btXML = bt.bind_file(os.path.expanduser(self.confFilePath))

			self.showTips = (self.btXML.tipsOfTheDay.show == "True")
			if self.showTips:
				for tip in self.btXML.tipsOfTheDay.tip:
					self.avTips[int(tip.id)] = (tip.enabled == "True")
Esempio n. 2
0
def make_unlem(dir='en_unlem'):
    unlems = defaultdict(default_trie)
    for filename in os.listdir(dir):
        if filename.endswith('.xml'):
            print filename
            pos, infl, _ = filename.split('.', 2)
            doc = binderytools.bind_file(dir + '/' + filename)
            trie = make_node(doc.root, '', 0, range(20))
            unlems[pos, infl] = trie
    out = open('en.unlem.pickle', 'w')
    pickle.dump(unlems, out, -1)
    out.close()
Esempio n. 3
0
def make_unlem(dir='en_unlem'):
    unlems = defaultdict(default_trie)
    for filename in os.listdir(dir):
        if filename.endswith('.xml'):
            print filename
            pos, infl, _ = filename.split('.', 2)
            doc = binderytools.bind_file(dir+'/'+filename)
            trie = make_node(doc.root, '', 0, range(20))
            unlems[pos, infl] = trie
    out = open('en.unlem.pickle', 'w')
    pickle.dump(unlems, out, -1)
    out.close()
Esempio n. 4
0
    def Load(self, a_sFilename=None):
        if a_sFilename <> None:
            self.SetFilename(a_sFilename)
        else:
            if self.m_sFilename == None:
                self.m_sFilename = "Cannot Load without filename"
                return False

        #reseting present diagram..
        self.m_oBlocks,self.m_oConnectors,self.m_oCurrConnector,self.m_nSessionId = {},[],None,0

        #this two must be updated at each block/conn insertion
        self.m_nBlockCountId = 1  #since block counts are kept, render this from the saved file
        self.m_nConnectorCountId = 1  #since connector Ids are generated from scratch, just reset it

        t_oLoad = bt.bind_file(self.m_sFilename)  #binding saved project

        #loading blocks on canvas
        for block in t_oLoad.harpia.GcState.block:
            self.InsertBlockPosId(int(block.type), float(block.position.x),
                                  float(block.position.y), int(block.id))
            self.m_nBlockCountId = max(self.m_nBlockCountId, int(block.id))
        self.m_nBlockCountId += 1

        #loading connectors on canvas
        try:
            for block in t_oLoad.harpia.network.block:
                for connector in block.outputs.output:
                    if connector.inBlock <> "--" and connector.input <> "--":
                        self.InsertReadyConnector(int(block.id),
                                                  (int(connector.id) - 1),
                                                  int(connector.inBlock),
                                                  (int(connector.input) - 1))
                        #this "-1" are "paired" with those "+1" at line 286 (GetProcessChain:offset=14)
        except AttributeError:
            pass

        #loading properties
        for block in t_oLoad.harpia.properties.block:
            t_sBlockProperties = '<?xml version="1.0" encoding="UTF-8"?>\n<properties>\n' + block.xml(
            ) + '\n</properties>\n'
            self.m_oBlocks[int(block.id)].SetPropertiesXML(
                bt.bind_string(t_sBlockProperties))

        self.UpdateScrolling()
        self.GotoScrolling(0, 0)
        return True
Esempio n. 5
0
def make_mblem():
    doc = binderytools.bind_file('em.xml')
    trie = make_node(doc.root, '', 0, range(20))
    trie.permutation = [x-21 for x in 
    [20, 19, 1, 18, 2, 3, 17, 4, 5, 6, 7, 16, 8, 9, 15, 10, 14, 11, 13, 12]]
    
    # these appear not to work.
    
    #programming = trie.lookup(trie.permute('programming'))
    #programming.append(Leaf.make('', 'ming', 'V', 'pe'))

    #people = trie.lookup(trie.permute('people'))
    #people.append(Leaf.make('rson', 'ople', 'N', 'P'))

    out = open('en.mblem.pickle', 'w')
    pickle.dump(trie, out, -1)
    out.close()
Esempio n. 6
0
	def Load( self, a_sFilename=None ):
		if a_sFilename <> None:
			self.SetFilename(a_sFilename)
		else:
			if self.m_sFilename == None:
				self.m_sFilename = "Cannot Load without filename"
				return False
		
		#reseting present diagram.. 
		self.m_oBlocks,self.m_oConnectors,self.m_oCurrConnector,self.m_nSessionId = {},[],None,0
		
		#this two must be updated at each block/conn insertion
		self.m_nBlockCountId = 1 #since block counts are kept, render this from the saved file
		self.m_nConnectorCountId = 1 #since connector Ids are generated from scratch, just reset it
		
		t_oLoad = bt.bind_file(self.m_sFilename) #binding saved project
		
		#loading blocks on canvas
		for block in t_oLoad.harpia.GcState.block:
			self.InsertBlockPosId(int(block.type),float(block.position.x),float(block.position.y),int(block.id))
			self.m_nBlockCountId = max(self.m_nBlockCountId,int(block.id))
		self.m_nBlockCountId += 1
			
		#loading connectors on canvas
		try:
			for block in t_oLoad.harpia.network.block:
				for connector in block.outputs.output:
					if connector.inBlock <> "--" and connector.input <> "--":
						self.InsertReadyConnector(int(block.id), (int(connector.id)-1), int(connector.inBlock), (int(connector.input)-1)) 
						#this "-1" are "paired" with those "+1" at line 286 (GetProcessChain:offset=14)
		except AttributeError:
			pass
		
		#loading properties
		for block in t_oLoad.harpia.properties.block:
			t_sBlockProperties = '<?xml version="1.0" encoding="UTF-8"?>\n<properties>\n' + block.xml() + '\n</properties>\n'
			self.m_oBlocks[int(block.id)].SetPropertiesXML(bt.bind_string(t_sBlockProperties))
		
		self.UpdateScrolling()
		self.GotoScrolling(0,0);
		return True
Esempio n. 7
0
def make_mblem():
    doc = binderytools.bind_file('em.xml')
    trie = make_node(doc.root, '', 0, range(20))
    trie.permutation = [
        x - 21 for x in [
            20, 19, 1, 18, 2, 3, 17, 4, 5, 6, 7, 16, 8, 9, 15, 10, 14, 11, 13,
            12
        ]
    ]

    # these appear not to work.

    #programming = trie.lookup(trie.permute('programming'))
    #programming.append(Leaf.make('', 'ming', 'V', 'pe'))

    #people = trie.lookup(trie.permute('people'))
    #people.append(Leaf.make('rson', 'ople', 'N', 'P'))

    out = open('en.mblem.pickle', 'w')
    pickle.dump(trie, out, -1)
    out.close()
Esempio n. 8
0
import pickle, yaml
# English permutation:
# 20, 19, 1, 18, 2, 3, 17, 4, 5, 6, 7, 16, 8, 9, 15, 10, 14, 11, 13, 12
# Dutch permutation:
# 20, 19, 18, 17, 16, 15, 1, 2, 14, 3, 4, 5, 6, 13, 7, 8, 9, 12, 10, 11

good_indices = [0, 1, 2, 3, 4, 5, 8, 13, 17, 19]

def dictionarify(node, prefix, depth):
    dic = {}
    if prefix.endswith('='): prefix = prefix[:-1]
    dic["*"] = str(node.target)
    print prefix, dic["*"]
    passthrough = None
    for childNode in node.childNodes:
        if hasattr(childNode, 'nodeName') and childNode.nodeName == 'nodes':
            for child in childNode.node:
                letter = str(child.feature)
                entry = prefix + letter
                dic[letter] = dictionarify(child, entry, depth+1)
                if letter == '=': passthrough = dic[letter]
    if depth in good_indices: return dic
    else:
        if passthrough is not None: return passthrough
        else: return {'*': dic['*']}

doc = binderytools.bind_file('dm.xml')
dic = dictionarify(doc.root, '', 0)
pickle.dump(dic, open("dm.pickle", 'w'))
yaml.dump(dic, open("dm.yaml", 'w'))
Esempio n. 9
0
#! /usr/bin/python
# -*- coding: utf-8 -*-

from amara import binderytools
from Backoffice import *
import os
import shutil

xml = binderytools.bind_file('blueprint.xml')

# Move old apoidea to apoidea.old

# Create apoidea
backofficeDirectory = "~/Sites/engage/"
if os.path.exists(backofficeDirectory):
    shutil.rmtree(backofficeDirectory)

# Copy bones
shutil.copytree('bones', backofficeDirectory)

# Create sql
sql = """----------------------
-- Apoidea Database --
----------------------
------------------------------------------
-- mysql -u webuser -p < bd_apoidea.sql --
------------------------------------------

drop database apoidea2;
create database apoidea2;
use apoidea2;
Esempio n. 10
0
# 20, 19, 1, 18, 2, 3, 17, 4, 5, 6, 7, 16, 8, 9, 15, 10, 14, 11, 13, 12
# Dutch permutation:
# 20, 19, 18, 17, 16, 15, 1, 2, 14, 3, 4, 5, 6, 13, 7, 8, 9, 12, 10, 11

good_indices = [0, 1, 2, 3, 4, 5, 8, 13, 17, 19]


def dictionarify(node, prefix, depth):
    dic = {}
    if prefix.endswith('='): prefix = prefix[:-1]
    dic["*"] = str(node.target)
    print prefix, dic["*"]
    passthrough = None
    for childNode in node.childNodes:
        if hasattr(childNode, 'nodeName') and childNode.nodeName == 'nodes':
            for child in childNode.node:
                letter = str(child.feature)
                entry = prefix + letter
                dic[letter] = dictionarify(child, entry, depth + 1)
                if letter == '=': passthrough = dic[letter]
    if depth in good_indices: return dic
    else:
        if passthrough is not None: return passthrough
        else: return {'*': dic['*']}


doc = binderytools.bind_file('dm.xml')
dic = dictionarify(doc.root, '', 0)
pickle.dump(dic, open("dm.pickle", 'w'))
yaml.dump(dic, open("dm.yaml", 'w'))
Esempio n. 11
0
	def __init__( self, diagram, a_nBlockType, a_nBlockCountId=1):#a_nInputs, a_nOutputs, a_nBlockType ):
		
		#initialize all members
		
		#if len(a_oDictBlock) == 0:
			#a_oDictBlock["Label"] = "Unknown Block"
			#a_oDictBlock["Icon"] = 'haarDetect.png'
			#a_oDictBlock["Color"] = "150:20:40:150"
			#a_oDictBlock["Inputs"] = 0
			#a_oDictBlock["Outputs"] = 0
		
		self.m_nBlockType = a_nBlockType
		
		self.ParentDiagram = diagram
		
		self.m_sDataDir = os.environ['HARPIA_DATA_DIR']
		
		if s2idirectory.block.has_key(a_nBlockType):
			self.m_oDictBlock = s2idirectory.block[a_nBlockType] #a_oDictBlock
		else:
			self.m_oDictBlock = s2idirectory.block[0] #a_oDictBlock
			print "Bad block type.. assuming 00"
		
		self.m_nBlockCountId = a_nBlockCountId
		
		self.widgets = {}
		
		self.m_bFocus = False
		
		#self.m_oPropertiesXML=bt.bind_file(str(s2idirectory.block[self.m_nType]["Path"]["Xml"]) )
		
		self.m_bHasFlow = False
		self.m_bTimeShifts = False
		self.m_bIsSource = False
		
		if self.m_oDictBlock.has_key("IsSource"): #all data sources
			self.m_bIsSource = self.m_oDictBlock["IsSource"]
		
		if self.m_oDictBlock.has_key("TimeShifts"): #delay block
			self.m_bTimeShifts = self.m_oDictBlock["TimeShifts"]
		
		self.m_oPropertiesXML=bt.bind_file(self.m_sDataDir+str(self.m_oDictBlock["Path"]["Xml"]))
		self.m_oPropertiesXML.properties.block.id = unicode(str(self.m_nBlockCountId))
		
		
		self.m_oBorderColor = [ 0, 0, 0, 255 ]
		self.m_oBackColor = [0,0,0,150]
		
		self.m_nRadius = 15
		
		self.m_nInputHeight = 24
		self.m_nInputWidth = 24
		self.m_nOutputHeight = 24
		self.m_nOutputWidth = 24
		
		self.inputPortCenters = []
		self.outputPortCenters = []
		
		self.width = WIDTH_DEFAULT
		self.TextWidth = self.width - WIDTH_2_TEXT_OFFSET
		
		
		t_nMaxIO = max(self.m_oDictBlock["Inputs"],self.m_oDictBlock["Outputs"])
		
		## Generates the block size, based on the number of inputs,outputs
			
		# Comment block is too small...
		if not t_nMaxIO:
			t_nMaxIO = 1
		
		self.height = max( ((t_nMaxIO-1)* 5 ) #espacamento entre ports = 5
												+(self.m_nRadius*2 ) #tirando a margem superior e inferior
												+(t_nMaxIO * self.m_nInputHeight),#adicionando a altura de cada port
												 HEIGHT_DEFAULT)
		
		self.Label = self.m_oDictBlock["Label"]
		self.iconFile = self.m_sDataDir+self.m_oDictBlock["Icon"]
		
		self.__gobject_init__()
		
		self.wGroup = self.ParentDiagram.root().add(self,x=0,y=0)
		self.wGroup.connect("event", self.group_event)
		
		self.wGroup.set_flags(gtk.CAN_FOCUS)
		
		self.Build()
Esempio n. 12
0
    def __init__(self, Editor):
        """
			The Constructor. Loads the glade object, and initializes the GladeWindow object for signal connecting.
		"""

        self.m_oEditor = Editor
        self.m_sDataDir = os.environ['HARPIA_DATA_DIR']

        ## Imports the Glade file
        filename = self.m_sDataDir + 'glade/preferences.glade'

        # The widget list
        widget_list = [
            'preferences', 'PREFGridInt', 'PREFShowGrid', 'PREFServer',
            'PREFPort'
        ]

        # Signal Handlers from the Buttons Confirm and Cancel
        handlers = [
            'on_preferences_confirm_clicked', 'on_preferences_cancel_clicked'
        ]

        # The Top window widget
        top_window = 'preferences'

        # Starts the GladeWindow, calling his __init__ method.
        GladeWindow.__init__(self, filename, top_window, widget_list, handlers)

        # Set the preferences Icon
        self.widgets['preferences'].set_icon_from_file(self.m_sDataDir +
                                                       "images/harpia_ave.png")

        #---------------------------------

        ## The Homefolder where the preferences will be stored.
        if os.name == "nt":
            self.HomeFolder = os.path.join(os.path.expanduser("~"),
                                           "harpiaFiles\\")
        else:
            self.HomeFolder = os.path.expanduser("~/harpiaFiles/")
#        self.HomeFolder = "/tmp/.harpia/"

## The Config File Path
        self.configfile = self.HomeFolder + "harpia.conf"

        # If the path do not exist, creates one.
        if not (os.path.exists(self.HomeFolder)):
            os.makedirs(self.HomeFolder, mode=0700)

        # If the path do not exist, creates one copyint the default harpia.conf.
        if not (os.path.exists(self.configfile)):
            shutil.copy("harpia.conf", self.HomeFolder)

        print "TESTE" + self.configfile
        ## A binderytool object, with the preferences stored
        self.m_oPreferencesXML = bt.bind_file(self.configfile)

        #---------------------------------

        # Load Preferences
        for Preference in self.m_oPreferencesXML.harpia.editor.property:

            if Preference.name == "show-grid":
                if Preference.value == "false":
                    state = "False"
                else:
                    state = "True"
                self.widgets['PREFShowGrid'].set_active(eval(state))

            if Preference.name == "grid-int":
                self.widgets['PREFGridInt'].set_value(int(Preference.value))

            if Preference.name == "server":
                self.widgets['PREFServer'].set_text(unicode(Preference.value))

            if Preference.name == "port":
                self.widgets['PREFPort'].set_value(int(Preference.value))
Esempio n. 13
0
def parseAndGenerate(dirName, XMLChain,installDirName):
		cleanGenerator()
		global g_bSaveVideo #Passando todas as variaveis globais devolta ao default
		global g_bLive
		global g_bVideo
		global g_bCameras
		global g_bFrameRate
		global g_ShowCount
		g_ShowCount = 0
		g_bSaveVideo = []
		g_bVideo = []
		g_bCameras = []
		g_bFrameRate = 0.1
		g_bLive = False #this shall be a list containing the "blockNumbers" for each live acquisition block; len(g_bLive) works just like it is now..
		yield [_("Starting Up Generator")]
		doc = binderytools.bind_file(XMLChain)
		########################Create the blocks from XMLChain############################
		
		##################################################################################
		#				in the future we may want to show some kind of progress bar..
		#							the next few comented lines implement a progress counter.. this could be thrown up to the GUI via yields =]
		##################################################################################
		#t_nBlockCount = 0.0
		#for block in (doc.harpia.properties.block):
			#t_nBlockCount += 1.0
		#t_nItCount = 0.0
		yield [_("Generating Code")]
		for blockIter in (doc.harpia.properties.block):
				#print str(100.0*(t_nItCount/t_nBlockCount)) + "%"
				#t_nItCount += 1.0
				tmpBlock = blockTemplate()
				tmpBlock.blockType = blockIter.type
				tmpBlock.blockNumber = blockIter.id
				tmpBlock.properties = []
				tmpBlock.myConnections = []
				tmpBlock.outputsToSave = []
				try:
						for propIter in blockIter.property:
								tmpBlock.properties.append((propIter.name,propIter.value))
				except AttributeError:
						pass
				ID = tmpBlock.blockNumber
				tmpBlock.getBlockOutputTypes()
				for block in (doc.harpia.network.block):
						if (block.id == ID and int(block.type) <> 10) :
								portCount = -1
								for output in block.outputs.output:
										tmpConnection = connection()
										portCount += 1
										if output.inBlock != '--':
												tmpConnection.sourceOutput = output.id
												tmpConnection.destinationInput = output.input
												tmpConnection.destinationNumber = output.inBlock
												#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
												#!!!!!!cpscotti type-oriented connections...!!!!!
												tmpConnection.connType = tmpBlock.outTypes[int(tmpConnection.sourceOutput) - 1]
												#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
												tmpBlock.myConnections.append(tmpConnection)
										else:
												tmpConnection.destinationNumber = '--'
												tmpBlock.myConnections.append(tmpConnection)
										try:
												if output.grab == 'True':
														tmpBlock.outputsToSave.append(output.id)
										except:
												pass
		###################################################################################
		#ADDING TO EACH BLOCK OBJECT THE RESULTING CODE , THEN ADDING THE BLOCK IN A LIST #
		###################################################################################
		##Please, do not change the sequence
				tmpBlock.blockCodeWriter()
				tmpBlock.connectorCodeWriter()
				tmpBlock.saverCodeWriter()
				blockList.append(tmpBlock)
		###################################################################################

		weights = []
		#Apply the weights on each connection of each block in listOfBlocks, then return a list with its connections
		def applyWeightsOnConnections(listOfBlocks):
		#def applyWeightsOnConnections(listOfBlocks,RollinList):
				##For each block on listt:
				returnList = []
				for block in listOfBlocks:
						##Put the connections on returnList
						for connection in block.myConnections:
								##and apply the weight on this connection
								for tmpBlock in blockList:
										if tmpBlock.blockNumber == connection.destinationNumber:
												tmpBlock.weight += block.weight
												if tmpBlock not in returnList:
													#if tmpBlock not in RollinList:
													returnList.append(tmpBlock)
													#RollinList.append(tmpBlock)
				return returnList


		for block in blockList:
				#cpscotti..
				#if block.blockType == '00':
				if s2idirectory.block[int(block.blockType)]["Inputs"] == 0 and s2idirectory.block[int(block.blockType)]["Outputs"] <> 0:
						tmpList = []
						#RollinPathList = []
						tmpList.append(block)
						#RollinPathList.append(block)
						organizedChain = applyWeightsOnConnections(tmpList) #,RollinPathList)
						while organizedChain <> []:
								organizedChain = applyWeightsOnConnections(organizedChain) #,RollinPathList)
								###Recursive tests... future functionality
								#print "Start: "
								#for block in organizedChain:
									#print "\t"+str(block.blockNumber)


		biggestWeight = -1
		for block in blockList:
				if block.weight >= biggestWeight:
						biggestWeight = block.weight

		for activeWeight in range(biggestWeight):
				activeWeight += 1
				for block in blockList:
						if block.weight == activeWeight:
								arguments.append(block.functionArguments)
								images.append(block.imagesIO)
								functionCalls.append("//Weight: " + str(block.weight) + "\n")
								functionCalls.append(block.functionCall)
								deallocations.append(block.dealloc)
								outDeallocations.append(block.outDealloc)




		header = r"""// Auto-generated C Code - S2i Harpia
/*
*	In order to compile this source code run, in a terminal window, the following command:
*	gcc sourceCodeName.c `pkg-config --libs --cflags opencv` -o outputProgramName
*	
*	the `pkg-config ... opencv` parameter is a inline command that returns the path to both 
*	the libraries and the headers necessary when using opencv. The command also returns other necessary compiler options.
*/
// header:

#ifdef _CH_
#pragma package <opencv>
#endif

#include <stdio.h>
#include <stdlib.h>
#include <opencv/cv.h>
#include <opencv/cxmisc.h>
#include <opencv/cxcore.h>
#include <opencv/ml.h>
#include <opencv/cvaux.h>
#include <opencv/cvwimage.h>
#include <opencv/highgui.h>
#include <math.h>

#define PI 3.1415926535898
double rads(double degs)
{
	return (PI/180 * degs);
}
		"""
		global usesFindSquares
		if usesFindSquares == 1:
			header += r"""

//Routines to findSquares
double angle( CvPoint* pt1, CvPoint* pt2, CvPoint* pt0 )
{
		double dx1 = pt1->x - pt0->x;
		double dy1 = pt1->y - pt0->y;
		double dx2 = pt2->x - pt0->x;
		double dy2 = pt2->y - pt0->y;
		return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}

CvSeq* findSquares4( IplImage* img, CvMemStorage* storage, int minArea, int maxArea)
{
		CvSeq* contours;
		int i, c, l, N = 11;
		int thresh = 50;
		CvSize sz = cvSize( img->width & -2, img->height & -2 );
		IplImage* timg = cvCloneImage( img ); // make a copy of input image
		IplImage* gray = cvCreateImage( sz, 8, 1 ); 
		IplImage* pyr = cvCreateImage( cvSize(sz.width/2, sz.height/2), 8, 3 );
		IplImage* tgray;
		CvSeq* result;
		double s, t;

		if(minArea == -1)
			minArea = 0;
		if(maxArea == -1)
			maxArea = (img->width * img->height);

		CvSeq* squares = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvPoint), storage );
		

		cvSetImageROI( timg, cvRect( 0, 0, sz.width, sz.height ));
		
		// down-scale and upscale the image to filter out the noise
		cvPyrDown( timg, pyr, CV_GAUSSIAN_5x5 );
		cvPyrUp( pyr, timg, CV_GAUSSIAN_5x5 );
		tgray = cvCreateImage( sz, 8, 1 );
		
		// find squares in every color plane of the image
		for( c = 0; c < 3; c++ )



		{
				// extract the c-th color plane
				cvSetImageCOI( timg, c+1 );
				cvCopy( timg, tgray, 0 );
				for( l = 0; l < N; l++ )
				{
						if( l == 0 )
						{
								cvCanny( tgray, gray, 0, thresh, 5 );
								cvDilate( gray, gray, 0, 1 );
						}
						else
						{
								cvThreshold( tgray, gray, (l+1)*255/N, 255, CV_THRESH_BINARY );
						}
						cvFindContours( gray, storage, &contours, sizeof(CvContour),
								CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) );
						while( contours )
						{
								result = cvApproxPoly( contours, sizeof(CvContour), storage,
										CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0 );
								if( result->total == 4 &&
										fabs(cvContourArea(result,CV_WHOLE_SEQ)) > minArea &&
										fabs(cvContourArea(result,CV_WHOLE_SEQ)) < maxArea &&
										cvCheckContourConvexity(result) )
								{
										s = 0;
										
										for( i = 0; i < 5; i++ )
										{
												if( i >= 2 )
												{
														t = fabs(angle(
														(CvPoint*)cvGetSeqElem( result, i ),
														(CvPoint*)cvGetSeqElem( result, i-2 ),
														(CvPoint*)cvGetSeqElem( result, i-1 )));
														s = s > t ? s : t;
												}
										}
										if( s < 0.3 )
												for( i = 0; i < 4; i++ )
														cvSeqPush( squares,
																(CvPoint*)cvGetSeqElem( result, i ));
								}
								contours = contours->h_next;
						}
				}
		}
		cvReleaseImage( &gray );
		cvReleaseImage( &pyr );
		cvReleaseImage( &tgray );
		cvReleaseImage( &timg );
		return squares;
}

double drawSquares( IplImage* cpy, CvSeq* squares )
{
		CvSeqReader reader;
		int i;
		cvStartReadSeq( squares, &reader, 0 );
		for( i = 0; i < squares->total; i += 4 )
		{
				CvPoint pt[4], *rect = pt;
				int count = 4;
				CV_READ_SEQ_ELEM( pt[0], reader );
				CV_READ_SEQ_ELEM( pt[1], reader );
				CV_READ_SEQ_ELEM( pt[2], reader );
				CV_READ_SEQ_ELEM( pt[3], reader );
				cvPolyLine( cpy, &rect, &count, 1, 1, CV_RGB(0,255,0), 3, CV_AA, 0 );
		}
	return (double)squares->total;
}

//End of routines to findSquares

			"""
		global usesFindColor
		if usesFindColor == 1:
			header += r"""

int GetColor(IplImage * imagem, int x, int y)
{
	return   (int)(((uchar*)(imagem->imageData + imagem->widthStep*y))[x]);
}

void SetColor(IplImage * imagem, int x, int y, uchar color)
{
	((uchar*)(imagem->imageData + imagem->widthStep*y))[x] = color;
}


void CheckImg(IplImage * img, uchar c_value, uchar tolerance)
{
	uchar min,max;
	int y_It,x_It;
	if((int)c_value < (int)tolerance)
		tolerance = c_value;

	if(((int)c_value+(int)tolerance) > 255)
		tolerance = 255 - c_value;

	min = c_value - tolerance;
	max = c_value + tolerance;

	for(y_It=0;y_It<(img->height);y_It++)
		for(x_It=0;x_It<(img->width);x_It++)
		{
				uchar val;
				val = GetColor(img,x_It,y_It);
				if(val >= min && val <= max)
					SetColor(img,x_It,y_It,255);
				else
					SetColor(img,x_It,y_It,0);
		}
}

CvPoint GetCenter(IplImage * src, long int * nOfPts)//, long int * numOfPoints)
{
	long int numOfMatchingPoints;
	long int posXsum;
	long int posYsum;
	int x_It, y_It;
	CvPoint Center;
	
	posXsum = 0;
	posYsum = 0;
	numOfMatchingPoints = 0;

	for(y_It=0;y_It<(src->height);y_It++)
		for(x_It=0;x_It<(src->width);x_It++)
			if(GetColor(src,x_It,y_It))
			{
				posXsum += x_It;
				posYsum += y_It;
				numOfMatchingPoints++;
			}

	if(numOfMatchingPoints > 0)
	{
		Center.x = (int)(posXsum/numOfMatchingPoints);
		Center.y = (int)(posYsum/numOfMatchingPoints);
	}
	else
		numOfMatchingPoints = -1;
// 	(*numOfPoints) = numOfMatchingPoints;
	if(nOfPts)
		*nOfPts = numOfMatchingPoints;

	return Center;
}


double dist22Points(CvPoint a, CvPoint b)
{
	int xD,yD;
	xD = a.x - b.x;
	yD = a.y - b.y;

	xD = (xD>0)?xD:-xD;
	yD = (yD>0)?yD:-yD;

	return (double)(xD*xD + yD*yD);
}

double GetVariance(IplImage * src,CvPoint center)//, long int * numOfPoints)
{
	long int numOfMatchingPoints;
	double distSquaresSum;
	double variance;
	int x_It,y_It;

	numOfMatchingPoints = 0;
	distSquaresSum = 0.0;


	for(y_It=0;y_It<(src->height);y_It++)
		for(x_It=0;x_It<(src->width);x_It++)
			if(GetColor(src,x_It,y_It))
			{
				numOfMatchingPoints++;
				distSquaresSum += dist22Points(center,cvPoint(x_It,y_It));
			}

	if(numOfMatchingPoints)
		variance = distSquaresSum/numOfMatchingPoints;
	else
		variance = -1;


	return variance;
}

long int CheckForColor(IplImage * src, IplImage * dst, uchar * c_value, uchar * tolerance, CvPoint * pointCenter, double * variance)
{
	uchar B,B_T,G,G_T,R,R_T;
	int i;
	long int numOfPoints;
	CvPoint centro;
	IplImage * m_pChans[3] = {NULL,NULL,NULL};

	numOfPoints = 0;

	B = c_value[0];
	G = c_value[1];
	R = c_value[2];

	B_T = tolerance[0];
	G_T = tolerance[1];
	R_T = tolerance[2];

	for(i=0;i<3;i++)
		m_pChans[i] = cvCreateImage(cvGetSize(src),IPL_DEPTH_8U, 1);

	cvSplit(src,m_pChans[0],m_pChans[1],m_pChans[2], NULL);

	CheckImg(m_pChans[0],B,B_T);
	CheckImg(m_pChans[1],G,G_T);
	CheckImg(m_pChans[2],R,R_T);

	cvAnd(m_pChans[0], m_pChans[1], dst, NULL );
	cvAnd(m_pChans[2], dst, dst, NULL );

	centro = GetCenter(dst,&numOfPoints);//,&numOfPoints);

	if(numOfPoints != -1)
		*variance = GetVariance(dst,centro);

	pointCenter->x = centro.x;
	pointCenter->y = centro.y;

	cvReleaseImage( &m_pChans[0] );
	cvReleaseImage( &m_pChans[1] );
	cvReleaseImage( &m_pChans[2] );

	return numOfPoints;
}
			"""
		header += "\nint main(int argc, char ** argv)\n{"

		declaration = "\n\t//declaration block\n"
		
		for x in arguments:
				declaration = declaration + x

		for x in images:
				declaration = declaration + x

		if g_bLive:
				declaration += \
				'int end;  end = 0; int key; \n'
				for aCapture in g_bVideo:
					declaration += 'CvCapture * block' + aCapture[0] + '_capture = NULL; \n IplImage * block' + aCapture[0] + '_frame = NULL; \n block' + aCapture[0] + '_capture = cvCreateFileCapture("'+ aCapture[1] +'"); \n'
				for aCamera in g_bCameras:
					declaration += 'CvCapture * block' + aCamera[0] + '_capture = NULL; \n IplImage * block' + aCamera[0] + '_frame = NULL; \n block' + aCamera[0] + '_capture = cvCaptureFromCAM(' + aCamera[1] + '); \n'
				declaration += 'while(!end) \n {\t \n'
				
				for aCapture in g_bVideo:
					declaration += 'cvGrabFrame (block' + aCapture[0] + '_capture); \n block' + aCapture[0] + '_frame = cvRetrieveFrame (block' + aCapture[0] + '_capture); \n'
				
				for aCamera in g_bCameras:
					declaration += 'cvGrabFrame (block' + aCamera[0] + '_capture); \n block' + aCamera[0] + '_frame = cvRetrieveFrame (block' + aCamera[0] + '_capture); \n'

		execution = "\n\t//execution block\n"
		for x in functionCalls:
				execution += x
		if g_ShowCount == 0:
			execution += '\n\tcvNamedWindow("Control Window",CV_WINDOW_AUTOSIZE );'
		if g_bLive:
				execution += '\n\tkey = cvWaitKey (' + str(int((1.0/g_bFrameRate)*1000.0)) + ');\n if(key != -1)\n end = 1;'
			
				
				deallocating = "\n\t//deallocation block\n"
				for x in deallocations:
						deallocating += x 
				
				deallocating += "}"
				
		else:
				deallocating = "\n\t//deallocation block\n"
				
				for x in deallocations:
						deallocating += x 

		closing = ""
		closing += "\n"
		for outDea in outDeallocations:
			closing += outDea
		if g_bLive:
			for aCapture in g_bVideo:
				closing += 'cvReleaseCapture(&block' + aCapture[0] + '_capture);\n'
			for aCamera in g_bCameras:
				closing += 'cvReleaseCapture(&block' + aCamera[0] + '_capture);\n'
		for vWriter in g_bSaveVideo:
			closing += 'cvReleaseVideoWriter(&block' + vWriter + '_vidWriter);\n'
		closing += "return 0;\n } //closing main()\n"
		
		
		#Final code assembly
		entireCode = header+declaration+execution+deallocating+closing
		
		yield [_("Saving Code")]
		#saving code file
		os.chdir(tmpDir+dirName)
		codeFilename = dirName + '.c'
		codeFile = open(codeFilename, 'w')
		codeFile.write(entireCode)
		codeFile.close()
		
		yield [_("Building Makefile")]
		#Assembly of "necessary" makefiles
		#...windows..
		makeFilename = 'Makefile' + dirName + '.bat'
		makeFileEntry = '"' + installDirName+'\\bin\\gcc.exe" ' + codeFilename + " -o " + codeFilename[:-2] + ".exe -lcv -lcxcore -lhighgui"
		makeFile = open(makeFilename, 'w')
		makeFile.write(makeFileEntry)
		makeFile.close()
		
		#...posix..
		makeFilename = 'Makefile.' + dirName
		makeFileEntry = "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:"+installDirName+"/lib/; export PKG_CONFIG_PATH="+installDirName+"/lib/pkgconfig/;g++ "+ codeFilename +" -o " + codeFilename[:-2] + " `pkg-config --cflags --libs opencv`"
		makeFile = open(makeFilename, 'w')
		makeFile.write(makeFileEntry)
		makeFile.close()
		
		yield [_("Compiling ...")]
		if os.name=="nt":
				i,o = os.popen4('Makefile' + dirName + '.bat')

				o.readlines()
				o.close()
				i.close()
				yield [_("Running ...")]
				i,o = os.popen4(codeFilename[:-2]+'.exe')
		
		## ERROR LOG
				Error = ''
				errorList = o.readlines()
				for element in errorList:
						Error = Error + element
				
				SetErrorLog(Error)

				o.readlines()
				o.close()
				i.close()
		else:
				i,o = os.popen4("sh " + makeFilename)

				## appending compile errors too.. helps finding bugs! =]
				CompilingErrors = ''
				CerrorList = o.readlines()

				if len(CerrorList) <> 0:
					CompilingErrors += "Something was detected while compiling the source code.\n" + \
												"There is a huge chance you've found a bug, please report to [email protected] \n" + \
												"sending the processing chain (.hrp), this error message and some description on what you were doing.\n" + \
												"We appreciate your help!\n"
				for element in CerrorList:
					CompilingErrors += element
				
				o.close()
				i.close()
				if g_bLive:
					yield [_("Running, press any key (on the video output window) to terminate."), CompilingErrors]
				else:
					yield [_("Running ..."), CompilingErrors]
				
				#cpscotti, xunxo bunitinho pra nao travar a interface qndo tive rodando o live =]
				t_oPrg = RunPrg("LD_LIBRARY_PATH=" + installDirName + "/lib/ ./"+codeFilename[:-2])
				t_oPrg.start()
				while t_oPrg.isAlive():
					t_oPrg.join(0.4)
					while gtk.events_pending():
						gtk.main_iteration(False)
				
				#fim do "xunx"
				
				## ERROR LOG
				o = open("RunErrorLog","r")
				Error = ''
				errorList = o.readlines()
				for element in errorList:
						Error += element
				
				yield [_("Leaving.."), Error]
				SetErrorLog(CompilingErrors + Error)

				o.close()
				i.close()
Esempio n. 14
0
	def __init__( self, Editor ):
		"""
			The Constructor. Loads the glade object, and initializes the GladeWindow object for signal connecting.
		"""
		
		self.m_oEditor = Editor
		self.m_sDataDir = os.environ['HARPIA_DATA_DIR']
		
		## Imports the Glade file
		filename = self.m_sDataDir+'glade/preferences.ui'

		# The widget list
		widget_list = [ 'preferences',
                        'PREFGridInt',
                        'PREFShowGrid',
                        'PREFServer',
                        'PREFPort']

		# Signal Handlers from the Buttons Confirm and Cancel
		handlers = [  'on_preferences_confirm_clicked',
                      'on_preferences_cancel_clicked']

		# The Top window widget
		top_window = 'preferences'
		
		# Starts the GladeWindow, calling his __init__ method.
		GladeWindow.__init__(self, filename, top_window, widget_list, handlers)
        
		# Set the preferences Icon
		self.widgets['preferences'].set_icon_from_file(self.m_sDataDir+"images/harpia_ave.png")

        #---------------------------------
        
		## The Homefolder where the preferences will be stored.
		if os.name=="nt":
                    self.HomeFolder = os.path.join(os.path.expanduser("~"),"harpiaFiles\\")
                else:
                    self.HomeFolder = os.path.expanduser("~/harpiaFiles/")
#        self.HomeFolder = "/tmp/.harpia/"

		## The Config File Path
		self.configfile = self.HomeFolder + "harpia.conf"
		
		# If the path do not exist, creates one.
		if not( os.path.exists(self.HomeFolder) ):
			os.makedirs(self.HomeFolder, mode=0700)

		# If the path do not exist, creates one copyint the default harpia.conf.
		if not( os.path.exists(self.configfile) ):
			shutil.copy("harpia.conf", self.HomeFolder)

                print "TESTE" +  self.configfile       
		## A binderytool object, with the preferences stored
		self.m_oPreferencesXML = bt.bind_file(self.configfile)


        #---------------------------------
        

        # Load Preferences
		for Preference in self.m_oPreferencesXML.harpia.editor.property:

			if Preference.name == "show-grid":
				if Preference.value == "false":
					state = "False"
				else:
					state = "True"
				self.widgets['PREFShowGrid'].set_active( eval(state) )
                
			if Preference.name == "grid-int":
				self.widgets['PREFGridInt'].set_value( int(Preference.value) )

			if Preference.name == "server":
				self.widgets['PREFServer'].set_text( unicode(Preference.value) ) 

			if Preference.name == "port":
				self.widgets['PREFPort'].set_value( int(Preference.value) )