TesteCaminhao/TesteImagemCaminhao/Controllers/VehicleDetectionController .cs
2025-03-17 11:13:59 -03:00

233 lines
7.9 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.ML;
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.Drawing;
using Microsoft.ML;
using Microsoft.ML.Vision;
using static System.Net.Mime.MediaTypeNames;
using Microsoft.ML.Data;
using TesteImagemCaminhao;
using Microsoft.ML.Transforms.Image;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace VehicleDetectionAPI
{
[ApiController]
[Route("api/[controller]")]
public class VehicleDetectionController : ControllerBase
{
private readonly PredictionEngine<ModelInput, ModelOutput> _predictionEngine;
private readonly IWheelsDetectionService _wheelsDetectionService;
public VehicleDetectionController(
PredictionEnginePool<ModelInput, ModelOutput> predictionEnginePool,
IWheelsDetectionService wheelsDetectionService)
{
_predictionEngine = predictionEnginePool.GetPredictionEngine("VehicleTypeModel");
_wheelsDetectionService = wheelsDetectionService;
}
[HttpPost]
[Route("detect")]
public async Task<IActionResult> DetectVehicle(IFormFile imageFile)
{
if (imageFile == null || imageFile.Length == 0)
return BadRequest("Nenhuma imagem foi enviada.");
try
{
// Salvar a imagem temporariamente
var imagePath = Path.GetTempFileName();
using (var stream = new FileStream(imagePath, FileMode.Create))
{
await imageFile.CopyToAsync(stream);
}
// Detectar o tipo de veículo
var vehicleType = DetectVehicleType(imagePath);
var wheelsCount = 0;
switch (vehicleType.ToLower())
{
case "motos":
wheelsCount = 2;
break;
case "carros":
wheelsCount = 4;
break;
case "caminhao":
wheelsCount = 6;
break;
default:
wheelsCount = -1;
break;
}
// Excluir o arquivo temporário
System.IO.File.Delete(imagePath);
return Ok(new
{
VehicleType = vehicleType,
WheelsCount = wheelsCount
});
}
catch (Exception ex)
{
return StatusCode(500, $"Erro ao processar a imagem: {ex.Message}");
}
}
private string DetectVehicleType(string imagePath)
{
// Criar um MLContext
var mlContext = new MLContext();
// Carregar o modelo (você precisará ajustar o caminho)
var modelpath = AppContext.BaseDirectory.ToString();
var modelfile = Path.Combine(modelpath, "neMmodel.zip");
var model = modelfile;
//var model = mlContext.Model.Load("C:\\Users\\USER\\Pictures\\neMmodel.zip", out var _);
// Preparar a entrada de dados
var imageData = System.IO.File.ReadAllBytes(imagePath);
var preProcessingPipeline = mlContext
.Transforms
.LoadRawImageBytes(
outputColumnName: "ImageBytes",
imageFolder: Path.GetDirectoryName(imagePath),
inputColumnName: "ImagePath");
var imagePathAsArray = new[]
{
new
{
ImagePath = imagePath,
Label = string.Empty
}
};
//Load the image into a data view and process it into bytes
var imagePathDataView = mlContext
.Data
.LoadFromEnumerable(imagePathAsArray);
var imageBytesDataView = preProcessingPipeline
.Fit(imagePathDataView)
.Transform(imagePathDataView);
// Create a model input to use in the prediction engine
var modelInput = mlContext
.Data
.CreateEnumerable<ModelInput>(
imageBytesDataView,
true)
.First();
// Fazer a previsão
var prediction = _predictionEngine.Predict(modelInput);
// Retornar o tipo de veículo com maior confiança
return prediction.PredictedLabel;
}
private string DetectVehicleType2(string imagePath)
{
// Criar um MLContext
var mlContext = new MLContext();
// Carregar o modelo (você precisará ajustar o caminho)
var model = mlContext.Model.Load("C:\\Users\\USER\\Pictures\\neMmodel.zip", out var _);
// Preparar a entrada de dados
var imageData = System.IO.File.ReadAllBytes(imagePath);
// Criar um IDataView a partir da entrada
var dataView = mlContext.Data.LoadFromEnumerable(new List<ModelInput>
{
new ModelInput
{
ImagePath = imagePath//,
//input = MLImage.CreateFromFile(imagePath)
}
});
// Realizar a predição
var predictions = model.Transform(dataView);
// Converter para enumerável para acessar os resultados
var results = mlContext.Data.CreateEnumerable<ModelOutput>(predictions, reuseRowObject: false).ToList();
if (results.Count > 0)
{
// Obter a predição com maior score
var prediction = results[0];
// Exibir os scores para debug
Console.WriteLine($"Scores: {string.Join(", ", prediction.Score)}");
return prediction.PredictedLabel;
}
return "Desconhecido";
}
private string DetectVehicleType1(string imagePath)
{
// Carregar imagem para ML.NET
var image = MLImage.CreateFromFile(imagePath);
// Preparar os dados de entrada
ModelInput input = new ModelInput
{
ImageBytes = new byte[image.Width * image.Height]
};
// Fazer a previsão
var prediction = _predictionEngine.Predict(input);
// Retornar o tipo de veículo com maior confiança
return prediction.PredictedLabel;
}
private int EstimateAxlesFromWheels(string vehicleType, int wheelsCount)
{
// Lógica para estimar a quantidade de eixos com base no tipo de veículo e número de rodas
switch (vehicleType.ToLower())
{
case "motos":
return wheelsCount / 2;
case "carros":
return wheelsCount / 4 > 0 ? wheelsCount / 4 : 1;
case "caminhao":
// Caminhões normalmente têm mais de um eixo
return Math.Max(2, wheelsCount / 4);
default:
return wheelsCount / 4;
}
}
}
// Classes para o modelo ML.NET
public class ModelInput
{
public byte[] ImageBytes { get; set; }
public string Label { get; set; }
public string ImagePath { get; set; }
}
public class ModelOutput
{
public string PredictedLabel { get; set; }
public float[] Score { get; set; }
}
}