def upload_image(): if request.method == "POST": if request.files: image = request.files["image"] if image.filename == "": # print("Selecione uma imagem!") return redirect(request.url) if not allowed_image(image.filename): # flash("A extensão do ficheiro selecionado não é suportada!") return redirect(request.url) else: filename = secure_filename(image.filename) image.save(os.path.join(app.config["UPLOAD_FOLDER"], filename)) im = ImageClassifier() im.write_image(filename, im.classify(os.path.join(app.config["UPLOAD_FOLDER"], filename)), app.config["UPLOAD_FOLDER"]) return render_template('result.html', filename = filename) return render_template('homepage.html')
def process_video(file_name, sub_clip_from=0, sub_clip_to=0, visualization=True): global num_frames_global num_frames_global = 0 imgEng = ImageEngine(load_setup=True) clfLinearSVC = ImageClassifier('clf_linear') clfSVC = ImageClassifier('clf_rbf') global processor processor = FrameProcessor(imgEng, clfLinearSVC, clfSVC, baseWindowSize, detectionRegions, visualization=visualization, heatMapFrames=5, heatMapThreshold=15, heatMapTotalMin=1000, heatMapTotalMinFrame=200) v_clip = VideoFileClip(input_dir_path + file_name) if sub_clip_to > 0: v_clip = v_clip.subclip(sub_clip_from, sub_clip_to) white_clip = v_clip.fl_image(process_image) white_clip.write_videofile(output_dir_path + file_name, audio=False) print("Video is processed. Frames: {0}.".format(num_frames_global)) return
def test_predict(self): """ Test predict methods on 2d array. """ proba_shape = (2, 2) clf = ImageClassifier(n_in=8, n_out=2, filters=[2,2]) clf.fit(X,y) assert_equal(clf.predict_proba(X[:2]).shape, proba_shape) assert_equal(clf.predict(X[:2]).shape, y[:2].shape)
def classifyTwitterAccount(self, account, config, twitter_id=None, tweet_id=None): result = 'unknown' # classify name if result == 'unknown': try: result = self.name_classifier.classifyName(account.name) result = result.lower() except: raise Exception('Error in name recognition') # if name classification had no result try image classification if result == 'unknown': try: result = ImageClassifier().classifyImage(account.profile_image_url.replace('normal', '400x400'), config['faceplusplus']) result = result.lower() except: raise Exception('Error in image recognition') if tweet_id is not None: result = {'tweetId': tweet_id, 'gender': result} else: if twitter_id is not None: result = {'accountId': twitter_id, 'gender': result} else: result = {'accountId': account['screen_name'], 'gender': result} return result
def main(args): writer = MlflowWriter(args.exp_name) writer = write_log_base(args, writer) logger = CustomMlFlowLogger(writer) pl.seed_everything(args.seed) model = mobilenet_v2(pretrained=True, num_classes=args.num_classes) datamodule = AnimeFaceDataModule(args) criterion = nn.CrossEntropyLoss() plmodel = ImageClassifier(args, model, criterion) trainer = pl.Trainer( logger=logger, checkpoint_callback=False, gpus=2, max_epochs=args.epochs, flush_logs_every_n_steps=args.print_freq, log_every_n_steps=args.log_freq, accelerator="dp", precision=16 if args.apex else 32, deterministic=True, num_sanity_val_steps=-1, ) starttime = time.time() # 実行時間計測(実時間) trainer.fit(plmodel, datamodule=datamodule) trainer.test(plmodel, datamodule=datamodule, verbose=True) writer.move_mlruns() # 実行時間表示 endtime = time.time() interval = endtime - starttime print("elapsed time = {0:d}h {1:d}m {2:d}s".format( int(interval / 3600), int((interval % 3600) / 60), int((interval % 3600) % 60), ))
def test_get_classification(self): classifier = ImageClassifier("../data/saved_models/1587154471") image_3 = Image.open("./validation/xestlvphik_0.png") result = classifier.get_classification(image_3) self.assertTrue(result.__eq__(3)) image_plus = Image.open("./validation/xestlvphik_1.png") result = classifier.get_classification(image_plus) self.assertTrue(result.__eq__(0)) image_9 = Image.open("./validation/xestlvphik_2.png") result = classifier.get_classification(image_9) self.assertTrue(result.__eq__(9))
def classifyTwitterAccount(self, account, config, twitter_id=None, tweet_id=None): result = 'unknown' # classify name if result == 'unknown': try: result = self.name_classifier.classifyName(account.name) result = result.lower() except: raise Exception('Error in name recognition') # if name classification had no result try image classification if result == 'unknown': try: result = ImageClassifier().classifyImage( account.profile_image_url.replace('normal', '400x400'), config['faceplusplus']) result = result.lower() except: raise Exception('Error in image recognition') if tweet_id is not None: result = {'tweetId': tweet_id, 'gender': result} else: if twitter_id is not None: result = {'accountId': twitter_id, 'gender': result} else: result = { 'accountId': account['screen_name'], 'gender': result } return result
def processFrame(src_name, visualization=True, show_diagram=False): img = cv2.imread(input_dir_path + src_name) imgEng = ImageEngine(load_setup=True) clfLinearSVC = ImageClassifier('clf_linear') clfSVC = ImageClassifier('clf_rbf') processor = FrameProcessor(imgEng, clfLinearSVC, clfSVC, baseWindowSize, detectionRegions, visualization=visualization, heatMapFrames=1, heatMapThreshold=2, heatMapTotalMin=200, heatMapTotalMinFrame=200) processor.processFrame(img) if visualization: cv2.imwrite(all_boxes_dir_path + src_name, processor.visAllBoxesImage) cv2.imwrite(vehicle_boxes_dir_path + src_name, processor.visVehicleBoxesImage) cv2.imwrite(heat_map_dir_path + src_name, processor.visHeatMapImage) cv2.imwrite(annotated_dir_path + src_name, processor.visImageAnnotated) if show_diagram: # Visualize img binary f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10)) ax1.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) ax1.set_title('Original Image', fontsize=30) ax2.imshow( cv2.cvtColor(processor.visVehicleBoxesImage, cv2.COLOR_BGR2RGB)) ax2.set_title('Annotated Image', fontsize=30) plt.show()
def runTest(D=None, EPOCHS=10, BATCH_SIZE=128, rate=0.001, pre_ops=[], network=MT.LeNet, network_args={}): if D is None: D = IC() STR = "EP-{}_BS-{}_R-{}_OPS-{}-NET-{}".format( EPOCHS, BATCH_SIZE, rate, get_string_for_array(pre_ops), network.__name__) STR = (os.path.join('test_results', STR)) printTestParam(EPOCHS, BATCH_SIZE, rate, pre_ops, save_dir=STR) D.reset_data() D.preprocess_all(pre_ops) T = MT(D, EPOCHS=EPOCHS, BATCH_SIZE=BATCH_SIZE, rate=rate, network=network, network_args=network_args) T.train(dirname=STR, pre_ops=pre_ops) return D, T
def setUpClass(cls): cls.image_classifier = ImageClassifier('krzysztof-krawczyk.jpg')
socket.bind("tcp://*:5555") RESP = [""] # SERIAL DATA # Port = "COM3" Port = '/dev/cu.usbmodem14101' Baud = 115200 BufferLength = 160 Divider = "999" SERIAL = Serial.CONNECTION(Port, Baud, BufferLength, Divider, start_time) # PLOT fig, ax = plt.subplots() IC = ImageClassifier.IMAGECLASSIFIER() # Dirty af ID = 0 NoFingerID = 0 OneFingerID = 0 TwoFingerID = 0 def addNoFinger(e): global NoFingerID NoFingerID += 1 saveImage('noFinger', NoFingerID) def addOneFinger(e):
required=True, ) args = parser.parse_args() arguments = args.__dict__ if not os.path.isfile(arguments['classes']): print("Can't load file with classes - '" + arguments['classes'] + "'") exit() if not os.path.isfile(arguments['info']): print("Can't load file with info - '" + arguments['info'] + "'") exit() return arguments arguments = parse_arguments() classifier = ImageClassifier(arguments['model_file'], arguments['classes'], arguments['info']) start = time.time() recognizer = ImageRecognizer(classifier, save_fields={ 'class_field': 'class', 'accuracy_field': 'accuracy' }, verbose=True) recognizer.recognize_images_batch(limit=20000, batch_size=10) # recognize_images(recognizer, 1000) # recognize_images_batch(classifier, limit=10000, batch_size=10, # result_fields={'class_field': 'class1', 'accuracy_field': 'accuracy1'}) # recognize_images_batch(recognizer, limit=10000, batch_size=10, place_id=294100933965764) # recognize_images_batch(recognizer, limit=10000, batch_size=10, place_id=422387764530637) # recognize_images_batch(recognizer, limit=10000, batch_size=10, place_id=163218223742220)
dest='top_k', type=int, default=2, help='K most likely classes') parser.add_argument('--gpu', action='store_true', dest='gpu', default=False, help='Predict using CUDA:0 if available') results = parser.parse_args() return results if __name__ == "__main__": # Get cmd args args = parse_input() # Instanciate Image Classifier Class ic = ImageClassifier() # Request GPU if available ic.use_gpu(args.gpu) # Load class to names if args.category_names is not None and not ic.load_class_names(args.category_names): exit() # Load checkpoint to predict if not ic.load_checkpoint(args.ckp_file): exit() # Predict the class for the provided image path ic.print_predictions(ic.predict(args.img_file, args.top_k, show_image=True))
def imageClassification(self, account_data, output): imageClassifier = ImageClassifier() image_classifier_output = imageClassifier.classify(account_data) output.append(image_classifier_output)
import numpy, os, cPickle from ImageClassifier import ImageClassifier def load_mnist(): path = '..' data = cPickle.load(open(os.path.join(path,'mnist.pkl'), 'r')) return data (train_X, train_Y), (valid_X, valid_Y), (test_X, test_Y) = load_mnist() print test_X.shape clf = ImageClassifier(n_in=28,n_out=10) clf.fit(train_X, train_Y) results = clf.predict(test_X) print numpy.mean(results==test_Y)
def test_deterministic_fit(self): """ Test that multiple fits yield same scores. """ clf = ImageClassifier(n_in=8, n_out=2, filters=[2,2]) clf.fit(X,y) assert_array_equal(self.clf.score(X,y), clf.score(X,y))
from ImageClassifier import ImageClassifier #creating new model IC = ImageClassifier('cat-dog-training_data', classifier_name='cat_dogs', batch_size=100) # training model IC.train(2000) #testing this model IC.test('cat-dog-testing_data') # classify an image prediction = IC.predict('predict-dog.jpg') print(prediction)
action='store_true', dest='gpu', default=False, help='Train using CUDA:0') results = parser.parse_args() return results if __name__ == "__main__": print("Hola!") # Get cmd args args = parse_input() # Instanciate Image Classifier Class ic = ImageClassifier() # Request GPU if available ic.use_gpu(args.gpu) # Load Dataset if not ic.load_data(args.data_dir): exit() if args.ckp_file is None: # Create Model print('#' * 30) print(ic.create_model(args.arch, args.hidden_units)) # Create Optimizer print('#' * 30)
from ImageClassifier import ImageClassifier import json import sys RESULT_FILE_NAME = 'result.json' if len(sys.argv) != 2: exit() imageUrl = str(sys.argv[1]) classifier = ImageClassifier(**ImageClassifier.default_args) classifier.net.forward() result = classifier.classify_url(imageUrl) #write to json jsonResult = json.dumps(result[2]) resultFile = open(RESULT_FILE_NAME, 'w+') resultFile.write(jsonResult) resultFile.close()
imgEng=imgEng, savePreProcessedFeatures=True, override=True) else: train_data.initStorage() valid_data.initStorage() x_data_train, y_data_train = train_data.readAllData() x_data_valid, y_data_valid = valid_data.readAllData() if full_train: x_data_train = np.vstack((x_data_train, x_data_valid)) y_data_train = np.append(y_data_train, y_data_valid) # Train LinearSVC classifier clfLinearSVC = ImageClassifier('clf_linear') t = time.time() clfLinearSVC.fit((x_data_train, y_data_train), classifierType='LinearSVC', C=0.01) print(round(time.time() - t, 2), 'seconds to train classifier...') t = time.time() score = clfLinearSVC.score((x_data_valid, y_data_valid)) print(round(time.time() - t, 2), 'seconds to evaluate accuracy...') print('Test accuracy of classifier = ', round(score, 4)) # Train SVC with RBF kernel classifier clfSVC = ImageClassifier('clf_rbf')
from ImageClassifier import ImageClassifier from data_utils import prepare_data if __name__ == '__main__': name = 'colour_white_classifier' classes = ['colour', 'white'] source_path = r'data2/dataset of groups/group 1/img' train_data_path = 'data/colour_white_classifier/train' val_data_path = 'data/colour_white_classifier/val' prepare_data(classes, source_path, train_data_path, val_data_path) classifier = ImageClassifier( name=name, classes=classes, model_path='{}_weights.h5'.format(name), train_data_path=train_data_path, val_data_path=val_data_path, ) # classifier.train(epochs=5) print(classifier.predict('upload/2021032021555414.jpg'))
parser.add_argument('--gpu', action='store_true', dest='gpu', default=False, help='Test using CUDA:0') results = parser.parse_args() return results if __name__ == "__main__": # Get cmd args args = parse_input() # Instanciate Image Classifier Class ic = ImageClassifier() # Request GPU if available ic.use_gpu(args.gpu) # Load Dataset if not ic.load_data(args.data_dir): exit() # Load checkpoint to resume training if not ic.load_checkpoint(args.ckp_file): exit() # Test the dataset ic.test()