commit bfafb85d1caa142f3d0ef7cff2fb7268fbcebe71
Author: Ricardo Carneiro <71648276+ricarneiro@users.noreply.github.com>
Date: Mon Mar 17 11:13:59 2025 -0300
feat: versáo inicial
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..8a30d25
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,398 @@
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
+
+# User-specific files
+*.rsuser
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Mono auto generated files
+mono_crash.*
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+[Ww][Ii][Nn]32/
+[Aa][Rr][Mm]/
+[Aa][Rr][Mm]64/
+bld/
+[Bb]in/
+[Oo]bj/
+[Ll]og/
+[Ll]ogs/
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# Visual Studio 2017 auto generated files
+Generated\ Files/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+
+# NUnit
+*.VisualState.xml
+TestResult.xml
+nunit-*.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+
+# ASP.NET Scaffolding
+ScaffoldingReadMe.txt
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
+*_i.c
+*_p.c
+*_h.h
+*.ilk
+*.meta
+*.obj
+*.iobj
+*.pch
+*.pdb
+*.ipdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*_wpftmp.csproj
+*.log
+*.tlog
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Coverlet is a free, cross platform Code Coverage Tool
+coverage*.json
+coverage*.xml
+coverage*.info
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# NuGet Symbol Packages
+*.snupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+*.appxbundle
+*.appxupload
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!?*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
+
+# SQL Server files
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+*- [Bb]ackup.rdl
+*- [Bb]ackup ([0-9]).rdl
+*- [Bb]ackup ([0-9][0-9]).rdl
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio 6 auto-generated project file (contains which files were open etc.)
+*.vbp
+
+# Visual Studio 6 workspace and project file (working project files containing files to include in project)
+*.dsw
+*.dsp
+
+# Visual Studio 6 technical files
+*.ncb
+*.aps
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# CodeRush personal settings
+.cr/personal
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+
+# OpenCover UI analysis results
+OpenCover/
+
+# Azure Stream Analytics local run output
+ASALocalRun/
+
+# MSBuild Binary and Structured Log
+*.binlog
+
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
+
+# MFractors (Xamarin productivity tool) working folder
+.mfractor/
+
+# Local History for Visual Studio
+.localhistory/
+
+# Visual Studio History (VSHistory) files
+.vshistory/
+
+# BeatPulse healthcheck temp database
+healthchecksdb
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+MigrationBackup/
+
+# Ionide (cross platform F# VS Code tools) working folder
+.ionide/
+
+# Fody - auto-generated XML schema
+FodyWeavers.xsd
+
+# VS Code files for those working on multiple tools
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+*.code-workspace
+
+# Local History for Visual Studio Code
+.history/
+
+# Windows Installer files from build outputs
+*.cab
+*.msi
+*.msix
+*.msm
+*.msp
+
+# JetBrains Rider
+*.sln.iml
diff --git a/MLTrainingVeiculos/MLTrainingVeiculos.csproj b/MLTrainingVeiculos/MLTrainingVeiculos.csproj
new file mode 100644
index 0000000..c6c4761
--- /dev/null
+++ b/MLTrainingVeiculos/MLTrainingVeiculos.csproj
@@ -0,0 +1,21 @@
+
+
+
+ Exe
+ net8.0
+ enable
+ enable
+ x64
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/MLTrainingVeiculos/Program.cs b/MLTrainingVeiculos/Program.cs
new file mode 100644
index 0000000..4814890
--- /dev/null
+++ b/MLTrainingVeiculos/Program.cs
@@ -0,0 +1,316 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using Microsoft.ML;
+using Microsoft.ML.Data;
+using Microsoft.ML.Vision;
+
+namespace VehicleModelTraining
+{
+ class Program
+ {
+ static void Main(string[] args)
+ {
+ // Caminho para os diretórios de treinamento (organizados por categoria)
+ string datasetFolder = "C:\\Users\\USER\\Pictures\\Veiculos";
+ string workspaceFolder = "C:\\Users\\USER\\Pictures\\WorkSpace";
+ string outputModelPath = "C:\\Users\\USER\\Pictures\\neMmodel.zip";
+
+ // Inicializar MLContext
+ MLContext mlContext = new MLContext(seed: 1);
+
+ var preprocessingPipeline =
+ mlContext
+ .Transforms
+ .LoadRawImageBytes(
+ outputColumnName: "ImageBytes",
+ imageFolder: datasetFolder,
+ inputColumnName: "ImagePath")
+ .Append(
+ mlContext
+ .Transforms
+ .Conversion
+ .MapValueToKey(
+ inputColumnName: "Label",
+ outputColumnName: "LabelAsKey"
+ )
+ );
+
+ // Carregar dados - usamos um método mais direto aqui
+ var images = LoadImagesFromDirectory(datasetFolder);
+ Console.WriteLine($"Número total de imagens carregadas: {images.Count}");
+
+ // Verificar se há imagens
+ if (images.Count == 0)
+ {
+ Console.WriteLine("Nenhuma imagem foi carregada. Verifique o caminho e as extensões suportadas.");
+ return;
+ }
+
+ // Criar o DataFrame
+ IDataView imageData = mlContext.Data.LoadFromEnumerable(images);
+
+ IDataView shuffledImageDataView = mlContext
+ .Data
+ .ShuffleRows(imageData, 0);
+
+
+ Console.WriteLine("Pre processing images....");
+ var timestamp = DateTime.Now;
+
+ // Pre Process images and split into train/test/validation
+ IDataView preProcessedImageDataView = preprocessingPipeline
+ .Fit(shuffledImageDataView)
+ .Transform(shuffledImageDataView);
+
+ Console.WriteLine($"Image preprocessing done in {(DateTime.Now - timestamp).TotalSeconds} seconds");
+ Console.WriteLine();
+
+ var firstSplit = mlContext
+ .Data
+ .TrainTestSplit(data: preProcessedImageDataView,
+ testFraction: 0.3,
+ seed: 0);
+ var trainSet = firstSplit.TrainSet;
+
+ var secondSplit = mlContext
+ .Data
+ .TrainTestSplit(data: firstSplit.TestSet,
+ testFraction: 0.5, seed: 0);
+
+ var validationSet = secondSplit.TrainSet;
+ var testSet = secondSplit.TestSet;
+
+
+ var classifierOptions = new ImageClassificationTrainer.Options()
+ {
+ FeatureColumnName = "ImageBytes",
+ LabelColumnName = "LabelAsKey",
+ Arch = ImageClassificationTrainer.Architecture.InceptionV3,
+ //Arch = ImageClassificationTrainer.Architecture.MobilenetV2,
+ //Arch = ImageClassificationTrainer.Architecture.ResnetV250,
+
+ TestOnTrainSet = false,
+ ValidationSet = validationSet,
+
+ ReuseTrainSetBottleneckCachedValues = true,
+ ReuseValidationSetBottleneckCachedValues = true,
+ WorkspacePath = workspaceFolder,
+
+ MetricsCallback = Console.WriteLine
+ };
+
+ var trainingPipeline = mlContext
+ .MulticlassClassification
+ .Trainers
+ .ImageClassification(classifierOptions)
+ .Append(mlContext
+ .Transforms
+ .Conversion
+ .MapKeyToValue("PredictedLabel"));
+
+ Console.WriteLine("Training model....");
+ timestamp = DateTime.Now;
+
+ var trainedModel = trainingPipeline.Fit(trainSet);
+
+ Console.WriteLine($"Model training done in {(DateTime.Now - timestamp).TotalSeconds} seconds");
+ Console.WriteLine();
+
+ Console.WriteLine("Calculating metrics...");
+
+ IDataView evaluationData = trainedModel.Transform(testSet);
+ var metrics = mlContext
+ .MulticlassClassification
+ .Evaluate(evaluationData, "LabelAsKey");
+
+ Console.WriteLine($"LogLoss: {metrics.LogLoss}");
+ Console.WriteLine($"LogLossReduction: {metrics.LogLossReduction}");
+ Console.WriteLine($"MicroAccuracy: {metrics.MicroAccuracy}");
+ Console.WriteLine($"MacroAccuracy: {metrics.MacroAccuracy}");
+ Console.WriteLine();
+ Console.WriteLine($"{metrics.ConfusionMatrix.GetFormattedConfusionTable()}");
+
+ Console.WriteLine();
+ Console.WriteLine("Saving model");
+
+ Directory.CreateDirectory("Model");
+ mlContext.Model.Save(trainedModel, preProcessedImageDataView.Schema, outputModelPath);
+
+ //Console.WriteLine();
+ //// Exibir informações das categorias
+ //var categoryCount = images.GroupBy(x => x.Label).Select(g => new { Category = g.Key, Count = g.Count() }).ToList();
+ //foreach (var category in categoryCount)
+ //{
+ // Console.WriteLine($"Categoria: {category.Category}, Contagem: {category.Count}");
+ //}
+
+ //// Dividir em dados de treinamento e teste
+ //var dataSplit = mlContext.Data.TrainTestSplit(imageData, testFraction: 0.2);
+ //var trainSet = dataSplit.TrainSet;
+ //var testSet = dataSplit.TestSet;
+
+ //// IMPORTANTE: Para o ImageClassificationTrainer, vamos usar a abordagem recomendada
+ //var classifierOptions = new ImageClassificationTrainer.Options()
+ //{
+ // FeatureColumnName = "Image", // Alterado para 'Image' em vez de 'Input'
+ // LabelColumnName = "LabelKey",
+ // ValidationSet = testSet,
+ // Arch = ImageClassificationTrainer.Architecture.ResnetV2101,
+ // Epoch = 10,
+ // BatchSize = 5,
+ // LearningRate = 0.01f,
+ // MetricsCallback = (metrics) => Console.WriteLine(metrics),
+ // WorkspacePath = Path.Combine(Environment.CurrentDirectory, "workspace"),
+ // //TrainDatasetPath = Path.Combine(Environment.CurrentDirectory, "trainFolder"),
+ // //TestDatasetPath = Path.Combine(Environment.CurrentDirectory, "testFolder"),
+ // //OutputTensorName = "softmax2_pre_activation", // Nome da camada de saÃda do Resnet
+ // ReuseValidationSetBottleneckCachedValues = true,
+ // ReuseTrainSetBottleneckCachedValues = true
+ //};
+
+ //try
+ //{
+ // // Criar diretórios necessários
+ // EnsureDirectoryExists(classifierOptions.WorkspacePath);
+ // //EnsureDirectoryExists(classifierOptions.TrainDatasetPath);
+ // //EnsureDirectoryExists(classifierOptions.TestDatasetPath);
+
+ // // Construir pipeline com passos especÃficos para o ImageClassificationTrainer
+ // var pipeline = mlContext.Transforms.LoadImages(
+ // outputColumnName: "Image",
+ // imageFolder: "",
+ // inputColumnName: nameof(ImageData.ImagePath))
+ // .Append(mlContext.Transforms.Conversion.MapValueToKey(
+ // outputColumnName: "LabelKey",
+ // inputColumnName: nameof(ImageData.Label)))
+ // .Append(mlContext.MulticlassClassification.Trainers.ImageClassification(classifierOptions))
+ // .Append(mlContext.Transforms.Conversion.MapKeyToValue(
+ // outputColumnName: "PredictedLabel",
+ // inputColumnName: "PredictedLabel"));
+
+ // Console.WriteLine("\nIniciando o treinamento do modelo...");
+
+ // // Treinar o modelo
+ // ITransformer trainedModel = pipeline.Fit(trainSet);
+ // Console.WriteLine("Treinamento concluÃdo com sucesso!");
+
+ // // Salvar o modelo
+ // mlContext.Model.Save(trainedModel, trainSet.Schema, outputModelPath);
+ // Console.WriteLine($"Modelo salvo em: {outputModelPath}");
+
+ // // Avaliar o modelo
+ // EvaluateModel(mlContext, testSet, trainedModel);
+
+ // // Opcional: Remover diretórios temporários após o uso
+ // //CleanupDirectory(classifierOptions.WorkspacePath);
+ // //CleanupDirectory(classifierOptions.TrainDatasetPath);
+ // //CleanupDirectory(classifierOptions.TestDatasetPath);
+ //}
+ //catch (Exception ex)
+ //{
+ // Console.WriteLine($"Erro durante o treinamento: {ex.Message}");
+ // Console.WriteLine($"Detalhes: {ex.StackTrace}");
+
+ // if (ex.InnerException != null)
+ // {
+ // Console.WriteLine($"Inner Exception: {ex.InnerException.Message}");
+ // Console.WriteLine($"Inner Stack Trace: {ex.InnerException.StackTrace}");
+ // }
+ //}
+ }
+
+ private static void EnsureDirectoryExists(string path)
+ {
+ if (!Directory.Exists(path))
+ {
+ Directory.CreateDirectory(path);
+ Console.WriteLine($"Diretório criado: {path}");
+ }
+ }
+
+ private static void CleanupDirectory(string path)
+ {
+ if (Directory.Exists(path))
+ {
+ try
+ {
+ Directory.Delete(path, recursive: true);
+ Console.WriteLine($"Diretório removido: {path}");
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Erro ao remover diretório {path}: {ex.Message}");
+ }
+ }
+ }
+
+ // Avaliar o desempenho do modelo nos dados de teste
+ private static void EvaluateModel(MLContext mlContext, IDataView testData, ITransformer trainedModel)
+ {
+ IDataView predictions = trainedModel.Transform(testData);
+ var metrics = mlContext.MulticlassClassification.Evaluate(predictions, labelColumnName: "LabelKey", predictedLabelColumnName: "PredictedLabel");
+
+ Console.WriteLine($"Acurácia micro: {metrics.MicroAccuracy:0.###}");
+ Console.WriteLine($"Acurácia macro: {metrics.MacroAccuracy:0.###}");
+ Console.WriteLine($"Pontuação de perda de log: {metrics.LogLoss:#.###}");
+
+ // Exibir matriz de confusão
+ Console.WriteLine("Matriz de confusão:");
+ Console.WriteLine(metrics.ConfusionMatrix.GetFormattedConfusionTable());
+ }
+
+ // Carregar imagens do diretório
+ private static List LoadImagesFromDirectory(string folder)
+ {
+ List images = new List();
+
+ try
+ {
+ var files = Directory.GetFiles(folder, "*", searchOption: SearchOption.AllDirectories);
+ var imageFiles = files.Where(file =>
+ Path.GetExtension(file).ToLower() == ".jpg" ||
+ Path.GetExtension(file).ToLower() == ".jpeg" ||
+ Path.GetExtension(file).ToLower() == ".png" ||
+ Path.GetExtension(file).ToLower() == ".webp").ToList();
+
+ Console.WriteLine($"Encontrados {imageFiles.Count} arquivos de imagem em {folder}");
+
+ foreach (var file in imageFiles)
+ {
+ // Verificar se o arquivo existe
+ if (!File.Exists(file))
+ {
+ Console.WriteLine($"Arquivo não encontrado: {file}");
+ continue;
+ }
+
+ // Determinar a categoria com base no nome da pasta pai
+ var label = Directory.GetParent(file).Name;
+ Console.WriteLine($"Processando imagem: {file}, Label: {label}");
+
+ images.Add(new ImageData()
+ {
+ ImagePath = file,
+ Label = label
+ });
+ }
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Erro ao carregar imagens: {ex.Message}");
+ }
+
+ return images;
+ }
+
+ // Classe para representar dados de imagem
+ public class ImageData
+ {
+ public string ImagePath { get; set; }
+ public string Label { get; set; }
+ public byte[] ImageBytes { get; set; }
+ }
+ }
+}
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..e69de29
diff --git a/TesteCaminhao.sln b/TesteCaminhao.sln
new file mode 100644
index 0000000..85a07fc
--- /dev/null
+++ b/TesteCaminhao.sln
@@ -0,0 +1,31 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.10.35122.118
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TesteImagemCaminhao", "TesteImagemCaminhao\TesteImagemCaminhao.csproj", "{14E2FF5A-D3BC-4E6D-A421-2DAC489A2363}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MLTrainingVeiculos", "MLTrainingVeiculos\MLTrainingVeiculos.csproj", "{43A36E3B-3D8A-4F31-A959-2310B510957E}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {14E2FF5A-D3BC-4E6D-A421-2DAC489A2363}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {14E2FF5A-D3BC-4E6D-A421-2DAC489A2363}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {14E2FF5A-D3BC-4E6D-A421-2DAC489A2363}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {14E2FF5A-D3BC-4E6D-A421-2DAC489A2363}.Release|Any CPU.Build.0 = Release|Any CPU
+ {43A36E3B-3D8A-4F31-A959-2310B510957E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {43A36E3B-3D8A-4F31-A959-2310B510957E}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {43A36E3B-3D8A-4F31-A959-2310B510957E}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {43A36E3B-3D8A-4F31-A959-2310B510957E}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {62092363-AC4B-4A2E-B79F-E10DBC35E242}
+ EndGlobalSection
+EndGlobal
diff --git a/TesteCaminhao/Program.cs b/TesteCaminhao/Program.cs
new file mode 100644
index 0000000..bb04eb2
--- /dev/null
+++ b/TesteCaminhao/Program.cs
@@ -0,0 +1,44 @@
+var builder = WebApplication.CreateBuilder(args);
+
+// Add services to the container.
+// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
+builder.Services.AddEndpointsApiExplorer();
+builder.Services.AddSwaggerGen();
+
+var app = builder.Build();
+
+// Configure the HTTP request pipeline.
+if (app.Environment.IsDevelopment())
+{
+ app.UseSwagger();
+ app.UseSwaggerUI();
+}
+
+app.UseHttpsRedirection();
+
+var summaries = new[]
+{
+ "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
+};
+
+app.MapGet("/weatherforecast", () =>
+{
+ var forecast = Enumerable.Range(1, 5).Select(index =>
+ new WeatherForecast
+ (
+ DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
+ Random.Shared.Next(-20, 55),
+ summaries[Random.Shared.Next(summaries.Length)]
+ ))
+ .ToArray();
+ return forecast;
+})
+.WithName("GetWeatherForecast")
+.WithOpenApi();
+
+app.Run();
+
+internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
+{
+ public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
+}
diff --git a/TesteCaminhao/Properties/launchSettings.json b/TesteCaminhao/Properties/launchSettings.json
new file mode 100644
index 0000000..9c4063a
--- /dev/null
+++ b/TesteCaminhao/Properties/launchSettings.json
@@ -0,0 +1,41 @@
+{
+ "$schema": "http://json.schemastore.org/launchsettings.json",
+ "iisSettings": {
+ "windowsAuthentication": false,
+ "anonymousAuthentication": true,
+ "iisExpress": {
+ "applicationUrl": "http://localhost:58312",
+ "sslPort": 0
+ }
+ },
+ "profiles": {
+ "http": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "launchUrl": "swagger",
+ "applicationUrl": "http://localhost:5115",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "https": {
+ "commandName": "Project",
+ "dotnetRunMessages": true,
+ "launchBrowser": true,
+ "launchUrl": "swagger",
+ "applicationUrl": "https://localhost:7210;http://localhost:5115",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ },
+ "IIS Express": {
+ "commandName": "IISExpress",
+ "launchBrowser": true,
+ "launchUrl": "swagger",
+ "environmentVariables": {
+ "ASPNETCORE_ENVIRONMENT": "Development"
+ }
+ }
+ }
+}
diff --git a/TesteCaminhao/TesteCaminhao.csproj b/TesteCaminhao/TesteCaminhao.csproj
new file mode 100644
index 0000000..7015e9b
--- /dev/null
+++ b/TesteCaminhao/TesteCaminhao.csproj
@@ -0,0 +1,14 @@
+
+
+
+ net8.0
+ enable
+ enable
+
+
+
+
+
+
+
+
diff --git a/TesteCaminhao/TesteCaminhao.http b/TesteCaminhao/TesteCaminhao.http
new file mode 100644
index 0000000..ec6d215
--- /dev/null
+++ b/TesteCaminhao/TesteCaminhao.http
@@ -0,0 +1,6 @@
+@TesteCaminhao_HostAddress = http://localhost:5115
+
+GET {{TesteCaminhao_HostAddress}}/weatherforecast/
+Accept: application/json
+
+###
diff --git a/TesteCaminhao/appsettings.Development.json b/TesteCaminhao/appsettings.Development.json
new file mode 100644
index 0000000..0c208ae
--- /dev/null
+++ b/TesteCaminhao/appsettings.Development.json
@@ -0,0 +1,8 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ }
+}
diff --git a/TesteCaminhao/appsettings.json b/TesteCaminhao/appsettings.json
new file mode 100644
index 0000000..10f68b8
--- /dev/null
+++ b/TesteCaminhao/appsettings.json
@@ -0,0 +1,9 @@
+{
+ "Logging": {
+ "LogLevel": {
+ "Default": "Information",
+ "Microsoft.AspNetCore": "Warning"
+ }
+ },
+ "AllowedHosts": "*"
+}
diff --git a/TesteImagemCaminhao/Controllers/Circle1DetectionController.cs b/TesteImagemCaminhao/Controllers/Circle1DetectionController.cs
new file mode 100644
index 0000000..78e3b8c
--- /dev/null
+++ b/TesteImagemCaminhao/Controllers/Circle1DetectionController.cs
@@ -0,0 +1,389 @@
+using Microsoft.AspNetCore.Mvc;
+using OpenCvSharp;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Threading.Tasks;
+using CircleDetectionApi.Helpers;
+
+namespace CircleDetectionApi.Controllers
+{
+ [ApiController]
+ [Route("api/[controller]")]
+ public class Circle1DetectionController : ControllerBase
+ {
+ private readonly IWebHostEnvironment _environment;
+ private readonly VehicleDetectionHelper _vehicleDetector;
+
+ public Circle1DetectionController(IWebHostEnvironment environment)
+ {
+ _environment = environment;
+
+ // Caminho para os arquivos do modelo YOLO
+ var modelPath = Path.Combine(environment.ContentRootPath, "Models", "yolov4.weights");
+ var configPath = Path.Combine(environment.ContentRootPath, "Models", "yolov4.cfg");
+ var classesPath = Path.Combine(environment.ContentRootPath, "Models", "coco.names");
+
+ // Inicializar o detector de veÃculos
+ _vehicleDetector = new VehicleDetectionHelper(modelPath, configPath, classesPath);
+ }
+
+ [HttpPost]
+ public async Task DetectCircles(IFormFile image, bool detectVehicle)
+ {
+ // Verificar se a imagem foi enviada
+ if (image == null || image.Length == 0)
+ {
+ return BadRequest(new { error = "Nenhuma imagem foi enviada" });
+ }
+
+ // Verificar o tipo do arquivo
+ var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".bmp", ".tiff" };
+ var extension = Path.GetExtension(image.FileName).ToLowerInvariant();
+
+ if (!allowedExtensions.Contains(extension))
+ {
+ return BadRequest(new { error = "Tipo de arquivo não suportado. Por favor, envie uma imagem JPG, PNG, BMP ou TIFF." });
+ }
+
+ try
+ {
+ // Ler a imagem em um MemoryStream
+ using var memoryStream = new MemoryStream();
+ await image.CopyToAsync(memoryStream);
+ memoryStream.Position = 0;
+
+ // Carregar a imagem usando OpenCvSharp
+ using var mat = Mat.FromImageData(memoryStream.ToArray(), ImreadModes.Color);
+
+ // Variáveis para armazenar informações sobre o veÃculo
+ bool isVehicle = false;
+ string vehicleClass = "Não detectado";
+ Rect vehicleBox = new Rect();
+
+ // Detectar veÃculo (se solicitado)
+ if (detectVehicle)
+ {
+ (isVehicle, vehicleClass, vehicleBox) = _vehicleDetector.DetectVehicle(mat);
+ }
+
+ // Converter para escala de cinza
+ using var grayMat = new Mat();
+ Cv2.CvtColor(mat, grayMat, ColorConversionCodes.BGR2GRAY);
+
+ // Aplicar blur para reduzir ruÃdo
+ using var blurredMat = new Mat();
+ Cv2.MedianBlur(grayMat, blurredMat, 5);
+
+ // Usar o algoritmo de Hough Circle para detectar cÃrculos
+ CircleSegment[] circles = Cv2.HoughCircles(
+ blurredMat,
+ HoughModes.Gradient,
+ 1, // Razão entre resolução da imagem e acumulador
+ 240, // Distância mÃnima entre centros de cÃrculos detectados
+ param1: 250, // Limite superior para detector de bordas Canny
+ param2: 50, // Limite para detecção de centros
+ minRadius: 5, // Raio mÃnimo do cÃrculo
+ maxRadius: 200 // Raio máximo do cÃrculo
+ );
+
+ // Também tentar o método de detecção avançado
+ var wheelDetections = VehicleDetectionHelper.DetectWheelsAndAxles(mat);
+
+ // Criar lista para armazenar os cÃrculos detectados
+ var detectedCircles = new List