def testClassifier(classifierFilename, case): assert case == "lena" or case == "car", "case parameter should be lena or car" superPixelClassifier = pomio.unpickleObject(classifierFilename) print "\n*Loaded classifier [ ", type( superPixelClassifier), "] from:", classifierFilename image = None orientation = None if case == "car": print "*Loading MSRC car image::" image = pomio.msrc_loadImages( "/home/amb/dev/mrf/data/MSRC_ObjCategImageDatabase_v2", ['Images/7_3_s.bmp'])[0].m_img orientation = "lower" elif case == "lena": print "*Loading Lena.jpg" image = skimage.data.lena() orientation = "upper" print "*Predicting superpixel labels in image::" numberSuperPixels = 400 superPixelCompactness = 10 [superPixelLabels, superPixelsMask] = predictSuperPixelLabels(superPixelClassifier, image, numberSuperPixels, superPixelCompactness) carSuperPixelLabels = getSuperPixelLabelledImage(image, superPixelsMask, superPixelLabels) plotSuperPixelImage(image, carSuperPixelLabels, orientation)
def test(): classifierLocation = "/home/amb/dev/mrf/classifiers/logisticRegression/superpixel/logReg_miniMSRC.pkl" classifier = pomio.unpickleObject(classifierLocation) carFile = "7_3_s.bmp" msrcData = "/home/amb/dev/mrf/data/MSRC_ObjCategImageDatabase_v2" car = pomio.msrc_loadImages(msrcData, ["Images/" + carFile])[0] groundTruth = car.m_gt mask = superPixels.getSuperPixels_SLIC(car.m_img, 400, 10) spLabels = SuperPixelClassifier.predictSuperPixelLabels( classifier, car.m_img, 400, 10, True)[0] prediction = SuperPixelClassifier.getSuperPixelLabelledImage( car.m_img, mask, spLabels) # save prediction to file pomio.writeMatToCSV(prediction, "/home/amb/dev/mrf/eval/testPrediction1.labels") results = evaluatePrediction(prediction, groundTruth, carFile) print "\nINFO: Car test eval results::\n\t", results classResults = evaluateClassPerformance(prediction, groundTruth) print "\nINFO: Car test eval class results::\n\t", classResults confusionResults = evaluateConfusionMatrix(prediction, groundTruth) print "\nINFO: Car test eval confusion matrix results::\n\t", "Just sum up entries... ", np.sum( confusionResults)
def testClassifier(classifierFilename, case): assert case=="lena" or case=="car" , "case parameter should be lena or car" superPixelClassifier = pomio.unpickleObject(classifierFilename) print "\n*Loaded classifier [ " , type(superPixelClassifier) , "] from:" , classifierFilename image = None orientation = None if case == "car": print "*Loading MSRC car image::" image = pomio.msrc_loadImages("/home/amb/dev/mrf/data/MSRC_ObjCategImageDatabase_v2", ['Images/7_3_s.bmp'] )[0].m_img orientation = "lower" elif case == "lena": print "*Loading Lena.jpg" image = skimage.data.lena() orientation = "upper" print "*Predicting superpixel labels in image::" numberSuperPixels = 400 superPixelCompactness = 10 [superPixelLabels, superPixelsMask] = predictSuperPixelLabels(superPixelClassifier, image,numberSuperPixels, superPixelCompactness) carSuperPixelLabels = getSuperPixelLabelledImage(image, superPixelsMask, superPixelLabels) plotSuperPixelImage(image, carSuperPixelLabels, orientation)
def test(): # TODO use reference classifier classifierName = "/home/amb/dev/mrf/classifiers/randomForest/superpixel/randyForest_superPixel_maxDepth15_0.6Data.pkl" classifier = pomio.unpickleObject(classifierName) carFile = "7_3_s.bmp" msrcData = "/home/amb/dev/mrf/data/MSRC_ObjCategImageDatabase_v2" car = pomio.msrc_loadImages(msrcData, ["Images/" + carFile])[0] groundTruth = car.m_gt mask = SuperPixels.getSuperPixels_SLIC(car.m_img, 400, 10) spLabels = SuperPixelClassifier.predictSuperPixelLabels( classifier, car.m_img, 400, 10)[0] prediction = SuperPixelClassifier.getSuperPixelLabelledImage( car.m_img, mask, spLabels) # save prediction to file pomio.writeMatToCSV( prediction, "/home/amb/dev/eval/test/predict/testPrediction1.labels") results = evaluatePrediction(prediction, groundTruth) print "\nINFO: Car test eval results::\n\t", results
def getAdjProbs(name): if name != None and len(name)>0: print 'Loading adjacency probs...' adjProbs = pomio.unpickleObject(name) # This is actually a bunch of counts. Some will be zero, which is probably # a sampling error, so let's offset with some default number of counts. adjProbs += 10.0 # Now turn it into normalised probabilities. # todo: hey but this is not normalised for default class probability! adjProbs /= adjProbs.sum() # transform adjProbs = -np.log( adjProbs ) else: adjProbs = None return adjProbs
def getAdjProbs(name): if name != None and len(name) > 0: print 'Loading adjacency probs...' adjProbs = pomio.unpickleObject(name) # This is actually a bunch of counts. Some will be zero, which is probably # a sampling error, so let's offset with some default number of counts. adjProbs += 10.0 # Now turn it into normalised probabilities. # todo: hey but this is not normalised for default class probability! adjProbs /= adjProbs.sum() # transform adjProbs = -np.log(adjProbs) else: adjProbs = None return adjProbs
def test(): # TODO use reference classifier classifierName = "/home/amb/dev/mrf/classifiers/randomForest/superpixel/randyForest_superPixel_maxDepth15_0.6Data.pkl" classifier = pomio.unpickleObject(classifierName) carFile = "7_3_s.bmp" msrcData = "/home/amb/dev/mrf/data/MSRC_ObjCategImageDatabase_v2" car = pomio.msrc_loadImages(msrcData , [ "Images/" + carFile ] )[0] groundTruth = car.m_gt mask = SuperPixels.getSuperPixels_SLIC(car.m_img, 400, 10) spLabels = SuperPixelClassifier.predictSuperPixelLabels(classifier, car.m_img,400,10)[0] prediction = SuperPixelClassifier.getSuperPixelLabelledImage(car.m_img, mask, spLabels) # save prediction to file pomio.writeMatToCSV(prediction, "/home/amb/dev/eval/test/predict/testPrediction1.labels") results = evaluatePrediction(prediction, groundTruth) print "\nINFO: Car test eval results::\n\t" , results
parser.add_argument('--nshow', type=int, default=3,\ help='Max number of features to show at once on scatter plot grid') parser.add_argument('--nstart', type=int, default=0,\ help='Index of feature to start at') args = parser.parse_args() import amntools import matplotlib.pyplot as plt import pomio plt.interactive(1) # Load the features and labels if args.ftrs.endswith('.pkl'): ftrs = pomio.unpickleObject(args.ftrs) else: ftrs = pomio.readMatFromCSV(args.ftrs) N = ftrs.shape[0] D = ftrs.shape[1] print '%d feature vectors of dimensionality = %d' % (N, D) if args.labs == None: labs = None else: if args.labs.endswith('.pkl'): labs = pomio.unpickleObject(args.labs) else: labs = pomio.readMatFromCSV(args.labs).astype(np.int32) # show labels
import pomio import slic import superPixels import skimage import isprs import amntools imgRGB = amntools.readImage(args.imagefile) if len(args.spfile) == 0: numberSuperPixels = args.nbSuperPixels superPixelCompactness = args.superPixelCompactness # Turn image into superpixels. spix = superPixels.computeSuperPixelGraph( imgRGB, 'slic', [numberSuperPixels, superPixelCompactness]) elif args.spfile.endswith('.pkl'): superPixelInput = pomio.unpickleObject(args.spfile) spix = superPixelInput[0] classProbs = superPixelInput[1] colourMap = pomio.msrc_classToRGB elif args.spfile.endswith('.mat'): spix, classProbs = isprs.loadISPRSResultFromMatlab(args.spfile) colourMap = isprs.colourMap else: assert False # Display superpixel boundaries on image. plt.imshow( superPixels.generateImageWithSuperPixelBoundaries(imgRGB, spix.m_labels)) plt.show()
description='Apply superPixel classifier to an image.') parser.add_argument('clfrFn', type=str, action='store', \ help='filename of pkl or csv superPixel classifier file') parser.add_argument('infile', type=str, action='store', \ help='filename of input image to be classified') parser.add_argument('--outfile', type=str, action='store', \ help='filename of output image to be classified') parser.add_argument('--verbose', action='store_true') parser.add_argument('--nbSuperPixels', type=int, default=400, \ help='Desired number of super pixels in SLIC over-segmentation') parser.add_argument('--superPixelCompactness', type=float, default=10.0, \ help='Super pixel compactness parameter for SLIC') args = parser.parse_args() clfrFn = args.clfrFn clfr = pomio.unpickleObject(clfrFn) infile = args.infile outfile = args.outfile numberSuperPixels = args.nbSuperPixels superPixelCompactness = args.superPixelCompactness if args.verbose: plt.interactive(1) plt.figure() pomio.showClassColours() plt.figure() print 'Classifying file ', args.infile image = skimage.io.imread(args.infile) [spClassPreds, spGraph
assert clfrType in ['logreg', 'randyforest'], \ 'Unknown classifier type ' + clfrType # Check can write these files. if outfile != None: f = open(outfile, 'w') f.close() clfr = None labs = None ftrs = None # Load the features and labels if infileFtrs.endswith('.pkl'): ftrs = pomio.unpickleObject(infileFtrs) else: ftrs = pomio.readMatFromCSV(infileFtrs) D = ftrs.shape[1] print 'Feature dimensionality = ', D if infileLabs.endswith('.pkl'): labs = pomio.unpickleObject(infileLabs) else: labs = pomio.readMatFromCSV(infileLabs).astype(np.int32) n = len(labs) assert n == ftrs.shape[0], 'Error: there are %d labels and %d training examples' \ % ( n, ftrs.shape[0] ) assert np.all(np.isfinite(ftrs))
#classProbs = classProbs[:,:, np.array([1,2,5,3,4])-1] else: # super-pixel probs spix, classProbsLUT = isprs.loadISPRSResultFromMatlab( args.matFn ) classLabs = spix.m_labels # map the labels to HxWxC class probabilities matrix classProbs = np.zeros( classLabs.shape + (classProbsLUT.shape[1],) ) for c in range( classProbsLUT.shape[1] ): # Get a mask of matching pixels classProbs[ :,:, c ] = classProbsLUT[ classLabs, c ] classNames = isprs.classLabels colourMap = isprs.colourMap else: print 'Computing class probabilities...' print 'Loading classifier...' clfr = pomio.unpickleObject(clfrFn) ftype = 'classic' classLabs, classProbs = classification.classifyImagePixels(imgRGB, clfr, \ ftype, True) print 'done. result size = ', classProbs.shape print ' classes = ', clfr.classes_ # Transform class probs to the correct sized matrix. nbRows = imgRGB.shape[0] nbCols = imgRGB.shape[1] nbClasses = pomio.getNumClasses() cpnew = np.zeros( (nbRows, nbCols, nbClasses) ) for i in range( classProbs.shape[2] ): # stuff this set of probs to new label cpnew[:,:,clfr.classes_[i]] = classProbs[:,:,i]
'Unknown classifier type ' + clfrType # Check can write these files. if outfile != None: f=open(outfile,'w') f.close() clfr = None labs = None ftrs = None # Load the features and labels if infileFtrs.endswith('.pkl'): ftrs = pomio.unpickleObject( infileFtrs ) else: ftrs = pomio.readMatFromCSV( infileFtrs ) D = ftrs.shape[1] print 'Feature dimensionality = ', D if infileLabs.endswith('.pkl'): labs = pomio.unpickleObject( infileLabs ) else: labs = pomio.readMatFromCSV( infileLabs ).astype(np.int32) n = len(labs) assert n == ftrs.shape[0], 'Error: there are %d labels and %d training examples' \ % ( n, ftrs.shape[0] ) assert np.all( np.isfinite( ftrs ) )
# Class vars K = args.K spix = None classProbs = None adjProbs = None precomputedMode = args.infile.endswith('.pkl') or args.infile.endswith('.mat') if precomputedMode == True: # If the input file is a pkl (not image) assume we've run necessary superpixel classifier, and input is class label probabilities # Input is assumed to be a tuple [superpixels, classProbs] print "Using pre-computed superpixels and class label probabilities" if args.infile.endswith('.pkl'): superPixelInput = pomio.unpickleObject(args.infile) spix = superPixelInput[0] classProbs = superPixelInput[1] colourMap = pomio.msrc_classToRGB else: spix, classProbs = isprs.loadISPRSResultFromMatlab( args.infile ) colourMap = isprs.colourMap else: # Assume input image needs processing and classifying print "Superpixel generation mode" numberSuperPixels = args.nbSuperPixels superPixelCompactness = args.superPixelCompactness
parser.add_argument('--nshow', type=int, default=3,\ help='Max number of features to show at once on scatter plot grid') parser.add_argument('--nstart', type=int, default=0,\ help='Index of feature to start at') args = parser.parse_args() import amntools import matplotlib.pyplot as plt import pomio plt.interactive(1) # Load the features and labels if args.ftrs.endswith('.pkl'): ftrs = pomio.unpickleObject( args.ftrs ) else: ftrs = pomio.readMatFromCSV( args.ftrs ) N = ftrs.shape[0] D = ftrs.shape[1] print '%d feature vectors of dimensionality = %d' % (N,D) if args.labs == None: labs = None else: if args.labs.endswith('.pkl'): labs = pomio.unpickleObject( args.labs ) else: labs = pomio.readMatFromCSV( args.labs ).astype(np.int32)
# Class vars K = args.K spix = None classProbs = None adjProbs = None precomputedMode = args.infile.endswith('.pkl') or args.infile.endswith('.mat') if precomputedMode == True: # If the input file is a pkl (not image) assume we've run necessary superpixel classifier, and input is class label probabilities # Input is assumed to be a tuple [superpixels, classProbs] print "Using pre-computed superpixels and class label probabilities" if args.infile.endswith('.pkl'): superPixelInput = pomio.unpickleObject(args.infile) spix = superPixelInput[0] classProbs = superPixelInput[1] colourMap = pomio.msrc_classToRGB else: spix, classProbs = isprs.loadISPRSResultFromMatlab(args.infile) colourMap = isprs.colourMap else: # Assume input image needs processing and classifying print "Superpixel generation mode" numberSuperPixels = args.nbSuperPixels superPixelCompactness = args.superPixelCompactness imgRGB = amntools.readImage(args.infile)
from matplotlib import cm import pomio import slic import superPixels import skimage import isprs import amntools imgRGB = amntools.readImage(args.imagefile) if len(args.spfile) == 0: numberSuperPixels = args.nbSuperPixels superPixelCompactness = args.superPixelCompactness # Turn image into superpixels. spix = superPixels.computeSuperPixelGraph(imgRGB, "slic", [numberSuperPixels, superPixelCompactness]) elif args.spfile.endswith(".pkl"): superPixelInput = pomio.unpickleObject(args.spfile) spix = superPixelInput[0] classProbs = superPixelInput[1] colourMap = pomio.msrc_classToRGB elif args.spfile.endswith(".mat"): spix, classProbs = isprs.loadISPRSResultFromMatlab(args.spfile) colourMap = isprs.colourMap else: assert False # Display superpixel boundaries on image. plt.imshow(superPixels.generateImageWithSuperPixelBoundaries(imgRGB, spix.m_labels)) plt.show()