C# OpenCvSharp實現圖片批量改名
更新時間:2024年03月11日 17:05:16 作者:天天代碼碼天天
這篇文章主要為大家詳細介紹了C#如何結合OpenCvSharp實現圖片批量改名功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
效果




項目

代碼
using NLog;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace OpenCvSharp_Demo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
NLog.Windows.Forms.RichTextBoxTarget.ReInitializeAllTextboxes(this);
}
private static Logger _log = NLog.LogManager.GetCurrentClassLogger();
private void Form1_Load(object sender, EventArgs e)
{
}
string inPath = "";
string outPath = "";
DirectoryInfo folder;
List<FileInfo> files=new List<FileInfo>();
String[] imageExtensions = { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
/// <summary>
/// 選擇文件夾
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
inPath = "";
outPath = "";
files.Clear();
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.Description = "請選擇文件路徑";
if (dialog.ShowDialog() == DialogResult.OK)
{
inPath = dialog.SelectedPath;
textBox1.Text = inPath;
outPath = inPath + "\\out";
textBox2.Text = outPath;
_log.Info("圖片路徑:" + inPath);
_log.Info("保存路徑:" + outPath);
folder = new DirectoryInfo(inPath);
var temp = folder.GetFiles("*.*", SearchOption.TopDirectoryOnly);
foreach (FileInfo file in temp)
{
if (imageExtensions.Contains(file.Extension.ToLower()))
{
files.Add(file);
}
}
_log.Info("一共["+ files .Count()+ "]張圖片");
}
}
/// <summary>
/// 修改名稱
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
if (files.Count()==0)
{
return;
}
outPath = textBox2.Text;
//目錄不存在 則創(chuàng)建
if (!Directory.Exists(outPath))
{
DirectoryInfo directoryInfo = new DirectoryInfo(outPath);
//創(chuàng)建目錄
directoryInfo.Create();
}
else {
DirectoryInfo outFolder=new DirectoryInfo(outPath);
if (outFolder.GetFiles("*.*", SearchOption.AllDirectories).Length>0)
{
MessageBox.Show(outPath + "文件夾不為空,防止數據被覆蓋,請更換!");
return;
}
}
string oldName;
string newName;
Mat temp;
int index = 0;
foreach (FileInfo file in files)
{
oldName = file.Name;
newName = index.ToString() + file.Extension;
try
{
temp = new Mat(inPath + "\\" + oldName);
//其他處理 ,例如
//圖片縮放
//通道變換等
//……
Cv2.ImWrite(outPath + "\\" + newName, temp);
_log.Info(oldName + "-->" + newName);
index++;
}
catch (Exception ex)
{
_log.Info(oldName+"修改異常,異常信息:"+ex.Message);
}
}
_log.Info("全部修改完成!");
}
}
}到此這篇關于C# OpenCvSharp實現圖片批量改名的文章就介紹到這了,更多相關C# OpenCvSharp圖片改名內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Unity UGUI的GridLayoutGroup網格布局組件使用詳解
這篇文章主要介紹了Unity UGUI的GridLayoutGroup網格布局組件使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07
C#獲取機器碼的方法詳解(機器名,CPU編號,硬盤編號,網卡mac等)
這篇文章主要介紹了C#獲取機器碼的方法,結合實例形式詳細分析了C#獲取硬件機器名、CPU編號、硬盤編號、網卡mac等信息的相關實現方法,需要的朋友可以參考下2016-07-07

