public List <ClassifiedMatch> GetClassifiedMatchesFromImage(ClassifiedImage image, List <User> users)
        {
            var imageMatches = new List <ClassifiedMatch>();

            foreach (var location in image.Locations)
            {
                var croppedMat = new Mat(image.Mat, location).Resize(new Size(100, 100), interpolation: InterpolationFlags.Cubic).CvtColor(ColorConversionCodes.BGR2GRAY);

                Recognizer.Predict(croppedMat, out var userIndex, out var resultConfidence);

                if (resultConfidence > ClassifierConfiguration.ConfidenceThreshold)
                {
                    continue;
                }

                imageMatches.Add(new ClassifiedMatch
                {
                    User     = users[userIndex],
                    Distance = resultConfidence,
                    Location = GetLocationFromOpenCVRect(location)
                });
            }

            SetIsCenteredOnClassifiedMatches(image, imageMatches);

            return(imageMatches);
        }
示例#2
0
        public async Task PutImage(string path)
        {
            string imageBase64 = ImageToBase64(new Bitmap(path));

            SelectedImage = new ClassifiedImage()
            {
                Id          = -1, Name = Path.GetFileName(path),
                Class       = -1, Confidence = -1, RetrieveCount = -1,
                ImageBase64 = imageBase64
            };
            await Task.Run(() =>
            {
                HttpClient httpClient = new HttpClient();
                NewImage newImage     = new NewImage()
                {
                    Name        = Path.GetFileName(path),
                    ImageBase64 = imageBase64
                };
                string json = JsonConvert.SerializeObject(newImage);
                var content = new StringContent(json);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                var putResult = httpClient.PutAsync(Urls.ClassifiedImages, content).Result;
                json          = putResult.Content.ReadAsStringAsync().Result;
                Dispatcher.UIThread.InvokeAsync(() =>
                {
                    SelectedImage = JsonConvert.DeserializeObject <ClassifiedImage>(json);
                });
            });
        }
        public async Task <IActionResult> PutClassifiedImage([FromRoute] int id, [FromBody] ClassifiedImage classifiedImage)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != classifiedImage.Id)
            {
                return(BadRequest());
            }

            _context.Entry(classifiedImage).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ClassifiedImageExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
示例#4
0
        private void SetIsCenteredOnClassifiedMatches(ClassifiedImage image, List<ClassifiedMatch> classifiedMatches)
        {
            var centerPoint = new Point(image.Bitmap.Size.Width / 2, image.Bitmap.Height / 2);

            foreach (var classifiedMatch in classifiedMatches)
            {
                if (!classifiedMatches.Any(c => c.IsCenter))
                {
                    classifiedMatch.IsCenter = true;
                    continue;
                }

                var currentIsCenterClassifiedMatch = classifiedMatches.Single(c => c.IsCenter);
                var currentIsCenterCenterDifference = currentIsCenterClassifiedMatch.Location.CenterDifference(centerPoint);

                var classifiedMatchCenterDifference = classifiedMatch.Location.CenterDifference(centerPoint);

                if (currentIsCenterCenterDifference >= classifiedMatchCenterDifference)
                {
                    continue;
                }

                currentIsCenterClassifiedMatch.IsCenter = false;
                classifiedMatch.IsCenter = true;
            }
        }
示例#5
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Date,Latitude,Longitude,GeoPolygon,Photo,PhotoName,FileType,Geolocalization,GeoJSON,FireTypeClassification,SmokeTypeClassification,FireScoreClassification,SmokeScoreClassification")] ClassifiedImage classifiedImage)
        {
            if (id != classifiedImage.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(classifiedImage);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ClassifiedImageExists(classifiedImage.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(classifiedImage));
        }
示例#6
0
        public ClassifiedImage GetClassifiedImage(Bitmap bitmap)
        {
            var image = new ClassifiedImage(Classifier, ClassifierConfiguration);
            image.Load(bitmap);

            return image;
        }
示例#7
0
        public List<ClassifiedMatch> GetClassifiedMatchesFromImage(ClassifiedImage image, List<User> users)
        {
            var classifiedMatches = new List<ClassifiedMatch>();

            foreach (var location in image.Locations)
            {
                var croppedImage = image.Image.Copy(location).Convert<Gray, byte>().Resize(100, 100, Inter.Cubic);

                var result = Recognizer.Predict(croppedImage);

                Console.WriteLine($"{result.Distance} - {users[result.Label].Name}");

                if (result.Distance > ClassifierConfiguration.DistanceThreshold)
                {
                    continue;
                }

                classifiedMatches.Add(new ClassifiedMatch
                {
                    User = users[result.Label],
                    Distance = result.Distance,
                    Location = location
                });
            }

            SetIsCenteredOnClassifiedMatches(image, classifiedMatches);

            return classifiedMatches;
        }
示例#8
0
        public ClassifiedImage GetClassifiedImage(Bitmap bitmap)
        {
            var capturedImage = new ClassifiedImage(FaceRecognition);

            capturedImage.Load(bitmap);

            return(capturedImage);
        }
示例#9
0
        public async Task <IActionResult> Create([Bind("Id,Date,Latitude,Longitude,GeoPolygon,Photo,PhotoName,FileType,Geolocalization,GeoJSON,FireTypeClassification,SmokeTypeClassification,FireScoreClassification,SmokeScoreClassification")] ClassifiedImage classifiedImage)
        {
            if (ModelState.IsValid)
            {
                _context.Add(classifiedImage);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(classifiedImage));
        }
        public async Task <IActionResult> PostClassifiedImage([FromBody] ClassifiedImage classifiedImage)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.ClassifiedImages.Add(classifiedImage);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetClassifiedImage", new { id = classifiedImage.Id }, classifiedImage));
        }
示例#11
0
        public ClassifiedImage PutImage(NewImage newImage)
        {
            ClassifiedImage classifiedImage = db.FindImage(newImage);

            if (classifiedImage != null)
            {
                return(classifiedImage);
            }
            classifiedImage = classifier.Classify(newImage);
            db.PutImage(classifiedImage);
            return(classifiedImage);
        }
示例#12
0
        public async Task <IActionResult> Create(ClassifiedListing listing)
        {
            if (ModelState.IsValid)
            {
                var identityUser = await _userManager.GetUserAsync(HttpContext.User);

                var loggedInUser = await _context.Owner.FindAsync(identityUser.OwnerId);

                listing.LastModifiedBy   = loggedInUser.FullName;
                listing.LastModifiedDate = DateTime.Now;
                listing.ListingDate      = DateTime.Now;
                listing.Owner            = loggedInUser;
                listing.OwnerId          = loggedInUser.OwnerId;

                _context.ClassifiedListing.Add(listing);
                await _context.SaveChangesAsync();

                //image uploading
                string webRootPath = _hostingEnvironment.WebRootPath;
                var    files       = HttpContext.Request.Form.Files;

                var uploads = Path.Combine(webRootPath, @"img\ClassifiedsImages");

                int i = 0;
                foreach (var file in files)
                {
                    i++;
                    var extension = Path.GetExtension(file.FileName);
                    using (var filestream = new FileStream(Path.Combine(uploads, listing.ClassifiedListingId + @"_" + i + extension), FileMode.Create))
                    {
                        file.CopyTo(filestream); // moves to server and renames
                    }
                    var image = new ClassifiedImage()
                    {
                        ClassifiedListingId = listing.ClassifiedListingId,
                        IsMainImage         = (file == files.First()),
                        ImageExtension      = extension,
                        ImageURL            = @"\" + @"img\ClassifiedsImages" + @"\" + listing.ClassifiedListingId + @"_" + i + extension
                    };

                    _context.ClassifiedImage.Add(image);
                }

                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            ViewData["Category"] = new SelectList(_context.ClassifiedCategory.Where(u => u.Description != "Other"), "ClassifiedCategoryId", "Description", listing.ClassifiedCategoryId);
            return(View(listing));
        }
示例#13
0
        public ClassifiedImageModel AddClassifiedImage(InputClassifiedImageModel inputModel)
        {
            using (var scope = new TransactionScope())
            {
                var classifiedImage = new ClassifiedImage()
                {
                    ClassifiedId   = inputModel.ClassifiedId,
                    ImageExtension = inputModel.ImageExtension,
                    ImageGuid      = inputModel.ImageGuid,
                    IsMainImage    = inputModel.IsMainImage
                };

                _unitOfWork.ClassifiedImageRepository.Add(classifiedImage);
                _unitOfWork.Save();
                scope.Complete();
                return(Mapper.Map <ClassifiedImage, ClassifiedImageModel>(classifiedImage));
            }
        }
示例#14
0
        public List <ClassifiedMatch> GetClassifiedMatchesFromImage(ClassifiedImage image, List <User> users)
        {
            var classifiedMatches = new List <ClassifiedMatch>();

            foreach (var user in users)
            {
                foreach (var userImage in user.UserImages)
                {
                    // you can leverage a saved encoding instead of loading the image then comparing.

                    var userClassifiedImage = new ClassifiedImage(FaceRecognition);
                    userClassifiedImage.Load(userImage.ImageFilePath);

                    for (var encodingIndex = 0; encodingIndex < image.Encodings.Count; encodingIndex++)
                    {
                        foreach (var userEncoding in userClassifiedImage.Encodings)
                        {
                            var faceDistance = FaceRecognition.FaceDistance(image.Encodings[encodingIndex], userEncoding);

                            if (!(faceDistance < FaceDistanceThreshold))
                            {
                                continue;
                            }

                            classifiedMatches.Add(new ClassifiedMatch
                            {
                                User         = user,
                                FaceEncoding = image.Encodings[encodingIndex],
                                Distance     = faceDistance,
                                Location     = GetLocationFromFaceRecognitionLocation(image.Locations[encodingIndex])
                            });
                        }
                    }
                }
            }

            SetIsCenteredOnClassifiedMatches(image, classifiedMatches);

            return(classifiedMatches);
        }
示例#15
0
        public async Task <IActionResult> PutClassifiedImage(int Id, DateTime Date, string Latitude, string Longitude, string GeoPolygon, string Photo, string PhotoName, string FileType, string Geolocalization, string GeoJSON, string FireTypeClassification, string SmokeTypeClassification, double FireScoreClassification, double SmokeScoreClassification)
        {
            ClassifiedImage classifiedImageobj = new ClassifiedImage(Id, Date, Latitude, Longitude, GeoPolygon, Photo, PhotoName, FileType, Geolocalization, GeoJSON, FireTypeClassification, SmokeTypeClassification, FireScoreClassification, SmokeScoreClassification);

            _context.Entry(classifiedImageobj).State = Microsoft.EntityFrameworkCore.EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ClassifiedImageExists(classifiedImageobj.Id))
                {
                    Console.WriteLine("L'immagine selezionata non esiste");
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
示例#16
0
        public ClassifiedImage PutImage(ClassifiedImage classifiedImage)
        {
            ClassifiedDbImage dbImage = new ClassifiedDbImage()
            {
                Name          = classifiedImage.Name,
                Class         = classifiedImage.Class,
                Confidence    = classifiedImage.Confidence,
                RetrieveCount = classifiedImage.RetrieveCount,
            };

            using (ImageDbContext dbContext = new ImageDbContext())
            {
                Blob blob = new Blob()
                {
                    Bytes = Convert.FromBase64String(classifiedImage.ImageBase64)
                };
                dbContext.Add(blob);
                dbImage.Image = blob;
                dbContext.Add(dbImage);
                dbContext.SaveChanges();
            }
            classifiedImage.Id = dbImage.Id;
            return(classifiedImage);
        }
示例#17
0
        public async Task <ActionResult> Edit(int?id, ClassifiedListing listing)
        {
            if (id != listing.ClassifiedListingId)
            {
                return(NotFound());
            }

            var identityUser = await _userManager.GetUserAsync(HttpContext.User);

            var loggedInUser = await _context.Owner.FindAsync(identityUser.OwnerId);

            if (ModelState.IsValid)
            {
                listing.LastModifiedBy   = loggedInUser.FullName;
                listing.LastModifiedDate = DateTime.Now;
                listing.OwnerId          = loggedInUser.OwnerId;

                _context.Update(listing);
                await _context.SaveChangesAsync();

                var files = HttpContext.Request.Form.Files;
                if (files.Count != 0)
                {
                    string webRootPath = _hostingEnvironment.WebRootPath;

                    var uploads = Path.Combine(webRootPath, @"img\ClassifiedsImages");

                    var oldImages = await _context.ClassifiedImage.Where(x => x.ClassifiedListingId == listing.ClassifiedListingId).ToListAsync();

                    foreach (var oldImage in oldImages)
                    {
                        if (System.IO.File.Exists(Path.Combine(webRootPath, oldImage.ImageURL.Substring(1))))
                        {
                            System.IO.File.Delete(Path.Combine(webRootPath, oldImage.ImageURL.Substring(1)));
                        }
                        _context.ClassifiedImage.Remove(oldImage);
                    }

                    int i = 0;
                    foreach (var file in files)
                    {
                        i++;
                        var extension = Path.GetExtension(file.FileName);
                        using (var filestream = new FileStream(Path.Combine(uploads, listing.ClassifiedListingId + @"_" + i + extension), FileMode.Create))
                        {
                            file.CopyTo(filestream); // moves to server and renames
                        }
                        var image = new ClassifiedImage()
                        {
                            ClassifiedListingId = listing.ClassifiedListingId,
                            IsMainImage         = (file == files.First()),
                            ImageExtension      = extension,
                            ImageURL            = @"\" + @"img\ClassifiedsImages" + @"\" + listing.ClassifiedListingId + @"_" + i + extension
                        };

                        _context.ClassifiedImage.Add(image);
                    }
                    await _context.SaveChangesAsync();
                }

                return(RedirectToAction(nameof(Index)));
            }


            ViewData["Category"] = new SelectList(_context.ClassifiedCategory, "ClassifiedCategoryId", "Description", listing.ClassifiedCategoryId);
            return(View(listing));
        }
示例#18
0
        public IActionResult ShowClassification(string localization, List <IFormFile> files)
        {
            ViewData["localization"] = localization;                     //localization contiene il posizione in termini di latitudine e longitudine

            var photo_note = new List <String>();                        //photo_note è una nota di testo contentente i nomi di tutte le immagini passate in input (serve per la classificazione)

            string path1 = @"assets\inputs-predict\data\image_list.tsv"; //path1 percorso della nota di testo
            string path2 = @"assets\inputs-predict\data";                //path2 percorso della cartella contenente le foto



            //se la cartella relativa al 'path2' non esiste viene creata
            if (System.IO.Directory.Exists(path2) == false)
            {
                Directory.CreateDirectory(path2); //viene creata la cartella che conterrà le immagini
            }

            //se la cartella relativa al 'path2' esiste ed è piena viene svuotata per far spazio alle nuove foto in input
            System.IO.DirectoryInfo di = new DirectoryInfo(path2);

            foreach (FileInfo file in di.GetFiles())
            {
                file.Delete();
            }
            foreach (DirectoryInfo dir in di.GetDirectories())
            {
                dir.Delete(true);
            }

            //files_from_video è la lista che conterrà i nome dei frame video (nel caso in cui in input ci fosse un video)
            List <String> files_from_video = new List <String>();

            //cotruisco una lista di oggetti da salvare nel database successivamente
            List <ClassifiedImage> classifiedImages = new List <ClassifiedImage>();

            int i = 0;                   //mi serve per la gestione della lista 'score'
            int n = 0;                   //mi serve per la gestione della lista 'classifiedImages'

            foreach (var image in files) //iterazione di tutte le immagini in input
            {
                if (image != null)
                {
                    /*
                     * GESTIONE CARICAMENTO IMMAGINI
                     */



                    //il seguente if serve per controllare se il file caricato è un immagine o no
                    if (Path.GetExtension(image.FileName).ToLower() == ".jpg" ||
                        Path.GetExtension(image.FileName).ToLower() == ".png" ||
                        Path.GetExtension(image.FileName).ToLower() == ".gif" ||
                        Path.GetExtension(image.FileName).ToLower() == ".jpeg")
                    {
                        var fileName = Path.Combine(he.WebRootPath, Path.GetFileName(image.FileName));
                        image.CopyTo(new FileStream(fileName, FileMode.Create));

                        photo_note.Add(image.FileName); //il nome dell'immagine viene aggiunto alla nota di testo

                        string FileToCopy = null;
                        string NewCopy    = null;
                        FileToCopy = fileName;
                        NewCopy    = Path.Combine(path2, image.FileName); //viene caricata l'immagine nel 'path2'

                        //se l'immagine gia esiste viene sovrascritta
                        if (System.IO.File.Exists(FileToCopy) == true)
                        {
                            if (System.IO.File.Exists(NewCopy))
                            {
                                System.IO.File.Delete(NewCopy);
                            }
                            System.IO.File.Copy(FileToCopy, NewCopy);
                        }


                        //visto che in ingresso ci sono immagini viene settata a null la lista files_from_video
                        files_from_video = null;

                        Image p = Image.FromFile("assets/inputs-predict/data/" + image.FileName);


                        //converto l'immagine in una stringa base64
                        MemoryStream m = new MemoryStream();
                        p.Save(m, p.RawFormat);
                        byte[] imageBytes   = m.ToArray();
                        string base64String = Convert.ToBase64String(imageBytes);

                        string img_db          = base64String;
                        string gpsLatitudeRef  = " ";
                        double latitude        = 0;
                        string gpsLongitudeRef = " ";
                        double longitude       = 0;


                        //la seguente porzione di codice serve per estrapolare i metadati dalle immagine
                        try{
                            gpsLatitudeRef  = BitConverter.ToChar(p.GetPropertyItem(1).Value, 0).ToString();
                            latitude        = DecodeRational64u(p.GetPropertyItem(2));
                            gpsLongitudeRef = BitConverter.ToChar(p.GetPropertyItem(3).Value, 0).ToString();
                            longitude       = DecodeRational64u(p.GetPropertyItem(4));
                        }
                        catch (System.ArgumentException e)
                        {
                            Console.WriteLine("{0} Exception caught.", e);
                        }

                        string geolocalization = (latitude.ToString().Replace(",", ".") + "," + longitude.ToString().Replace(",", "."));
                        string filetype        = Path.GetExtension(image.FileName);
                        string photoname       = image.FileName;


                        //creo un nuovo oggetto da aggiungere al database
                        ClassifiedImage classifiedImage = new ClassifiedImage
                        {
                            PhotoName                = photoname,
                            Date                     = DateTime.Now,
                            Photo                    = img_db,
                            Latitude                 = latitude,
                            Longitude                = longitude,
                            FileType                 = filetype,
                            Geolocalization          = geolocalization,
                            FireScoreClassification  = 200,
                            SmokeScoreClassification = 233
                        };

                        classifiedImages.Add(classifiedImage);
                    }

                    /*
                     * GESTIONE CARICAMENTO IMMAGINI DA VIDEO
                     */
                    /*
                     * il servizio chiamato estrae i frame dal video caricato e successivamente
                     * carica all'interno della cartella (che poi si trasformerà in un db) sia questi ultimi che
                     * il file di testo.
                     *
                     */
                    if (Path.GetExtension(image.FileName).ToLower() == ".avi")
                    {
                        var        fileName   = Path.Combine(he.WebRootPath, Path.GetFileName(image.FileName));
                        FileStream filestream = new FileStream(fileName, FileMode.Create);
                        image.CopyTo(filestream);
                        filestream.Close();

                        string FileToCopy = fileName;
                        string NewCopy    = null;
                        NewCopy = Path.Combine(path2, image.FileName); //viene caricato il video


                        //se il video gia esiste viene sovrascritta
                        if (System.IO.File.Exists(FileToCopy) == true)
                        {
                            if (System.IO.File.Exists(NewCopy))
                            {
                                System.IO.File.Delete(NewCopy);
                            }
                            System.IO.File.Copy(FileToCopy, NewCopy);
                        }

                        String uriString = "http://localhost:5020";
                        // Create a new WebClient instance.
                        WebClient myWebClient = new WebClient();

                        string fileNameHttpUpload = NewCopy;
                        // Caricamento del file sull'URI.
                        // Il metodo 'UploadFile(uriString,fileName)' usa implicitamente il metodo POST HTTP.
                        byte[] responseArray = myWebClient.UploadFile(uriString, fileNameHttpUpload);

                        // Decodificazione e visualizzazione della risposta.
                        Console.WriteLine("\nResponse Received.The contents of the file uploaded are:\n{0}",
                                          System.Text.Encoding.ASCII.GetString(responseArray));

                        // estrapolazione dei nomi dei frame contenuti all'interno del file di testo per salvarli nell'arraylist photo_note
                        // lettura file usando StreamReader.
                        using (StreamReader file = new StreamReader(path1))
                        {
                            int    counter = 0;
                            string ln;

                            while ((ln = file.ReadLine()) != null)
                            {
                                photo_note.Add(ln);
                                files_from_video.Add("/" + ln);
                                counter++;
                            }
                            file.Close();
                        }

                        foreach (var frame in files_from_video)
                        {
                            Image frame_video = Image.FromFile("assets/inputs-predict/data" + frame);

                            // conversione dell'immagine in una stringa base64
                            MemoryStream m = new MemoryStream();
                            frame_video.Save(m, frame_video.RawFormat);
                            byte[] imageBytes        = m.ToArray();
                            string base64Stringvideo = Convert.ToBase64String(imageBytes);

                            string frame_db = base64Stringvideo;

                            string gpsLatitudeRef  = " ";
                            double latitude        = 0;
                            string gpsLongitudeRef = " ";
                            double longitude       = 0;

                            try
                            {
                                gpsLatitudeRef  = BitConverter.ToChar(frame_video.GetPropertyItem(1).Value, 0).ToString();
                                latitude        = DecodeRational64u(frame_video.GetPropertyItem(2));
                                gpsLongitudeRef = BitConverter.ToChar(frame_video.GetPropertyItem(3).Value, 0).ToString();
                                longitude       = DecodeRational64u(frame_video.GetPropertyItem(4));
                            }
                            catch (System.ArgumentException e)
                            {
                                Console.WriteLine("{0} Exception caught.", e);
                            }

                            string geolocalization = (latitude.ToString().Replace(",", ".") + "," + longitude.ToString().Replace(",", "."));
                            string filetype        = Path.GetExtension(frame);
                            string photoname       = frame;



                            //creazione di un nuovo oggetto da aggiungere al database
                            ClassifiedImage classifiedImage = new ClassifiedImage
                            {
                                PhotoName                = photoname,
                                Date                     = DateTime.Now,
                                Photo                    = frame_db,
                                Latitude                 = latitude,
                                Longitude                = longitude,
                                FileType                 = filetype,
                                Geolocalization          = geolocalization,
                                FireScoreClassification  = 200,
                                SmokeScoreClassification = 233
                            };

                            classifiedImages.Add(classifiedImage);
                        }
                    }
                }
            }


            // se il file di testo gia esiste viene cancellato e poi creato
            if (System.IO.File.Exists(path1) == true)
            {
                System.IO.File.Delete(path1);
            }
            using (StreamWriter sw = System.IO.File.CreateText(path1))
            {
                foreach (var photo in photo_note) //iterazione della nota per scrivere i nomi all'interno di essa
                {
                    sw.WriteLine(photo);
                }
            }

            // creazione di una lista di stringhe che contiene i nomi di ogni immagine classicata
            var listfilenames = new List <String>();

            foreach (var o in files)
            {
                listfilenames.Add("/" + Path.GetFileName(o.FileName));
            }

            var score_fire  = new List <String>(); // creazione di una lista di stringhe che conterrà i valori di classificazione con il modello del fuoco
            var score_smoke = new List <String>(); // creazione di una lista di stringhe che conterrà i valori di classificazione con il modello del fumo
            var score       = new List <String>(); // creazione di una lista di stringhe che conterrà i valori di classificazione di entrambi i modelli

            // le liste vengono riempite chiamando un metodo proveniente dal progetto di tipo ML.NET
            score_fire  = TransferLearningTF.Program.ClassyAPIfire();
            score_smoke = TransferLearningTF.Program.ClassyAPIsmoke();

            // riempimento della lista score iterando sulle liste dei due modelli
            i = 0;
            foreach (var sco in score_fire)
            {
                score.Add(sco);
                score.Add(score_smoke[i]);
                i++;
            }

            n = 0;
            foreach (var cimg in classifiedImages)
            {
                cimg.FireTypeClassification   = score[n];
                cimg.SmokeTypeClassification  = score[n + 1];
                cimg.FireScoreClassification  = Convert.ToDouble(score[n + 2].ToString());
                cimg.SmokeScoreClassification = Convert.ToDouble(score[n + 3].ToString());
                n = n + 4;
            }


            if (files_from_video != null)
            {
                ViewData["filenames"] = files_from_video;
            }
            else
            {
                ViewData["filenames"] = listfilenames;
            }


            int countrow = CountRowInDB(); //qui conto il numero degli elementi all'interno del DB per calcolare l'Id

            Console.WriteLine("AAAAAAAAA: " + countrow);

            // questo serve per settare l'Id all'interno della lista classifiedImages da passare a ShowClassification
            int countrow_noid = 0;

            if (!countrow.Equals(1))
            {
                // se non è la prima immagine da inserire nel database allora bisogna prendere l'ultimo numero messo come id
                countrow_noid = GetLastIndexUpdate(countrow - 2);
            }

            PostClassifiedImages(classifiedImages, countrow);

            ViewData["classifiedImages"] = classifiedImages;
            ViewData["score"]            = score; // lista classificazione di ogni immagine

            return(View());
        }
示例#19
0
        public async Task <IActionResult> AddServicePOST(string description)
        {
            if (String.IsNullOrEmpty(description))
            {
                ModelState.AddModelError("Description", "Please enter a description");
            }

            var files = HttpContext.Request.Form.Files;

            if (files == null || files.Count == 0)
            {
                ModelState.AddModelError("Files", "Please upload one file");
            }

            if (ModelState.IsValid)
            {
                var identityUser = await _userManager.GetUserAsync(HttpContext.User);

                var loggedInUser = await _context.Owner.FindAsync(identityUser.OwnerId);

                var service = new ClassifiedListing
                {
                    ClassifiedCategoryId = 3, // Manually set to "Other"
                    ItemName             = "Service",
                    Description          = description,
                    Price            = 0,
                    LastModifiedBy   = loggedInUser.FullName,
                    LastModifiedDate = DateTime.Now,
                    ListingDate      = DateTime.Now,
                    Owner            = loggedInUser,
                    OwnerId          = loggedInUser.OwnerId
                };

                _context.ClassifiedListing.Add(service);
                await _context.SaveChangesAsync();

                //image uploading
                string webRootPath = _hostingEnvironment.WebRootPath;

                var uploads = Path.Combine(webRootPath, @"img\ClassifiedsImages");

                var file      = files[0];
                var extension = Path.GetExtension(file.FileName);
                using (var filestream = new FileStream(Path.Combine(uploads, service.ClassifiedListingId + extension), FileMode.Create))
                {
                    file.CopyTo(filestream); // moves to server and renames
                }
                var image = new ClassifiedImage()
                {
                    ClassifiedListingId = service.ClassifiedListingId,
                    IsMainImage         = (file == files.First()),
                    ImageExtension      = extension,
                    ImageURL            = @"\" + @"img\ClassifiedsImages" + @"\" + service.ClassifiedListingId + extension
                };

                _context.Add(image);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            return(View());
        }
 public Bitmap GetFaceBitmapFromClassifiedImage(ClassifiedImage image)
 {
     return(new Mat(image.Mat, image.Locations.First()).Resize(new Size(100, 100), interpolation: InterpolationFlags.Cubic).ToBitmap());
 }
示例#21
0
 public Bitmap GetFaceBitmapFromClassifiedImage(ClassifiedImage image)
 {
     return image.Image.Copy(image.Locations.First()).Resize(100, 100, Inter.Cubic).ToBitmap();
 }