Пример #1
0
    def test_getLabelableList(self):
        print("testing getLabelableList")
        sys.stdout.flush()
        labelList = easy.getLabelableList("easyTestData")
        '''verify that the labels are correct
           They should be , the root directory "easyTestData",
           "kitchen" and "MITmountain"
           
        '''
        for entry in labelList:
            print("label name " + entry.lab.name)
            if entry.lab.name != "easyTestData" and \
               entry.lab.name != "kitchen" and \
               entry.lab.name != "MITmountain":
                raise RuntimeError(
                    "Not a valid label name in test getLabelableList")
            if entry.lab.name == "kitchen":
                # should find easyTestData, inside, house properties
                if "easyTestData" not in entry.lab.properties:
                    raise RuntimeError("easyTestData not in properties")
                if "inside" not in entry.lab.properties:
                    raise RuntimeError("inside not in properties")
                if "house" not in entry.lab.properties:
                    raise RuntimeError("house not in properties")
        ''' verify that we can make a runset and use it with the labelableList
        '''
        runset = cvac.RunSet()
        posPurpose = easy.getPurpose('pos')
        easy.addToRunSet(runset, labelList, posPurpose)
        if not easy.isProperRunSet(runset):
            raise RuntimeError(
                "test getLabelableList failed with an invalid runset")
        labelList = easy.getLabelableList("easyTestData", recursive=False)
        ''' should only have one label "easyTestData"
        '''
        for entry in labelList:
            if entry.lab.name != "easyTestData":
                raise RuntimeError(
                    "recursive option failed in test getLabelableList")
            if len(entry.lab.properties) > 0:
                raise RuntimeError("labelable should not have any properties")

        if not easy.isProperRunSet(runset):
            raise RuntimeError(
                "test getLabelableList failed with an invalid runset with non-recursive call"
            )
Пример #2
0
 def test_getLabelableList(self):
     print("testing getLabelableList")
     sys.stdout.flush()
     labelList = easy.getLabelableList("easyTestData")
     '''verify that the labels are correct
        They should be , the root directory "easyTestData",
        "kitchen" and "MITmountain"
        
     '''
     for entry in labelList:
         print ("label name " + entry.lab.name)
         if entry.lab.name != "easyTestData" and \
            entry.lab.name != "kitchen" and \
            entry.lab.name != "MITmountain":
             raise RuntimeError("Not a valid label name in test getLabelableList")
         if entry.lab.name == "kitchen":
             # should find easyTestData, inside, house properties
             if "easyTestData" not in entry.lab.properties:
                 raise RuntimeError("easyTestData not in properties")
             if "inside" not in entry.lab.properties:
                 raise RuntimeError("inside not in properties")
             if "house" not in entry.lab.properties:
                 raise RuntimeError("house not in properties")
                 
     
     ''' verify that we can make a runset and use it with the labelableList
     '''
     runset = cvac.RunSet()
     posPurpose = easy.getPurpose('pos')
     easy.addToRunSet(runset, labelList, posPurpose)
     if not easy.isProperRunSet(runset):
         raise RuntimeError("test getLabelableList failed with an invalid runset")
     labelList = easy.getLabelableList("easyTestData", recursive=False)
     ''' should only have one label "easyTestData"
     '''
     for entry in labelList:
         if entry.lab.name != "easyTestData":
             raise RuntimeError("recursive option failed in test getLabelableList")
         if len(entry.lab.properties) > 0:
             raise RuntimeError("labelable should not have any properties")
             
     if not easy.isProperRunSet(runset):
         raise RuntimeError("test getLabelableList failed with an invalid runset with non-recursive call")
Пример #3
0
    def isProperDetector(self,
                         configString,
                         detectorData=None,
                         detectorProperties=None):
        '''Try to create or use the specified detector.
        Create a test runset and call the detector with it.
        Check for proper handling of intentional problems.
        '''
        detector = easy.getDetector(configString)
        if not detector:
            print("cannot find or connect to detector")
            return False

        # make a runset including erroneous files
        rs = cvac.RunSet()
        file_normal = easy.getLabelable("testImg/italia.jpg")
        file_notexist = easy.getLabelable("testImg/doesnotexist.jpg")
        file_notconvertible = easy.getLabelable("testImg/notconvertible.xxx")
        easy.addToRunSet(rs, file_normal,
                         cvac.Purpose(cvac.PurposeType.UNPURPOSED, -1))
        easy.addToRunSet(rs, file_notexist,
                         cvac.Purpose(cvac.PurposeType.UNPURPOSED, -1))
        easy.addToRunSet(rs, file_notconvertible,
                         cvac.Purpose(cvac.PurposeType.UNPURPOSED, -1))
        results = easy.detect(detector, detectorData, rs, detectorProperties)

        # check for number of results: must be the same as runset length
        nRunset = 0
        for pur in rs.purposedLists:
            nRunset += len(pur.labeledArtifacts)
        if len(results) != nRunset:
            print("incorrect result set size")
            return False

        # check that the doesnotexist file caused hasLabel==False
        found = False
        for lbl in results:
            # for an erroneous file
            if lbl.original.sub == img_notexist.sub or lbl.original.sub == img_notconvertible.sub:
                for foundlbl in lbl.foundLabels:
                    if foundlbl.lab.hasLabel:
                        print(
                            "Incorrectly assigned label for an erroneous file."
                        )
                        return False
            else:  #for a normal file
                for foundlbl in lbl.foundLabels:
                    # confidence 0..1
                    if not 0.0 <= foundlbl.confidence and foundlbl.confidence <= 1.0:
                        print("Label confidence out of bounds ({0}).".format(
                            foundlbl.confidence))
                        return False
                    # check that either this was not assigned a label, or the
                    # assigned label is of proper syntax
                    if foundlbl.lab.hasLabel:
                        if not isinstance(foundlbl.lab.name, str):
                            print("Label name must be of string type.")
                            return False
        return True
Пример #4
0
 def isProperDetector( self, configString, detectorData=None, detectorProperties=None ):
     '''Try to create or use the specified detector.
     Create a test runset and call the detector with it.
     Check for proper handling of intentional problems.
     '''
     detector = easy.getDetector( configString )
     if not detector:
         print("cannot find or connect to detector")
         return False
     
     # make a runset including erroneous files
     rs = cvac.RunSet()
     file_normal = easy.getLabelable( "testImg/italia.jpg" )
     file_notexist = easy.getLabelable( "testImg/doesnotexist.jpg" )
     file_notconvertible = easy.getLabelable( "testImg/notconvertible.xxx")
     easy.addToRunSet( rs, file_normal, cvac.Purpose( cvac.PurposeType.UNPURPOSED, -1 ))
     easy.addToRunSet( rs, file_notexist, cvac.Purpose( cvac.PurposeType.UNPURPOSED, -1 ))
     easy.addToRunSet( rs, file_notconvertible, cvac.Purpose( cvac.PurposeType.UNPURPOSED, -1 ) )
     results = easy.detect( detector, detectorData, rs, detectorProperties )
     
     # check for number of results: must be the same as runset length
     nRunset = 0 
     for pur in rs.purposedLists:
         nRunset += len(pur.labeledArtifacts)
     if len(results)!=nRunset:
         print("incorrect result set size")
         return False
     
     # check that the doesnotexist file caused hasLabel==False
     found=False
     for lbl in results:
         # for an erroneous file
         if lbl.original.sub==img_notexist.sub or lbl.original.sub==img_notconvertible.sub:
             for foundlbl in lbl.foundLabels:
                 if foundlbl.lab.hasLabel:
                     print("Incorrectly assigned label for an erroneous file.")
                     return False
         else:   #for a normal file
             for foundlbl in lbl.foundLabels:
                 # confidence 0..1
                 if not 0.0<=foundlbl.confidence and foundlbl.confidence<=1.0:
                     print("Label confidence out of bounds ({0}).".format(foundlbl.confidence))
                     return False
                 # check that either this was not assigned a label, or the
                 # assigned label is of proper syntax
                 if foundlbl.lab.hasLabel:
                     if not isinstance(foundlbl.lab.name, str):
                         print("Label name must be of string type.")
                         return False
     return True
Пример #5
0
matz 6/18/2013
'''
import cvac
import easy
import zipfile

#
# create a RunSet from corporate logo images
#
print("==== Training runset: ====")
#trainset = easy.createRunSet( "trainImg" )
trainset = cvac.RunSet()
caset = easy.createRunSet("trainImg/ca")
krset = easy.createRunSet("trainImg/kr")
usset = easy.createRunSet("trainImg/us")
easy.addToRunSet(trainset, caset, cvac.Purpose(cvac.PurposeType.MULTICLASS, 0))
easy.addToRunSet(trainset, krset, cvac.Purpose(cvac.PurposeType.MULTICLASS, 1))
easy.addToRunSet(trainset, usset, cvac.Purpose(cvac.PurposeType.MULTICLASS, 2))
easy.printRunSetInfo(trainset, printLabels=True)

#
# Connect to the trainer for a Bag of Words algorithm, then
# train with the given runset
#
print("starting training, this might take a few minutes...")
trainer = easy.getTrainer("BOW_Trainer")
trainedModel = easy.train(trainer, trainset)

#
# Display information about the file in which the model is stored;
# this is generally no concern to algorithm users and only of
Пример #6
0
    c.detectorData = "detectors/dpmStarbucksLogo.zip"
    c.foundMap = {
        'Positive': easy.getPurpose('pos'),
        'Negative': easy.getPurpose('neg')
    }
    contenders.append(c)

# OpenCVCascade, with special settings for anticipated poor performance
if (easy.getTrainer("OpenCVCascadeTrainer") == None):
    print("Cascade service(s) are insufficiently configured, skipping.")
else:
    c = ev.Contender("cascade")
    c.trainerString = "OpenCVCascadeTrainer"
    c.detectorString = "OpenCVCascadeDetector"
    # c.foundMap = {'any':easy.getPurpose('pos')}
    c.foundMap = {'positive': posPurpose, 'negative': negPurpose}
    detector = easy.getDetector(c.detectorString)
    detectorProps = easy.getDetectorProperties(detector)
    c.detectorProps = detectorProps
    c.detectorProps.props["maxRectangles"] = "200"
    c.detectorProps.minNeighbors = 0
    # This prevents hang up in evaluator when training has too few samples
    contenders.append(c)

runset = easy.createRunSet("trainImg/kr", "pos")
easy.addToRunSet(runset, "trainImg/ca", "neg")
easy.printRunSetInfo(runset, printArtifacts=False, printLabels=True)

perfdata = ev.joust(contenders, runset, folds=3)
ev.printEvaluationResults(perfdata[0])
Пример #7
0
    def test_cvacdatadir(self):
        print("testing cvac data dir")
        if sys.platform == 'win32':
            datadir = os.getenv("CVAC_DATADIR", None) 
            datadir = datadir.replace("/", "\\")
            easy.CVAC_DataDir = datadir
            print("Testing using back slashes")
            print("Using CVAC_DATADIR as " + datadir)
            testset = []
            easy.misc.searchDir(testset, datadir + '\\testImg', recursive=True, video=False, image=True)
            runset = cvac.RunSet()
            easy.addToRunSet(runset, testset, 'pos')
            modelfile = 'detectors/bowUSKOCA.zip'
            detector = easy.getDetector("BOW_Detector")
            props = easy.getDetectorProperties(detector)
            props.verbosity = 3
            results = easy.detect(detector, modelfile, runset, 
                            detectorProperties=props)
            easy.printResults(results)
        else:
            print("Skipping back slash test on this platform")
        
        #run it again with all forward slashes
        datadir = os.getenv("CVAC_DATADIR", None) 
        datadir = datadir.replace("\\", "/")
        print("Testing using all forward slashes")
        print("Using CVAC_DATADIR as " + datadir)
        easy.CVAC_DataDir = datadir
        testset = []
        easy.misc.searchDir(testset, datadir + '/testImg', recursive=True, video=False, image=True)
        runset = cvac.RunSet()
        easy.addToRunSet(runset, testset, 'pos')
        modelfile = 'detectors/bowUSKOCA.zip'
        detector = easy.getDetector("BOW_Detector")
        props = easy.getDetectorProperties(detector)
        props.verbosity = 3
        results = easy.detect(detector, modelfile, runset,
                               detectorProperties=props)
        easy.printResults(results)

        #run it for forward slashes and relative path
        origDir = datadir
        curDir = os.getcwd()
        curDir = curDir.replace("\\", "/")
        datadir = datadir.replace("\\", "/")
        print("using relative paths for " + curDir + " in  data dir " + datadir)
        if datadir.startswith(curDir):
            datadir = datadir[len(curDir)+1:]
            easy.CVAC_DataDir = datadir
            print("Using CVAC_DataDir as "  + datadir)
            testset = []
            easy.misc.searchDir(testset, origDir + '/testImg', recursive=True, video=False, image=True)
            runset = cvac.RunSet()
            easy.addToRunSet(runset, testset, 'pos')
            modelfile = origDir + '/detectors/bowUSKOCA.zip'
            detector = easy.getDetector("BOW_Detector")
            props = easy.getDetectorProperties(detector)
            props.verbosity = 3
            results = easy.detect(detector, modelfile, runset,
                                   detectorProperties=props)
            easy.printResults(results)
        else:
            RuntimeError("Bad datadir")
Пример #8
0
    c3.detectorString = "DPM_Detector:default -p 10116"
    c3.detectorData = "detectors/dpmStarbucksLogo.zip"
    c3.foundMap = {'Positive':easy.getPurpose('pos'), 'Negative':easy.getPurpose('neg')}

    # OpenCVCascade
    c2 = Contender("cascade")
    c2.trainerString = "OpenCVCascadeTrainer:default -p 10107"
    c2.detectorString = "OpenCVCascadeDetector:default -p 10102"
    c2.foundMap = {'positive':posPurpose, 'negative':negPurpose}
    detector = easy.getDetector(c2.detectorString)
    detectorProps = easy.getDetectorProperties(detector)
    c2.detectorProps = detectorProps;
    c2.detectorProps.props["maxRectangles"] = "200"
    c2.detectorProps.minNeighbors = 0; # This prevents hang up in evaluator when training has too few samples
    c4 = Contender("cascade")
    c4.trainerString = "OpenCVCascadeTrainer:default -p 10107"
    c4.detectorString = "OpenCVCascadeDetector:default -p 10102"
    c4.foundMap = {'any':easy.getPurpose('pos')}

    runset = easy.createRunSet( "trainImg/kr/Kr001.jpg", "pos" )
    easy.addToRunSet( runset, "trainImg/kr/Kr002.jpg", "pos" )
    easy.addToRunSet( runset, "trainImg/kr/Kr003.jpg", "pos" )
    easy.addToRunSet( runset, "trainImg/ca/ca0003.jpg", "neg" )
    easy.addToRunSet( runset, "trainImg/ca/ca0004.jpg", "neg" )
    easy.addToRunSet( runset, "trainImg/ca/ca0005.jpg", "neg" )
    easy.printRunSetInfo( runset, printArtifacts=False, printLabels=True )
    
    perfdata = joust( [c1, c2], runset, folds=3 )
    printEvaluationResults(perfdata)
    
Пример #9
0
import evaluate
import cvac
import time #for computing computation time
import os   #for chdir
stime = time.clock()

'''
Making training data
'''
#trainImg_roc_simple
#trainImg_roc
trainsetPos = easy.createRunSet( 'corporate_logos' )
trainsetNeg = easy.createRunSet( 'trainImg' )

runset = cvac.RunSet()
easy.addToRunSet(runset, trainsetPos, 'pos')
easy.addToRunSet(runset, trainsetNeg, 'neg')
easy.printRunSetInfo( runset, printLabels=True, )

strTrainer = "BOW_Trainer"
strDetector = "BOW_Detector"

list_nWord = [5,10,15,20]


doWithNegativeSample = True

if doWithNegativeSample:
    ###############################################################
    # With background data
    '''
Пример #10
0
    def test_cvacdatadir(self):
        print("testing cvac data dir")
        if sys.platform == 'win32':
            datadir = os.getenv("CVAC_DATADIR", None)
            datadir = datadir.replace("/", "\\")
            easy.CVAC_DataDir = datadir
            print("Testing using back slashes")
            print("Using CVAC_DATADIR as " + datadir)
            testset = []
            easy.misc.searchDir(testset,
                                datadir + '\\testImg',
                                recursive=True,
                                video=False,
                                image=True)
            runset = cvac.RunSet()
            easy.addToRunSet(runset, testset, 'pos')
            modelfile = 'detectors/bowUSKOCA.zip'
            detector = easy.getDetector("BOW_Detector")
            props = easy.getDetectorProperties(detector)
            props.verbosity = 3
            results = easy.detect(detector,
                                  modelfile,
                                  runset,
                                  detectorProperties=props)
            easy.printResults(results)
        else:
            print("Skipping back slash test on this platform")

        #run it again with all forward slashes
        datadir = os.getenv("CVAC_DATADIR", None)
        datadir = datadir.replace("\\", "/")
        print("Testing using all forward slashes")
        print("Using CVAC_DATADIR as " + datadir)
        easy.CVAC_DataDir = datadir
        testset = []
        easy.misc.searchDir(testset,
                            datadir + '/testImg',
                            recursive=True,
                            video=False,
                            image=True)
        runset = cvac.RunSet()
        easy.addToRunSet(runset, testset, 'pos')
        modelfile = 'detectors/bowUSKOCA.zip'
        detector = easy.getDetector("BOW_Detector")
        props = easy.getDetectorProperties(detector)
        props.verbosity = 3
        results = easy.detect(detector,
                              modelfile,
                              runset,
                              detectorProperties=props)
        easy.printResults(results)

        #run it for forward slashes and relative path
        origDir = datadir
        curDir = os.getcwd()
        curDir = curDir.replace("\\", "/")
        datadir = datadir.replace("\\", "/")
        print("using relative paths for " + curDir + " in  data dir " +
              datadir)
        if datadir.startswith(curDir):
            datadir = datadir[len(curDir) + 1:]
            easy.CVAC_DataDir = datadir
            print("Using CVAC_DataDir as " + datadir)
            testset = []
            easy.misc.searchDir(testset,
                                origDir + '/testImg',
                                recursive=True,
                                video=False,
                                image=True)
            runset = cvac.RunSet()
            easy.addToRunSet(runset, testset, 'pos')
            modelfile = origDir + '/detectors/bowUSKOCA.zip'
            detector = easy.getDetector("BOW_Detector")
            props = easy.getDetectorProperties(detector)
            props.verbosity = 3
            results = easy.detect(detector,
                                  modelfile,
                                  runset,
                                  detectorProperties=props)
            easy.printResults(results)
        else:
            RuntimeError("Bad datadir")
Пример #11
0
import easy
import evaluate
import cvac
import time  #for computing computation time
import os  #for chdir
stime = time.clock()
'''
Making training data
'''
#trainImg_roc_simple
#trainImg_roc
trainsetPos = easy.createRunSet('corporate_logos')
trainsetNeg = easy.createRunSet('trainImg')

runset = cvac.RunSet()
easy.addToRunSet(runset, trainsetPos, 'pos')
easy.addToRunSet(runset, trainsetNeg, 'neg')
easy.printRunSetInfo(
    runset,
    printLabels=True,
)

strTrainer = "BOW_Trainer"
strDetector = "BOW_Detector"

list_nWord = [5, 10, 15, 20]

doWithNegativeSample = True

if doWithNegativeSample:
    ###############################################################
Пример #12
0
# Create a list of labelable files under a directory.
lablist2 = easy.getLabelableList("trainImg")
categories2 = easy.getCategories(lablist2)
print("\n=== Corpus 2: ===")
print('Obtained {0} labeled artifact{1} from trainImg directory:'.format(
    len(lablist2), ("s", "")[len(lablist2) == 1]))
easy.printCategoryInfo(categories2)

# Note how both corpora contain flag images, but they have different
# labels.  To use them for evaluation, let's assign the same purpose
# to syntactically different but semantically identical labels.
# Because we don't specify it, this guesses the specific Purpose that
# is assigned to the labels.
# Also obtain this mapping from Purpose to label name, called "classmap."
rs1 = easy.createRunSet(categories1['CA_flag'] + categories2['ca'], "0")
easy.addToRunSet(rs1, categories1['KO_flag'] + categories2['kr'], "1")
easy.addToRunSet(rs1, categories1['US_flag'] + categories2['us'], "2")
print("\n=== The Corpora combined into one RunSet: ===")
easy.printRunSetInfo(rs1)

# A runset can be used for training or for testing
print("------- Bag of Words results for corporate logos: -------")
detector = easy.getDetector("BOW_Detector")
modelfile = "detectors/bowUSKOCA.zip"
results1 = easy.detect(detector, modelfile, rs1)
print("Note that both original and found labels are printed:")
easy.printResults(results1)

# Print again, this time replacing the found labels with a double
# mapping from foundLabel -> guessed Purpose -> classmap label;
# Note that this fails if multiple original labels mapped to the same
Пример #13
0
matz 6/18/2013
'''
import cvac
import easy
import zipfile

#
# create a RunSet from corporate logo images
#
print("==== Training runset: ====")
#trainset = easy.createRunSet( "trainImg" )
trainset = cvac.RunSet()
caset = easy.createRunSet("trainImg/ca")
krset = easy.createRunSet("trainImg/kr")
usset = easy.createRunSet("trainImg/us")
easy.addToRunSet(trainset, caset, cvac.Purpose(cvac.PurposeType.MULTICLASS,0))
easy.addToRunSet(trainset, krset, cvac.Purpose(cvac.PurposeType.MULTICLASS,1))
easy.addToRunSet(trainset, usset, cvac.Purpose(cvac.PurposeType.MULTICLASS,2))
easy.printRunSetInfo( trainset, printLabels=True )

#
# Connect to the trainer for a Bag of Words algorithm, then
# train with the given runset
#
print("starting training, this might take a few minutes...")
trainer = easy.getTrainer( "BOW_Trainer")
trainedModel = easy.train( trainer, trainset )

#
# Display information about the file in which the model is stored;
# this is generally no concern to algorithm users and only of
Пример #14
0
else:
    c = ev.Contender("DPM")
    c.detectorString = "DPM_Detector"
    c.detectorData = "detectors/dpmStarbucksLogo.zip"
    c.foundMap = {'Positive':easy.getPurpose('pos'), 'Negative':easy.getPurpose('neg')}
    contenders.append( c );

# OpenCVCascade, with special settings for anticipated poor performance
if (easy.getTrainer("OpenCVCascadeTrainer")==None):
    print("Cascade service(s) are insufficiently configured, skipping.")
else:
    c = ev.Contender("cascade")
    c.trainerString = "OpenCVCascadeTrainer"
    c.detectorString = "OpenCVCascadeDetector"
    # c.foundMap = {'any':easy.getPurpose('pos')}
    c.foundMap = {'positive':posPurpose, 'negative':negPurpose}
    detector = easy.getDetector(c.detectorString)
    detectorProps = easy.getDetectorProperties(detector)
    c.detectorProps = detectorProps;
    c.detectorProps.props["maxRectangles"] = "200"
    c.detectorProps.minNeighbors = 0; # This prevents hang up in evaluator when training has too few samples
    contenders.append( c );

runset = easy.createRunSet( "trainImg/kr", "pos" )
easy.addToRunSet( runset, "trainImg/ca", "neg" )
easy.printRunSetInfo( runset, printArtifacts=False, printLabels=True )

perfdata = ev.joust( contenders, runset, folds=3 )
ev.printEvaluationResults(perfdata[0])

Пример #15
0
cs = easy.getCorpusServer( "PythonCorpusService:default -p 10021")
corpus = easy.openCorpus( corpus_fname, corpusServer=cs )
categories, lablist = easy.getDataSet( corpus, corpusServer=cs )
print('Obtained {0} labeled artifact{1} from corpus "{2}":'.format(
    len(lablist), ("s","")[len(lablist)==1], corpus.name ));
easy.printCategoryInfo( categories )

# if desired, you can draw the images and their annotations,
# one image at a time, at a given maximum size (width, height)
#easy.drawLabelables( lablist, (512, 512) )

print("==== Training runset: ====")
posPurpose = easy.getPurpose('pos')
negPurpose = easy.getPurpose('neg')
trainset = cvac.RunSet()
easy.addToRunSet(trainset, categories[objname], posPurpose);
#trainset = easy.createRunSet( categories, purpose=posPurpose );
correct = easy.isProperRunSet(trainset, deleteInvalid=True)
if not correct:
    print("failed Integrity test!!!!")
    exit()
#trainset = easy.createRunSet( categories, purpose=posPurpose );
#easy.printRunSetInfo( trainset, printLabels=True )
easy.printRunSetInfo( trainset )

#
# Connect to the trainer for a Bag of Words algorithm, then
# train with the given runset
#
#trainer = easy.getTrainer( "BOW_Trainer")
trainer = easy.getTrainer( "BOW_Trainer:default -p 10103")
Пример #16
0
# Create a list of labelable files under a directory.
lablist2 = easy.getLabelableList( "trainImg" )
categories2 = easy.getCategories(lablist2)
print("\n=== Corpus 2: ===");
print('Obtained {0} labeled artifact{1} from trainImg directory:'.format(
    len(lablist2), ("s","")[len(lablist2)==1]));
easy.printCategoryInfo( categories2 )

# Note how both corpora contain flag images, but they have different
# labels.  To use them for evaluation, let's assign the same purpose
# to syntactically different but semantically identical labels.
# Because we don't specify it, this guesses the specific Purpose that
# is assigned to the labels.
# Also obtain this mapping from Purpose to label name, called "classmap."
rs1 = easy.createRunSet( categories1['CA_flag']+categories2['ca'], "0" )
easy.addToRunSet( rs1, categories1['KO_flag']+categories2['kr'], "1" )
easy.addToRunSet( rs1, categories1['US_flag']+categories2['us'], "2" )
print("\n=== The Corpora combined into one RunSet: ===");
easy.printRunSetInfo( rs1 )

# A runset can be used for training or for testing
print("------- Bag of Words results for corporate logos: -------")
detector = easy.getDetector( "BOW_Detector" )
modelfile = "detectors/bowUSKOCA.zip"
results1 = easy.detect( detector, modelfile, rs1 )
print("Note that both original and found labels are printed:")
easy.printResults( results1 )

# Print again, this time replacing the found labels with a double
# mapping from foundLabel -> guessed Purpose -> classmap label;
# Note that this fails if multiple original labels mapped to the same
Пример #17
0
detector = easy.getDetector( "StruckTracker" )

# a test video; the location is relative to the "CVAC.DataDir"
vfile = "tracks/VTS_01_2.mpg"
runset = cvac.RunSet()

# The tracker needs a labeled location that defines the location
# within the first frame of the video  of the item we want to track.
# In this we define a bounding box around the toy soldiers initial location.
vlab = easy.getLabelable( vfile, labelText="car" )
labloc = cvac.BBox(290, 280,60,30)
lab = cvac.LabeledLocation()
lab.loc = labloc
lab.confidence = 0
lab.sub = vlab.sub
easy.addToRunSet(runset, lab, easy.getPurpose('pos'))
# Setting the verbosity level gives us some feedback while the tracking is done.
props = easy.getDetectorProperties(detector)
props.verbosity = 7
# A model file is not required for this detector
modelfile = None

class MyDetectorCallbackReceiverI(easy.DetectorCallbackReceiverI):
    def __init__(self):
        import easy
        easy.DetectorCallbackReceiverI.__init__(self)
        self.video = cv2.VideoWriter("results.mpg", cv2.cv.CV_FOURCC('P','I','M','1'),25, (720, 480))
        if self.video.isOpened() == False:
            print("Could not create video file!")

    def foundNewResults(self, r2, current=None):
Пример #18
0
import cvac

# a simple RunSet with just one unlabeled image;
# remember that paths are relative to CVAC.DataDir
rs1 = easy.createRunSet( "testImg/italia.jpg" )
print("=== RunSet 1: ===");
easy.printRunSetInfo( rs1, printLabels=True )

# to give samples a purpose, state the purpose:
rs2 = easy.createRunSet( "testImg/italia.jpg", "POSITIVE" )
print("\n=== RunSet 2: ===");
easy.printRunSetInfo( rs2, printLabels=True )

# add more samples to a runset; anything starting with "pos"
# will be added into the POSITIVE sequence of labeled items
easy.addToRunSet( rs2, "testImg/TestKrFlag.jpg", "POS" )
easy.addToRunSet( rs2, "testImg/TestCaFlag.jpg", "neg" )
easy.addToRunSet( rs2, "testImg/TestUsFlag.jpg", "0" )
print("\n=== RunSet 2, after appending: ===");
easy.printRunSetInfo( rs2, printLabels=True )

# create a runset from a folder with sub-folders
rs3 = easy.createRunSet( "trainImg" )
print("\n=== RunSet 3: ===");
easy.printRunSetInfo( rs3, printLabels=True )

# you can check wether the runset has been properly constructed:
if easy.isProperRunSet( rs3 ):
    print("correctly constructed runset")
else:
    print("improperly constructed runset")
Пример #19
0
cs = easy.getCorpusServer("PythonCorpusService:default -p 10021")
corpus = easy.openCorpus(corpus_fname, corpusServer=cs)
categories, lablist = easy.getDataSet(corpus, corpusServer=cs)
print('Obtained {0} labeled artifact{1} from corpus "{2}":'.format(
    len(lablist), ("s", "")[len(lablist) == 1], corpus.name))
easy.printCategoryInfo(categories)

# if desired, you can draw the images and their annotations,
# one image at a time, at a given maximum size (width, height)
#easy.drawLabelables( lablist, (512, 512) )

print("==== Training runset: ====")
posPurpose = easy.getPurpose('pos')
negPurpose = easy.getPurpose('neg')
trainset = cvac.RunSet()
easy.addToRunSet(trainset, categories[objname], posPurpose)
#trainset = easy.createRunSet( categories, purpose=posPurpose );
correct = easy.isProperRunSet(trainset, deleteInvalid=True)
if not correct:
    print("failed Integrity test!!!!")
    exit()
#trainset = easy.createRunSet( categories, purpose=posPurpose );
#easy.printRunSetInfo( trainset, printLabels=True )
easy.printRunSetInfo(trainset)

#
# Connect to the trainer for a Bag of Words algorithm, then
# train with the given runset
#
#trainer = easy.getTrainer( "BOW_Trainer")
trainer = easy.getTrainer("BOW_Trainer:default -p 10103")