opencvsharp读取文件夹图片,并将图片的地址保存在一个string[]数组里
时间: 2024-09-06 17:01:53 浏览: 81
在使用OpenCVSharp库读取文件夹中的图片并将它们的路径存储到String数组中,你需要遵循以下步骤:
首先,确保你已经安装了OpenCVSharp库,可以使用NuGet包管理器添加。
1. 引入必要的命名空间:
```csharp
using OpenCvSharp;
using System.IO;
using System.Collections.Generic;
```
2. 定义一个函数来遍历文件夹并收集图片路径:
```csharp
public static string[] GetImagePaths(string folderPath)
{
List<string> imagePaths = new List<string>();
if (!Directory.Exists(folderPath))
{
Console.WriteLine($"The folder path {folderPath} does not exist.");
return imagePaths; // 返回空数组或抛出异常
}
foreach (string filePath in Directory.GetFiles(folderPath, "*.jpg", SearchOption.AllDirectories))
{
// 只考虑.jpg格式的图片,你可以根据需要调整这里
if (System.IO.Path.GetExtension(filePath) == ".jpg")
imagePaths.Add(filePath);
}
return imagePaths.ToArray(); // 转换为数组返回
}
```
在这个函数中,`Directory.GetFiles`用于获取指定文件夹下的所有`.jpg`文件,然后将路径添加到`List<string>`中。最后,我们将其转换回字符串数组返回。
使用这个函数的方式如下:
```csharp
string folderPath = "your_folder_path";
string[] imageFiles = GetImagePaths(folderPath);
foreach (string imagePath in imageFiles)
{
Console.WriteLine(imagePath); // 打印每张图片的路径
}
```
阅读全文
相关推荐
















