public void UseModel(DirectoryInfo modelLocation) { _predictionEndpoint = null; _classifier?.Dispose(); _classifier = ImageClassifier.CreateFromSignatureFile( new FileInfo(Path.Combine(modelLocation.FullName, "signature.json"))); }
public void UseUri(Uri predictionEndpoint) { _classifier?.Dispose(); _classifier = null; _predictionEndpoint = predictionEndpoint; _client = new LobeClient(_predictionEndpoint); }
private static LobeResult CallModel(string imageToClassify, ExecutionContext context) { try { imageToClassify = System.IO.Path.Combine(context.FunctionDirectory, "..\\testImages\\1565.jpg"); var signatureFilePath = System.IO.Path.Combine(context.FunctionDirectory, "..\\signature.json");; var modelFile = System.IO.Path.Combine(context.FunctionDirectory, "..\\model.onnx"); var modelFormat = GetConfig("modelFormat"); ImageClassifier.Register("onnx", () => new OnnxImageClassifier()); using var classifier = ImageClassifier. CreateFromSignatureFile( new FileInfo(signatureFilePath), modelFile, modelFormat); var results = classifier.Classify(Image .Load(imageToClassify).CloneAs <Rgb24>()); return(new LobeResult { Confidence = results.Classification.Confidence, Label = results.Classification.Label }); } catch (Exception e) { return(new LobeResult { Label = "unknown", Confidence = 0 }); } }
public static ImageClassifier GetClassifier(ClassifierType type) { string protoTxtPath = string.Empty; string mdlBinPath = string.Empty; switch (type) { case ClassifierType.Resnet: { protoTxtPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "resnet_nsfw.prototxt"); mdlBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "resnet_50_1by2_nsfw.caffemodel"); } break; case ClassifierType.Squeezenet: { protoTxtPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "squeezenet_nsfw.prototxt"); mdlBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "squeezenet_nsfw.caffemodel"); } break; } var classifier = new ImageClassifier(protoTxtPath, mdlBinPath, type); if (classifier.IsEmpty) { throw new Exception("Classifier shouldn't be empty. Are you model paths correct?"); } return(classifier); }
private static async Task ConfigureLobe(CSharpKernel csharpKernel) { ImageClassifier.Register("onnx", () => new OnnxImageClassifier()); await LoadAssemblyAndAddNamespace <ImageClassifier>(csharpKernel); await LoadAssemblyAndAddNamespace <OnnxImageClassifier>(csharpKernel); await AddNamespace(csharpKernel, typeof(ClassificationResults)); }
private async Task Processing() { string path = (string)labelPath.Content; if (path is null) { path = "..\\..\\..\\images"; } int tasksCount = 4; bool done = false; Task extractResults = Task.Run(() => { ImageResult predictionOutput; while (true) { Thread.Sleep(0); if (ImageClassifier.cts.Token.IsCancellationRequested || done) { return; } if (ImageClassifier.predictionOutputs.TryDequeue(out predictionOutput)) { Dispatcher.Invoke(() => { Pair replacing = ClassesCounts.FirstOrDefault(x => x.ClassLabel == predictionOutput.outputLabel); if (replacing != null) { var index = ClassesCounts.IndexOf(replacing); ClassesCounts[index].Count += 1; } else { ClassesCounts.Add(new Pair(predictionOutput.outputLabel, 1)); } ObservableCollection <string> localImages = null; if (!ImagesInClass.TryGetValue(predictionOutput.outputLabel, out localImages)) { localImages = new ObservableCollection <string>(); ImagesInClass[predictionOutput.outputLabel] = localImages; } string localPath = predictionOutput.path.Substring(predictionOutput.path.LastIndexOf('\\') + 1); ImagesInClass[predictionOutput.outputLabel].Add(localPath); }); } } }); await ImageClassifier.parallelProcess(path, tasksCount); if (!ImageClassifier.cts.IsCancellationRequested) { done = true; } await extractResults; }
public void can_classify_image(string imageFilePath, string expectedLabel) { using var classifier = ImageClassifier.CreateFromSignatureFile( new FileInfo(@"../../../../../models/controller/signature.json")); var results = classifier.Classify(Image.Load(imageFilePath).CloneAs <Rgb24>()); results.Prediction.Label.Should() .Be(expectedLabel); }
public void can_from_signature_via_factory() { Action initialization = () => ImageClassifier.CreateFromSignatureFile( new FileInfo(@"../../../../../models/controller/signature.json"), "saved_model.onnx", "onnx"); initialization.Should() .NotThrow(); }
public static async Task Main(string[] args) { string path = "images"; int tasksCount = 4; bool done = false; if (args.Length > 0) { path = args[0]; } if (args.Length > 1) { tasksCount = Int32.Parse(args[1]); } Stopwatch watch = new Stopwatch(); watch.Start(); Task keyboardTask = Task.Run(() => { if (Console.ReadKey().Key == ConsoleKey.Enter) { ImageClassifier.cts.Cancel(); Console.WriteLine("Canceled"); } }); Task extractResults = Task.Run(() => { ImageResult predictionOutput; while (true) { if (ImageClassifier.cts.Token.IsCancellationRequested || done) { return; } if (ImageClassifier.predictionOutputs.TryDequeue(out predictionOutput)) { Console.WriteLine(predictionOutput); } } }); await ImageClassifier.parallelProcess(path, tasksCount); if (!ImageClassifier.cts.IsCancellationRequested) { Console.WriteLine("Done"); done = true; } await extractResults; watch.Stop(); Console.WriteLine($"{watch.ElapsedMilliseconds} elapsed milliseconds"); }
public List <ImageResult> Post(string path) { path = "../MyClient/images"; List <ImageResult> results = new List <ImageResult>(); foreach (var imagePath in Directory.GetFiles(path)) { results.Add(ImageClassifier.processImage(imagePath)); } return(results); }
public void ClassifyImagesTest() { string[] files = System.IO.Directory.GetFiles(@"d:\20090505"); ImageDetail[] images = new ImageDetail[10]; for (int i = 0; i < images.Length; i++) { ImageDetail d = ImageDetail.FromPath(files[i]); images[i] = d; } ImageClassifier.ClassifyImages(images); }
public override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); mStateCallback = new StateListener(this); mSurfaceTextureListener = new SurfaceTextureListener(this); // fill ORIENTATIONS list ORIENTATIONS.Append((int)SurfaceOrientation.Rotation0, 90); ORIENTATIONS.Append((int)SurfaceOrientation.Rotation90, 0); ORIENTATIONS.Append((int)SurfaceOrientation.Rotation180, 270); ORIENTATIONS.Append((int)SurfaceOrientation.Rotation270, 180); tensorflow = new ImageClassifier(); }
public static string Run(string DataDirectoryName) { var statistics = new Dictionary <string, int>(); IImageBinarizer binarizer = new ImageBinarizer(); var directoryInfo = new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.Parent; var path = Path.Combine(directoryInfo.FullName, DataDirectoryName); directoryInfo = new DirectoryInfo(path); imageClassifier = new ImageClassifier(binarizer, Size * Size); //Train foreach (DirectoryInfo directory in directoryInfo.EnumerateDirectories()) { foreach (var file in directory.EnumerateFiles("*.bmp")) { string fileName = Path.GetFileNameWithoutExtension(file.FullName); imageClassifier.Train(new ImageUnit { Id = fileName, Image = new Bitmap(file.FullName) }); } } foreach (DirectoryInfo directory in directoryInfo.EnumerateDirectories()) { foreach (var file in directory.EnumerateFiles("*.bmp")) { string fileName = Path.GetFileNameWithoutExtension(file.FullName); var patternDirectory = directory.EnumerateDirectories().FirstOrDefault(p => p.Name == ("Randomized_" + fileName)); foreach (var patternFile in patternDirectory.EnumerateFiles("*.bmp")) { string patternFileName = Path.GetFileNameWithoutExtension(patternFile.FullName); string[] nameParts = patternFileName.Split(new[] { "_" }, StringSplitOptions.RemoveEmptyEntries); string percentValue = nameParts[1]; if (statistics.ContainsKey(percentValue) == false) { statistics.Add(percentValue, 0); } string classificationResult = imageClassifier.Classify(new Bitmap(patternFile.FullName)); if (classificationResult.Equals(fileName, StringComparison.CurrentCulture)) { statistics[percentValue] += 1; } } } } return(statistics.Aggregate("Classification result: \n\n", (current, statistic) => current + String.Format("Noise percent: {0}\n Matched: {1}\n\n", statistic.Key, statistic.Value))); }
public static ImageClassifier GetClassifier() { string protoTxtPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "deploy.prototxt"); string mdlBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "resnet_50_1by2_nsfw.caffemodel"); var classifier = new ImageClassifier(protoTxtPath, mdlBinPath); if (classifier.IsEmpty) { throw new Exception("Classifier shouldn't be empty. Are you model paths correct?"); } return(classifier); }
public ImageRecognitionService(StatusService statusService, ObjectDetector objectDetector, MetaDataService metadataService, AzureFaceService azureFace, AccordFaceService accordFace, EmguFaceService emguService, ThumbnailService thumbs, ConfigService configService, ImageClassifier imageClassifier, ImageCache imageCache, WorkService workService, ExifService exifService, ImageProcessService imageProcessor) { _thumbService = thumbs; _accordFaceService = accordFace; _azureFaceService = azureFace; _statusService = statusService; _objectDetector = objectDetector; _metdataService = metadataService; _emguFaceService = emguService; _configService = configService; _imageClassifier = imageClassifier; _imageProcessor = imageProcessor; _imageCache = imageCache; _workService = workService; _exifService = exifService; }
public ImageClassifierTests() { ImageClassifier.Register("onnx", () => new OnnxImageClassifier()); }
private static void RunClassifier(ImageClassifier classifier, string ClassifierPath, bool classifyPorn = true, bool verbose = false, bool copyWrongs = false, string wrongsPath = "", double cutoff = 0) { //cutoff = 2 --> usar default if (cutoff != 2) { classifier.Cutoff = cutoff; } Console.WriteLine("Classifier has cutoff of {0}.", classifier.Cutoff); //REVISAR falla al encontrar directorios con acceso denegado (ej. SVI ó RECYCLE.BIN) // Y es lento para grandes tamaños, ver exploración recursiva y EnumerateFiles en su lugar //var allImgs = Directory.GetFiles(ClassifierPath, "*.jpg", SearchOption.AllDirectories).ToList(); //var allImgs = Directory.GetFiles(ClassifierPath, "*.png", SearchOption.AllDirectories).ToList(); //var allImgs = Directory.GetFiles(ClassifierPath, "*.jpg").ToList(); var allImgs = Directory.GetFiles(ClassifierPath).ToList(); var total = allImgs.Count; bool tPorn = classifyPorn; Console.WriteLine("{0} imágenes a clasificar.", total); int imgRight = 0, imgWrong = 0; var sw = new Stopwatch(); sw.Start(); foreach (var img in allImgs) { var imgData = File.ReadAllBytes(img); var outPath = Path.Combine(wrongsPath, Path.GetFileName(img)); //var outPath = Path.Combine(@"D:\img_wrong", Path.GetFileName(img).Replace(".png", "_" + ctStr + score.ToString("F6") + ".png")); //Path.Combine(img, "wrong", Path.GetFileName(img)); try { if (classifier.ClassifyImage(imgData)) { if (tPorn) { ++imgRight; } else { ++imgWrong; if (copyWrongs) { File.Copy(img, outPath); } } } else { // If you feel like inspecting false negatives. //var outPath = Path.Combine(SOME PLACE FOR FALSE NEGATIVES, Path.GetFileName(img)); //File.Move(img, outPath); //var outPath = Path.Combine(img, "wrong", Path.GetFileName(img)); //File.Copy(img, outPath); if (tPorn) { ++imgWrong; //if (verbose) Console.WriteLine("score: {0}", classifier.GetPositiveProbability(imgData)); if (copyWrongs) { File.Copy(img, outPath); } } else { ++imgRight; } } if (verbose && (imgRight + imgWrong) % 100 == 0) { if (tPorn) { Console.WriteLine("Classified {0} of {1} pornographic images.", imgRight + imgWrong, total); } else { Console.WriteLine("Classified {0} of {1} non-pornographic images.", imgRight + imgWrong, total); } } //Console.WriteLine("score: {0}", score); } catch (Exception e) { // Extract some information from this exception, and then // throw it to the parent method. if (e.Source != null) { Console.WriteLine("Exception source: {0}", e.Source); } throw; } } sw.Stop(); if (tPorn) { Console.WriteLine("Classified {0} pornographic images with an accuracy of {1}%.", imgRight + imgWrong, 100d * ((double)imgRight / (double)(imgRight + imgWrong))); } else { Console.WriteLine("Classified {0} non-pornographic images with an accuracy of {1}%.", imgRight + imgWrong, 100d * ((double)imgRight / (double)(imgRight + imgWrong))); } Console.WriteLine("Classifier took an average of {0} msec per image to classify.", sw.ElapsedMilliseconds / (double)(total * 2)); }
public static ClassificationResults Classify <TPixel>(this ImageClassifier classifier, Image <TPixel> image) where TPixel : unmanaged, IPixel <TPixel> { return(classifier.Classify(image.ToFlatArrayMatchingInputShape(classifier.Signature, "Image"))); }
private static void TestClassifier(ImageClassifier classifier, ClassifierType type, bool verbose = false) { Console.WriteLine("{0} classifier has cutoff of {1}.", type, classifier.Cutoff); string badImagesTesting = @"SOME BAD STUFF BRO"; string goodImagesTesting = @"SOME GOOD STUFF KIDDO"; var badImgs = Directory.GetFiles(badImagesTesting, "*.jpg", SearchOption.AllDirectories).ToList(); var goodImgs = Directory.GetFiles(goodImagesTesting, "*.jpg", SearchOption.AllDirectories).ToList(); // Cut down our test base so it's not so huge. var min = Math.Min(badImgs.Count, goodImgs.Count); if (min > 1000) { min = 1000; } Console.WriteLine("Testing against a total of {0} images, {1} from each class.", min * 2, min); badImgs = badImgs.GetRange(0, min); goodImgs = goodImgs.GetRange(0, min); // Shuffle things up a bit. Random r = new Random(); badImgs = badImgs.OrderBy(x => r.Next()).ToList(); goodImgs = goodImgs.OrderBy(x => r.Next()).ToList(); int goodRight = 0, goodWrong = 0, badRight = 0, badWrong = 0; var sw = new Stopwatch(); sw.Start(); foreach (var img in badImgs) { var imgData = File.ReadAllBytes(img); if (classifier.ClassifyImage(imgData)) { ++badRight; } else { // If you feel like inspecting false negatives. //var outPath = Path.Combine(SOME PLACE FOR FALSE NEGATIVES, Path.GetFileName(img)); //File.Move(img, outPath); ++badWrong; } if (verbose && (badRight + badWrong) % 10 == 0) { Console.WriteLine("Classified {0} of {1} bad images.", badRight + badWrong, min); } } foreach (var img in goodImgs) { var imgData = File.ReadAllBytes(img); if (classifier.ClassifyImage(imgData)) { ++goodWrong; } else { ++goodRight; } if (verbose && (goodWrong + goodRight) % 10 == 0) { Console.WriteLine("Classified {0} of {1} good images.", goodWrong + goodRight, min); } } sw.Stop(); Console.WriteLine("Classifier with type {0} classified pornographic images with an accuracy of {1}%.", type, 100d * ((double)badRight / (double)(badRight + badWrong))); Console.WriteLine("Classifier with type {0} classified non-pornographic images with an accuracy of {1}%.", type, 100d * ((double)goodRight / (double)(goodRight + goodWrong))); Console.WriteLine("Classifier with type {0} took an average of {1} msec per image to classify.", type, sw.ElapsedMilliseconds / (double)(min * 2)); }
private static Parser CreateParser() { var rootCommand = new RootCommand { Description = @"Classify images using onnx model or directly the http endpoint from the lobe app." }; var signatureFileOption = new Option <FileInfo>("--signature-file", "signature file for model loading."); var imageFileOption = new Option <FileInfo>("--image-file", "image file to classify."); var imageFolderOption = new Option <FileInfo>("--image-folder", "folder that contain images to classify."); var predictionEndpointOption = new Option <Uri>("--prediction-endpoint", "prediction endpoint from lobe app."); rootCommand.AddOption(signatureFileOption); rootCommand.AddOption(imageFileOption); rootCommand.AddOption(imageFolderOption); rootCommand.AddOption(predictionEndpointOption); rootCommand.Handler = CommandHandler.Create <FileInfo, FileInfo, DirectoryInfo, Uri>( (signatureFile, imageFile, imageFolder, predictionEndpoint) => { var images = GatherImages(imageFile, imageFolder); if (signatureFile is null && predictionEndpoint is null) { throw new InvalidOperationException("Must use a signature file or prediction endpoint."); } if (imageFile is null && imageFolder is null) { throw new InvalidOperationException("Must use a image file or image folder."); } if (signatureFile != null) { if (!signatureFile.Exists) { throw new InvalidOperationException( $"Signature file {signatureFile.FullName} does not exist."); } ImageClassifier.Register("onnx", () => new OnnxImageClassifier()); using var classifier = ImageClassifier.CreateFromSignatureFile( new FileInfo(signatureFile.FullName)); foreach (var file in images) { var results = Classify(file, classifier.Classify); Console.WriteLine(results.Prediction.Label); } return(0); } if (predictionEndpoint != null) { var classifier = new LobeClient(predictionEndpoint); foreach (var file in images) { var results = Classify(file, classifier.Classify); Console.WriteLine(results.Prediction.Label); } return(0); } return(1); }); return(new CommandLineBuilder(rootCommand) .UseDefaults() .Build());
static void Main(string[] args) { //LogEvents.Subscribe(i => //{ // i.Operation.Id = ""; // Console.WriteLine(i.ToLogString()); //}, new[] //{ // typeof(PiTop4Board).Assembly, // typeof(FoundationPlate).Assembly, // typeof(ExpansionPlate).Assembly, // typeof(RoverRobot).Assembly, // typeof(StreamingCamera).Assembly, // typeof(Program).Assembly, //}); ImageClassifier.Register("onnx", () => new OnnxImageClassifier()); ImageClassifier classifier = null; var js = new XBoxController(); // using ` mjpg_streamer -i "input_uvc.so -d /dev/video0" -o output_http.so` // ==> http://pi-top.local:8080/?action=stream PiTop4Board.Instance.UseCamera(); using var rover = new RoverRobot(PiTop4Board.Instance.GetOrCreateExpansionPlate(), PiTop4Board.Instance.GetOrCreateCamera <StreamingCamera>(0), RoverRobotConfiguration.Default); var camControl = rover.TiltController; var motorControl = rover.MotionComponent as SteeringMotorController; rover.AllLightsOn(); rover.BlinkAllLights(); Observable.Interval(TimeSpan.FromMilliseconds(10)) .Select(_ => (X: js.LeftStick.X, Y: js.LeftStick.Y)) .DistinctUntilChanged() .Subscribe(stick => { var left = stick.X.WithDeadZone(-.5, .5, .3); var forward = stick.Y; motorControl.SetPower((forward + left) / 1.5, (forward - left) / 1.5); }); js.Events.OfType <ButtonEvent>().Where(e => e.Button == Button.A) .Subscribe(e => { if (e.Pressed) { rover.AllLightsOn(); } else { rover.AllLightsOff(); } }); js.Events.OfType <ButtonEvent>().Where(e => e.Button == Button.B && e.Pressed) .Subscribe(e => { rover.Camera.GetFrame().Save("/home/pi/shot.jpg"); }); js.Events.OfType <ButtonEvent>().Where(e => e.Button == Button.Y && e.Pressed) .Subscribe(e => { classifier?.Dispose(); var signatureFile = new FileInfo("/home/pi/models/pics/signature.json"); classifier = ImageClassifier.CreateFromSignatureFile(signatureFile); Console.WriteLine($"Loaded model from {signatureFile.FullName}"); }); js.Events.OfType <ButtonEvent>().Where(e => e.Button == Button.X && e.Pressed) .Subscribe(e => { var frame = rover.Camera.GetFrame().Focus(); var result = classifier?.Classify(frame.CloneAs <Rgb24>()); if (result is { }) { Console.WriteLine($"{result.Prediction.Label}"); } });
public static ClassificationResults Classify(this ImageClassifier classifier, Mat image) { return(classifier.Classify(image.ToFlatArrayMatchingInputShape(classifier.Signature, "Image"))); }
static void Main(string[] args) { FolderBrowserDialog fbd = new FolderBrowserDialog(); string allImagesTesting = ""; if (fbd.ShowDialog() == DialogResult.OK) { allImagesTesting = fbd.SelectedPath; } string protoTxtPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "deploy.prototxt"); string mdlBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "resnet_50_1by2_nsfw.caffemodel"); var classifier = new ImageClassifier(protoTxtPath, mdlBinPath); Console.WriteLine("Loaded classifier."); Console.WriteLine("Classifier has cutoff of {0}.", classifier.Cutoff); /* * string badImagesTesting = @"E:\img_malas"; * string goodImagesTesting = @"E:\img_buenas"; * string allImagesTesting = @"G:\Temp\$Temp\pics"; */ //string allImagesTesting = @"G:\Temp\$Temp\pics"; //classifier.Cutoff = 0.15; //var badImgs = Directory.GetFiles(badImagesTesting).ToList(); //var goodImgs = Directory.GetFiles(goodImagesTesting).ToList(); //Esto lista todas las .jpg en la carpeta seleccionada y todas sus subcarpetas var allImgs = Directory.GetFiles(allImagesTesting, "*.jpg", SearchOption.AllDirectories).ToList(); var total = allImgs.Count; //Creo subcarpeta para mover los falsos negativos Directory.CreateDirectory(Path.Combine(allImagesTesting, "wrong")); // Cut down our test base so it's not so huge. /* * var min = Math.Min(badImgs.Count, goodImgs.Count); * * if(min > 1000) * { * min = 1000; * } * * badImgs = badImgs.GetRange(0, min); * goodImgs = goodImgs.GetRange(0, min); * * * // Shuffle things up a bit. * Random r = new Random(); * badImgs = badImgs.OrderBy(x => r.Next()).ToList(); * goodImgs = goodImgs.OrderBy(x => r.Next()).ToList(); */ int goodRight = 0, goodWrong = 0, badRight = 0, badWrong = 0; var sw = new Stopwatch(); sw.Start(); foreach (var img in allImgs) { var imgData = File.ReadAllBytes(img); if (classifier.ClassifyImage(imgData)) { ++badRight; } else { // If you feel like inspecting false negatives. var outPath = Path.Combine(allImagesTesting, "wrong", Path.GetFileName(img)); //File.Move(img, outPath); File.Copy(img, outPath); ++badWrong; } //Publica avance cada 10 imágenes procesadas if ((badRight + badWrong) % 10 == 0) { Console.WriteLine("Classified {0} of {1} bad images.", badRight + badWrong, total); } } /* * * foreach(var img in badImgs) * { * var imgData = File.ReadAllBytes(img); * * if(classifier.ClassifyImage(imgData)) * { ++badRight; * } * else * { * // If you feel like inspecting false negatives. * // var outPath = Path.Combine(SOME_BASE_PATH_FOR_FALSE_NEGATIVES, Path.GetFileName(img)); * // File.Move(img, outPath); * var outPath = Path.Combine(badImagesTesting,"wrong", Path.GetFileName(img)); * File.Move(img, outPath); ++badWrong; * } * * if((badRight + badWrong) % 10 == 0) * { * Console.WriteLine("Classified {0} of {1} bad images.", badRight + badWrong, min); * } * } * * foreach(var img in goodImgs) * { * var imgData = File.ReadAllBytes(img); * * if(classifier.ClassifyImage(imgData)) * { ++goodWrong; * } * else * { ++goodRight; * } * * if((goodWrong + goodRight) % 10 == 0) * { * Console.WriteLine("Classified {0} of {1} good images.", goodWrong + goodRight, min); * } * } * */ sw.Stop(); Console.WriteLine("Classified pornographic images with an accuracy of {0}%.", 100d * ((double)badRight / (double)(badRight + badWrong))); Console.WriteLine("Classified non-pornographic images with an accuracy of {0}%.", 100d * ((double)goodRight / (double)(goodRight + goodWrong))); //Console.WriteLine("Took an average of {0} msec per image to classify.", sw.ElapsedMilliseconds / (double)(min * 2)); Console.WriteLine("Took an average of {0} msec per image to classify.", sw.ElapsedMilliseconds / (double)(total)); Console.ReadLine(); //Pausa para que no cierre consola }
static void Main(string[] args) { string protoTxtPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "deploy.prototxt"); string mdlBinPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "resnet_50_1by2_nsfw.caffemodel"); var classifier = new ImageClassifier(protoTxtPath, mdlBinPath); Console.WriteLine("Loaded classifier."); Console.WriteLine("Classifier has cutoff of {0}.", classifier.Cutoff); //string badImagesTesting = PATH_TO_BAD_IMAGES; //string goodImagesTesting = PATH_TO_GOOD_IMAGES; string badImagesTesting = @"E:\img_malas"; string goodImagesTesting = @"E:\img_malas"; var badImgs = Directory.GetFiles(badImagesTesting).ToList(); var goodImgs = Directory.GetFiles(goodImagesTesting).ToList(); // Cut down our test base so it's not so huge. var min = Math.Min(badImgs.Count, goodImgs.Count); if (min > 1000) { min = 1000; } badImgs = badImgs.GetRange(0, min); goodImgs = goodImgs.GetRange(0, min); // Shuffle things up a bit. Random r = new Random(); badImgs = badImgs.OrderBy(x => r.Next()).ToList(); goodImgs = goodImgs.OrderBy(x => r.Next()).ToList(); int goodRight = 0, goodWrong = 0, badRight = 0, badWrong = 0; var sw = new Stopwatch(); sw.Start(); foreach (var img in badImgs) { var imgData = File.ReadAllBytes(img); if (classifier.ClassifyImage(imgData)) { ++badRight; } else { // If you feel like inspecting false negatives. // var outPath = Path.Combine(SOME_BASE_PATH_FOR_FALSE_NEGATIVES, Path.GetFileName(img)); // File.Move(img, outPath); ++badWrong; } if ((badRight + badWrong) % 10 == 0) { Console.WriteLine("Classified {0} of {1} bad images.", badRight + badWrong, min); } } foreach (var img in goodImgs) { var imgData = File.ReadAllBytes(img); if (classifier.ClassifyImage(imgData)) { ++goodWrong; } else { ++goodRight; } if ((goodWrong + goodRight) % 10 == 0) { Console.WriteLine("Classified {0} of {1} good images.", goodWrong + goodRight, min); } } sw.Stop(); Console.WriteLine("Classified pornographic images with an accuracy of {0}%.", 100d * ((double)badRight / (double)(badRight + badWrong))); Console.WriteLine("Classified non-pornographic images with an accuracy of {0}%.", 100d * ((double)goodRight / (double)(goodRight + goodWrong))); Console.WriteLine("Took an average of {0} msec per image to classify.", sw.ElapsedMilliseconds / (double)(min * 2)); //Console.WriteLine("min = {0}", min); Console.ReadLine(); }