def pre_process_data(images): """Pre-process the data folder to find all images and crop all faces. Return: ImageSet of all faces. """ face_haar_cascade = HaarCascade('face2.xml') cropped_images = ImageSet() for image in images: cropped_images.extend(get_faces(image, face_haar_cascade)) return cropped_images
def build_bg(): for n in range(BG_PICS): pn = bgname.format(n) save_picture(pn) sleep(FRAME_DELAY) camera.stop_preview() frames = ImageSet() frames.load(bgdir) img = Image(frames[0].size()) nframes = len(frames) for frame in frames: img = img + (frame / nframes) img.save(bgf) return img
def run_trainer(): snack_trainer = SnackTrainer() snack_trainer.parse_options(sys.argv) debug = snack_trainer.options.debug if snack_trainer.options.classes == "": classes = snack_trainer.getClassNameFromPath( snack_trainer.options.train_path) else: classes = snack_trainer.options.classes.split(',') trainPaths = [snack_trainer.options.train_path + '/' + c for c in classes] testPaths = [snack_trainer.options.test_path + '/' + c for c in classes] extractors = [ snack_trainer.createExtractor('hue'), snack_trainer.createExtractor('edge'), snack_trainer.createExtractor('haar') ] resultPath = snack_trainer.options.result_path featurePath = snack_trainer.options.feature_path classifierFile = snack_trainer.options.classifier_file classifier_name = snack_trainer.options.classifier classifier = snack_trainer.createClassifier(classifier_name, extractors) snack_trainer.setClassifier(classifier) print "Using Classifier:", classifier_name print "Training Set:", trainPaths print "Training Features Save As:", featurePath snack_trainer.trainClassifier(classes, snack_trainer.options.train_path, featurePath) if classifierFile == "": classifierFile = "static/trainer/" + "%s.dat" % (classifier_name) print "Classifier Data Save As:", classifierFile classifier.save(classifierFile) if (debug): print "Testing Set:", testPaths imgs = ImageSet() for p in testPaths: imgs += ImageSet(p) random.shuffle(imgs) snack_trainer.testClassifier(classifier, classes, testPaths) print "Test Result:", resultPath snack_trainer.saveResults(classifier, imgs, resultPath) print "Done"
def analyze(self): image_set = ImageSet(self.in_path) image_set.sort() report_gen = CSVReportGenerator(os.path.join(self.report_path, 'noise_analysis.csv')) counter = 1 print 'Extracting using %s' % self.method_name for image in sorted(image_set, key=lambda img: img.filename): filename = os.path.splitext(os.path.basename(image.filename))[0] noise = self.analyze_single(image) #print 'Analyzing %d/%d: %s' % (counter, len(image_set.filelist), filename) print '%.2f' % noise counter += 1 report_gen.generate()
def GetSpecificCardData(suit, rank, path="./data/", label=True): fullpath = path + "/" + suit + "/" + rank + "/" print fullpath iset = ImageSet(fullpath) if (label): label_vals = [] l = (suit, rank) # not sure this is how we want to do this sz = len(iset) for i in range(0, sz): label_vals.append(l) return iset, label_vals else: return iset
def main(): data_batch_1 = ['/Users/linting/Desktop/CSC522/Project/simplecv/data/cifar-10-batches-mat/data_batch_1/'+c for c in classes ] data_batch_2 = ['/Users/linting/Desktop/CSC522/Project/simplecv/data/cifar-10-batches-mat/data_batch_2/'+c for c in classes ] data_batch_3 = ['/Users/linting/Desktop/CSC522/Project/simplecv/data/cifar-10-batches-mat/data_batch_3/'+c for c in classes ] data_batch_4 = ['/Users/linting/Desktop/CSC522/Project/simplecv/data/cifar-10-batches-mat/data_batch_4/'+c for c in classes ] data_batch_5 = ['/Users/linting/Desktop/CSC522/Project/simplecv/data/cifar-10-batches-mat/data_batch_5/'+c for c in classes ] trainPaths = data_batch_1 + data_batch_2 + data_batch_3 + data_batch_4 + data_batch_5 testPaths = ['/Users/linting/Desktop/CSC522/Project/simplecv/data/cifar-10-batches-mat/test_batch/'+c for c in classes] trainer = Trainer(classes,trainPaths) print "Start training....." trainer.train() imgs = ImageSet() for p in testPaths: imgs += ImageSet(p) random.shuffle(imgs) print "Result test" trainer.test(testPaths)
def extract(self): image_set = ImageSet(self.data_path) image_set.sort() output_path = os.path.join(self.result_path, self.__experiment.name + '.csv') report_gen = CSVReportGenerator(output_path, params=self.params) counter = 1 print 'Extracting using %s' % self.method_name for image in sorted(image_set, key=lambda img: img.filename): filename = os.path.splitext(os.path.basename(image.filename))[0] instance = session.query(Analysis).filter_by( filename=image.filename, experiment_name=self.__experiment.name, experiment_params=self.__experiment.params).first() if instance: analysis = instance else: try: analysis = self.analyze_mono_bead(image) analysis.experiment = self.__experiment session.add(analysis) print 'Analyzing %d/%d: %s' % ( counter, len(image_set.filelist), filename) except NoBeadException: print 'No Bead Exception: %s' % filename # Sholl Analysis Plots #self.plot_sholl_analysis(analysis, filename) # Add to overall report report_gen.add_analysis(filename, analysis) counter += 1 session.commit() report_gen.generate()
def GetFullDataSet(path="./data", label=True): # just load everything data = ImageSet() labels = [] for s in SUITS: for r in RANKS: if (label): d, l = GetSpecificCardData(s, r, path, label) data += d labels += l else: d = GetSpecificCardData(s, r, path, label) data += d if (label): return data, labels else: return data
def train(self, digits_path): for digit_to_train in range(-1, 10): logging.info("Training digit " + str(digit_to_train)) digit_images = ImageSet(digits_path + str(digit_to_train)) logging.debug("Loaded " + str(len(digit_images)) + " digits") for digit_image in digit_images: self.train_image(digit_image, digit_to_train) logging.info("Digit " + str(digit_to_train) + " trained") self.train_network()
#!/usr/bin/env python import logging logging.getLogger().setLevel(logging.INFO) from SimpleCV import ImageSet from GasMeter import GasMeter def is_number(s): try: float(s) return True except ValueError: return False test_frames = ImageSet("./images/input") for frame in test_frames: gas = GasMeter(frame) value = gas.get_meter_value() if is_number(value): print(frame.filename + "\t" + "{0:.3f}".format(float(value))) else: print(frame.filename + "\t" + value + " UNRELIABLE")
import os from time import sleep from SimpleCV import ImageSet from utils import PreparedCamera # Settings cam_size = {'width': 640, 'height': 480} gif_interval = 0.5 # Seconds between frames gif_length = 10 # Length in seconds file_name = os.path.join('pictures', 'ani.gif') cam = PreparedCamera(0, cam_size, debug=True) print("Recording images") img_set = ImageSet() for frame in range(0, int(gif_length * gif_interval)): img = cam.getImage() img_set.append(img) sleep(1.0/gif_interval) img_set.save(destination=file_name, dt=gif_interval)
from SimpleCV import ImageSet set = ImageSet(".") for img in set: oldname = img.filename newname = oldname[0:-3] + 'jpg' print "Converting " + oldname + " to " + newname img.save(newname)
def main( args ): # # Set these flags so they can be checked for validity later. # res = None fac = None # # Check for any args that can safely be defaulted. # if args.dest: outdir = args.dest # # Append a trailing slash if it's not there. # if outdir[-1] != '/': outdir = outdir + '/' else: outdir = 'scaled_thumbs/' # # Check for scale or resolution. The default action is to scale # by 1/2. # if args.res: (width, height) = args.res.split('x') # # Just set this to something other than None, so the script can # tell whether or not to use the resolution later. # res = args.res elif args.fac: # # Limit the scale factor so super-large images are made even bigger. # fac = float(args.fac) if fac >= 2.0: fac = 2.0 if fac <= 0.0: fac = 0.1 else: fac = .5 # # Make sure the new files have a home. # if not isdir(outdir): mkdir(outdir) # # Load the files from the command line # images = ImageSet() _info_('Adding images to image set... this may take a moment.') for item in args.files: # # Make sure I don't try to convert something that's not an image. # try: image = Image(item) except IOError, err: _err_("Invalid/unuseable file: " + item) exit(2) images.append(image)
from SimpleCV import Image, Display, ImageSet, Color, ROI import numpy as np import os as os sz = 256 count = 0 outdir = './faces/' if not os.path.exists(outdir): os.mkdir(outdir) negTotal = 0 negcount = 5 negdir = './negs/' if not os.path.exists(negdir): os.mkdir(negdir) disp = Display() iset = ImageSet('data') for img in iset: img.save(disp) face = img.findHaarFeatures('face.xml') if (face is not None and len(face) > 0): face[-1].draw(width=3) img.applyLayers().save(disp) fname = outdir + 'Face' + str(count) + '.png' face[-1].crop().resize(sz, sz).toGray().save(fname) print "Saving: " + fname count = count + 1 ncount = 0 while ncount < negcount: pt = 256 * np.random.rand(1, 2) roi = ROI( np.round((img.width - sz) * np.random.rand(1))[0],
from SimpleCV import Camera, ImageSet import time cam = Camera() camImages = ImageSet() # Set to a maximum of 10 images saved # Feel free to increase, but bewared running out of space maxImages = 10 for counter in range(maxImages): # Capture a new image and add to set img = cam.getImage() camImages.append(img) # Show the image and wait before capturing another img.show() time.sleep(6) camImages.save(verbose=True)
def __init__(self, source_paths, out_path, classList, key_bindings, preprocess=None, postprocess=None): #if( not os.access(out_path,os.W_OK) ): # print "Output path is not writeable." # raise Exception("Output path is not writeable.") self.keyBindings = key_bindings self.classes = classList self.countMap = {} self.classMap = {} self.directoryMap = {} self.out_path = out_path self.keyMap = {} if (len(classList) != len(key_bindings)): print "Must have a key for each class." raise Exception("Must have a key for each class.") for key, cls in zip(key_bindings, classList): self.keyMap[key] = cls # this should work if (preprocess is None): def fakeProcess(img): return [img] preprocess = fakeProcess self.preProcess = preprocess if (postprocess is None): def fakePostProcess(img): return img postprocess = fakePostProcess self.postProcess = postprocess self.srcImgs = ImageSet() if (isinstance(source_paths, ImageSet)): self.srcImgs = source_path else: for sp in source_paths: print "Loading " + sp imgSet = ImageSet(sp) print "Loaded " + str(len(imgSet)) self.srcImgs += imgSet if (not osp.exists(out_path)): os.mkdir(out_path) for c in classList: outdir = out_path + c + '/' self.directoryMap[c] = outdir if (not osp.exists(outdir)): os.mkdir(outdir) for c in classList: searchstr = self.directoryMap[c] + '*.png' fc = glob.glob(searchstr) self.countMap[c] = len(fc) self.classMap[c] = ImageSet(self.directoryMap[c])
from SimpleCV import Camera, ImageSet import time cam = Camera() camImages = ImageSet() maxImages = 10 for i in range(maxImages): # Capture a new image img = cam.getImage() # Add image to set camImages.append(img) # Show the image and wait before capturing another img.show() time.sleep(1) camImages.save(destination="./images/imagesets/")
import numpy from TemplateDigitDetector import TemplateDigitDetector from SVCDigitDetector import SVCDigitDetector # Simple script for evaluating Digit detectors svc_detector = SVCDigitDetector() template_detector = TemplateDigitDetector() svc_detector_success = [] template_detector_success = [] for test_digit in range(10): test_samples = ImageSet("./images/dataset-test/" + str(test_digit)) for test_sample in test_samples: svc_digit = svc_detector.detect_digit(test_sample) template_digit = template_detector.detect_digit(test_sample) print("svc_digit:" + str(svc_digit) + " template_digit:" + str(template_digit)) if svc_digit != test_digit: svc_detector_success.append(0) else: svc_detector_success.append(100) if template_digit != test_digit:
from SimpleCV import ImageSet import time images = ImageSet("C:\Users\saurav datta\Documents\python learning\simpleCV learnings") images.show(2) # 2nd argument is delay between slide show # display all the images ina folder as slide show
from SimpleCV import Camera, ImageSet import time cam = Camera() camImages = ImageSet() # Set to a maximum of 10 images saved # Feel free to increase, but beware of running out of space maxImages = 5 for counter in range(maxImages): # Capture a new image and add to set img = cam.getImage() camImages.append(img) # Show the image and wait before capturing another img.show() time.sleep(2) camImages.save(destination='imageset1', verbose=True)
from SimpleCV import ImageSet img_set = ImageSet(".") for img in img_set: oldname = img.filename newname = oldname[0:-3] + 'jpg' print 'Converting ' + oldname + ' to ' + newname img.save(newname)
y2 = np.round(imgsz * np.random.rand(1, nDesc))[0].tolist() p1 = zip(x1, y1) p2 = zip(x2, y2) descriptors = zip(p1, p2) def extract(iset, nDesc, descriptors): posCounts = np.zeros([1, nDesc])[0] for face in iset: for idx, d in enumerate(descriptors): if (face[d[0][0], d[0][1]][0] > face[d[1][0], d[1][1]][0]): posCounts[idx] += 1 return np.array(posCounts) / len(iset) faces = ImageSet('./faces/') faceResult = extract(faces, nDesc, descriptors) print faceResult notFaces = ImageSet('./negs/') negResult = extract(notFaces, nDesc, descriptors) print negResult fig = plt.figure() ax = fig.add_subplot(111) ind = np.arange(nDesc) width = 0.5 rects1 = ax.bar(ind, faceResult, width, color='r') rects2 = ax.bar(ind + width, negResult, width, color='b') # add some ax.set_ylabel('Percentage with descriptor == 1') ax.set_title('Random Binary Descriptor Incidence') ax.legend((rects1[0], rects2[0]), ('faces', 'notfaces'))
from SimpleCV import ColorSegmentation, Image, Display, ImageSet import time redBlock = Image('redblock.png') greenBlock = Image('greenblock.png') blueBlock = Image('blueblock.png') cs = ColorSegmentation() cs.addToModel(redBlock) cs.addToModel(greenBlock) cs.addToModel(blueBlock) cards = ImageSet('cards') card = None disp = Display((320, 240)) score = 0 isPrimary = False while (cards or card) and disp.isNotDone(): if card is None: card = cards.pop() cs.addImage(card) res = cs.getSegmentedImage() color = res.meanColor() if ((color[0] < 254) and (color[1] < 254) and (color[2] < 254)): isPrimary = True
# -*- coding: utf-8 -*- from SimpleCV import ImageSet set = ImageSet("ImageSetFolder/.") for img in set: oldname = img.filename newname = oldname[0:-3] + 'jpg' print "Converting " + oldname + " to " + newname img.save(newname)