使用 C# 执行反向图像搜索可让开发人员根据视觉内容(而非关键字或元数据)高效地在集合中查找相似图像。此功能在图像检索、内容管理系统和数字资产管理等应用程序中特别有用。通过使用 GroupDocs.Search,C# 开发人员可以实现反向图像搜索功能,以快速识别与给定参考相匹配的图像。在本文中,我们将探讨如何使用 C# 执行反向图像搜索并提供代码示例来帮助您入门。此功能在处理各种图像格式(例如 PNG、JPEG 或 ZIP 存档)时特别有用,可确保跨不同平台和文件类型的兼容性。
使用 C# 执行反向图像搜索的步骤
- 将 GroupDocs.Search for .NET 库添加到您的项目中以进行反向图像搜索
- 使用指定的索引文件夹创建 Index 对象
- 设置图像 IndexingOptions 以启用容器项目图像、嵌入图像和单独图像的索引
- 使用指定的图像索引选项将文档添加到索引文件夹
- 设置 ImageSearchOptions 包括哈希差异、最大结果数和搜索文档过滤器
- 使用 SearchImage.Create 方法指定图像文件的路径,为搜索创建参考图像
- 使用参考图像在索引中执行图像搜索,并使用 Index.Search 的搜索选项
- 循环搜索结果并打印每个找到的图像的详细信息
要执行此功能,首先要设置一个索引,该索引存储图像及其元数据。IndexingOptions 类用于为不同类型的图像启用索引,包括容器项图像、嵌入图像和单独图像。索引图像后,可以使用 SearchImage 类执行搜索,该类允许指定参考图像以在索引文档中查找相似的匹配项。ImageSearchOptions 为搜索过程提供额外的控制,例如最大结果数和要搜索的文档类型。这种方法使得在 C# 应用程序中执行高效的基于内容的图像检索成为可能。以下是 用于反向图像搜索的 C# 代码。
使用 C# 执行反向图像搜索的代码
using GroupDocs.Search; | |
using GroupDocs.Search.Common; | |
using GroupDocs.Search.Options; | |
using GroupDocs.Search.Results; | |
using System; | |
namespace PerformReverseImageSearchUsingCSharp | |
{ | |
internal class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Apply the license to remove the restrictions | |
// imposed by the Search library | |
License lic = new License(); | |
lic.SetLicense(@"GroupDocs.Search.lic"); | |
string indexFolder = @"d:\MyIndex\"; | |
string documentsFolder = @"d:\MyDocuments\"; | |
// Creating an index in the specified folder | |
Index index = new Index(indexFolder); | |
// Setting the image indexing options | |
IndexingOptions indexingOptions = new IndexingOptions(); | |
indexingOptions.ImageIndexingOptions.EnabledForContainerItemImages = true; | |
indexingOptions.ImageIndexingOptions.EnabledForEmbeddedImages = true; | |
indexingOptions.ImageIndexingOptions.EnabledForSeparateImages = true; | |
// Indexing documents in a document folder | |
index.Add(documentsFolder, indexingOptions); | |
// Setting the image search options | |
ImageSearchOptions imageSearchOptions = new ImageSearchOptions(); | |
imageSearchOptions.HashDifferences = 10; | |
imageSearchOptions.MaxResultCount = 100; | |
imageSearchOptions.SearchDocumentFilter = SearchDocumentFilter | |
.CreateFileExtension(".zip", ".png", ".jpg"); | |
// Creating a reference image for search | |
SearchImage searchImage = SearchImage.Create(@"d:\MyDocuments\image.png"); | |
// Searching in the index | |
ImageSearchResult result = index.Search(searchImage, imageSearchOptions); | |
Console.WriteLine("Images found: " + result.ImageCount); | |
for (int i = 0; i < result.ImageCount; i++) | |
{ | |
FoundImageFrame image = result.GetFoundImage(i); | |
Console.WriteLine(image.DocumentInfo.ToString()); | |
} | |
} | |
} | |
} |
使用 C# 执行基于内容的图像检索是一项强大的基于内容的图像检索功能,它允许应用程序在各种环境中快速准确地找到相似的图像,从桌面应用程序到基于云的解决方案。用于图像索引和搜索的搜索库的集成确保该解决方案独立于平台,与 Windows、macOS 和 Linux 兼容,并且可以扩展以处理大量图像数据集。通过利用这些功能,开发人员可以创建强大的图像搜索系统,以增强用户体验并简化跨不同平台和应用程序的内容管理任务。
之前,我们提供了使用 C# 执行正则表达式搜索的详细指南。要查看完整的分步说明,请务必阅读有关如何执行 使用 C# 的正则表达式搜索 的详细文章。