A automação de auditoria de palavras-chave para arquivos de imagem garante que os seus dados visuais são coerentemente marcados e facilmente encontráveis. com Aspose.OCR para .NET, você pode ler texto incorporado/visível das imagens e validá-lo contra uma lista controlada de palavra-chave – então relate o que está faltando. este guia melhora o fluxo de trabalho com passos concretos e executáveis que correspondem ao gist no final, além de melhorias opcionais para planejamento, relatório e manutenção.
Exemplo completo
Pré-requisitos
- .NET 8 (ou .NET 6+) SDK instalado.
- NuGet acesso para instalar
Aspose.OCR
. - Uma pasta de imagens para auditoria (por exemplo,
C:\Path\To\ImageArchive
). - (Opcional) Um arquivo de licença Aspose se você pretende ultrapassar os limites de avaliação.
Crie o projeto e adicione pacotes
dotnet new console -n ImageArchiveKeywordAudit -f net8.0
cd ImageArchiveKeywordAudit
dotnet add package Aspose.OCR
Passo 1 – Prepare a sua lista de palavras-chave
Decida as palavras-chave canônicas que as suas imagens devem conter.No gist, as palabras-cheve são hardcodadas para simplicidade:
// Exact shape used in the gist
List<string> keywords = new List<string>
{
"mountains", "beaches", "forests", "landscape"
};
- Tipo (opcional): * Armazenar palavras-chave em
keywords.txt
(um por linha) e carregá-los emList<string>
em tempo real para evitar recompilações.
Passo 2 - Iniciar Aspose.OCR e escanear o arquivo
Compatível com o gesto: crie um motor OCR, enumere imagens, cada arquivo O CR e verifique a presença de palavras-chave.
using System;
using System.Collections.Generic;
using System.IO;
using Aspose.Ocr;
namespace ImageArchiveKeywordAudit
{
class Program
{
static void Main(string[] args)
{
// Path to the image archive directory (edit to your folder)
string imageDirectory = @"C:\Path\To\ImageArchive";
// Keyword list for auditing (matches the gist approach)
List<string> keywords = new List<string>
{
"mountains", "beaches", "forests", "landscape"
};
// Initialize Aspose.OCR API (license is optional)
// new License().SetLicense("Aspose.Total.lic");
using (AsposeOcr api = new AsposeOcr())
{
// Process each JPG in the directory (same filter style as the gist)
foreach (string imagePath in Directory.GetFiles(imageDirectory, "*.jpg"))
{
// Extract text from the image
string extractedText = api.RecognizeImageFile(imagePath);
// Audit the extracted text against the keyword list
bool containsKeywords = AuditText(extractedText, keywords);
// Output the results
Console.WriteLine($"Image: {imagePath} - Contains Keywords: {containsKeywords}");
}
}
}
// Method to audit extracted text against a list of keywords (as in gist)
static bool AuditText(string text, List<string> keywords)
{
foreach (string keyword in keywords)
{
if (text.Contains(keyword, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
}
Passo 3 – Estender a auditoria (opcional, mas recomendado)
Você pode melhorar o relatório e filtragem enquanto mantém o mesmo núcleo OCR.
3.a Tipos de imagem múltiplos do filtro
// Replace the single GetFiles with this multi-pattern approach
string[] patterns = new[] { "*.jpg", "*.jpeg", "*.png", "*.tif", "*.tiff", "*.bmp" };
var imageFiles = new List<string>();
foreach (var pattern in patterns)
imageFiles.AddRange(Directory.GetFiles(imageDirectory, pattern, SearchOption.TopDirectoryOnly));
3.b Capturar que palavras-chave correspondem / faltam
// After OCR:
var matched = new List<string>();
var missing = new List<string>();
foreach (var k in keywords)
(extractedText.IndexOf(k, StringComparison.OrdinalIgnoreCase) >= 0 ? matched : missing).Add(k);
Console.WriteLine($"Image: {Path.GetFileName(imagePath)} | Matched: [{string.Join(", ", matched)}] | Missing: [{string.Join(", ", missing)}]");
3.c Escreva um relatório CSV
string reportPath = Path.Combine(imageDirectory, "audit-report.csv");
bool writeHeader = !File.Exists(reportPath);
using (var sw = new StreamWriter(reportPath, append: true))
{
if (writeHeader)
sw.WriteLine("Image,ContainsKeywords,Matched,Missing");
sw.WriteLine($"\"{Path.GetFileName(imagePath)}\",{matched.Count > 0},\"{string.Join(";", matched)}\",\"{string.Join(";", missing)}\"");
}
Passo 4 – Execute o PowerShell ou o Batch
Crie um simples PowerShell Runner run-audit.ps1
:
# Adjust paths as needed
$solutionRoot = "C:\Path\To\ImageArchiveKeywordAudit"
$imageDir = "C:\Path\To\ImageArchive"
# Build and run
dotnet build "$solutionRoot" -c Release
& "$solutionRoot\bin\Release\net8.0\ImageArchiveKeywordAudit.exe"
Opcional: Se você modificar o programa para aceitar argumentos, execute-o como:ImageArchiveKeywordAudit.exe "C:\Images" "C:\keywords.txt"
Passo 5 – Programação de Auditorias Recorrentes (Windows Task Scheduler)
Utilização schtasks
Todos os dias às 2h:
schtasks /Create /TN "ImageKeywordAudit" /TR "\"C:\Path\To\ImageArchiveKeywordAudit\bin\Release\net8.0\ImageArchiveKeywordAudit.exe\"" /SC DAILY /ST 02:00
Log output para arquivo por inserir o comando em um .cmd
que redireciona stdout/stderr:ImageArchiveKeywordAudit.exe >> C:\Path\To\Logs\audit-%DATE%.log 2>&1
Melhores Práticas
- Mantenha uma fonte de palavra-chave canônica. Mante a sua lista em Git ou um CMDB; revisão trimestral.
- Normalize o texto OCR. Trim espaço branco, hyphens unify e look-alikes Unicode antes de se ajustar.
- Tune performance. Batch por folhas; adicione paralelismo somente após medir I/O e CPU.
- Qualidade em, qualidade fora. Escaneamento limpo (descoque/denoise) melhora significativamente as taxas de jogo.
- Audit scope. Considere conjuntos de palavras-chave separados por coleção (por exemplo, “landescape”, “produto” e “formas”).
- Traceabilidade. Mantenha relatórios CSV com timestamps para mudar a história e difingir rapidamente.
Troubleshooting
- ** Output OCR vazio:** Verifique a orientação da imagem e o contraste; tente outro formato (
*.png
,*.tif
). - Negatividade falsa: Adicione variantes ou sinônimos plural/stem para a sua lista (por exemplo, “beaches”, “biches”).
- ** Problemas de trânsito:** Limite as corridas concorrentes; evite escanear as ações da rede sobre links lentos.