L’automazione degli audit delle parole chiave per gli archivi d’immagine assicura che i tuoi dati visivi siano coerentemente etichettati e facilmente scoperti. Aspose.OCR per .NET, puoi leggere il testo incorporato/visibile dalle immagini e validerlo contro un elenco controllato di parole principali - poi segnalare ciò che manca.
Esempio completo
Prerequisiti
- .NET 8 (o .NET 6+) SDK installato.
- NuGet accesso per installare
Aspose.OCR
. - Una cartella di immagini per l’audit (ad esempio,
C:\Path\To\ImageArchive
). - (Opzionale) Un file di licenza Aspose se si prevede di superare i limiti di valutazione.
Creare il progetto e aggiungere pacchetti
dotnet new console -n ImageArchiveKeywordAudit -f net8.0
cd ImageArchiveKeywordAudit
dotnet add package Aspose.OCR
Passo 1 - Preparare la tua lista di parole chiave
Decide le parole chiave canoniche che le tue immagini dovrebbero contenere. nel gist, le password sono hardcoded per semplicità:
// Exact shape used in the gist
List<string> keywords = new List<string>
{
"mountains", "beaches", "forests", "landscape"
};
** Tipo (opzionale): ** Conservare le parole chiave in keywords.txt
(una per linea) e caricare in List<string>
a tempo indeterminato per evitare le riproduzioni.
Passo 2 – Initializzare Aspose.OCR e Scanare l’archivio
Corrisponde al gesto: crea un motore OCR, elenca le immagini, ogni file oCR e verifica la presenza di parole chiave.
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 – Estendere l’audit (opzionale ma raccomandato)
Si può migliorare la segnalazione e il filtraggio mantenendo lo stesso nucleo OCR.
3.a Tipi di immagini multipli di 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 Scopri quali parole chiave corrispondono / mancano
// 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 Scrivere un rapporto 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 – Eseguire PowerShell o Batch
Creare un semplice 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"
Opzionale: Se si modifica il programma per accettare argomenti, eseguire come:ImageArchiveKeywordAudit.exe "C:\Images" "C:\keywords.txt"
Passo 5 – Programma di revisioni ripetute (Windows Task Scheduler)
Utilizzo schtasks
A partire dalle ore 2 del mattino:
schtasks /Create /TN "ImageKeywordAudit" /TR "\"C:\Path\To\ImageArchiveKeywordAudit\bin\Release\net8.0\ImageArchiveKeywordAudit.exe\"" /SC DAILY /ST 02:00
Scrivi una recensione per inserire il comando in un .cmd
che reindirizza stdout/stderr:ImageArchiveKeywordAudit.exe >> C:\Path\To\Logs\audit-%DATE%.log 2>&1
Migliori pratiche
- Mantenere una fonte canonica di parole chiave. Salva la tua lista in Git o in un CMDB; revisione trimestrale.
- Normalizza il testo OCR. Trim white space, unify hyphens e Unicode look-alikes prima di corrispondere.
- Tune performance. Batch per cartelle; aggiungere parallelismo solo dopo la misurazione I/O e CPU.
- Qualità in, qualità fuori. Le scansioni pulite (desk/denoise) migliorano notevolmente i tassi di match.
- Audit scope. Considerare separati set di parole chiave per collezione (ad esempio, “landescape”, “prodotto” e “formulari”).
- Traceability. Mantenere i rapporti CSV con timestamps per cambiare storia e diffondere rapidamente.
Troubleshooting
- Produzione OCR vuota: Verifica l’orientamento e il contrasto dell’immagine; prova un altro formato (
*.png
,*.tif
). - Negative false: Aggiungi varianti o sinonimi plurali/grandi alla tua lista (ad esempio, “beach”, “bache”).
- Problemi di trasmissione: Limitare i corsi concorrenti; evitare di scansionare le azioni di rete su collegamenti lenti.