C#使用OpenCv图像批处理并改变图片大小并且重命名
添加NuGet包
选择最新版就好了
安装完成后右键项目重新生成方案
使用OpenCvSharp.CPlusPlus命名空间
using OpenCvSharp.CPlusPlus;
写一个函数用来改变图片大小并且重新命名
read_path是存储图片的文件夹的路径,write_path是改变后图片存储的文件夹路径,filename是图片重命名,width和height分别为图片修改后的宽和高
public static void ResizeImg(String read_path,String write_path,String filename,double width,double height) {
Mat img1 = new Mat(read_path);
Mat img2 = img1;
OpenCvSharp.CPlusPlus.Size size = new OpenCvSharp.CPlusPlus.Size(width, height);
Cv2.Resize(img1, img2, size, 0, 0);
Cv2.ImWrite(write_path+"\\"+ filename, img2);
}
在Main函数中使用该函数
static void Main(string[] args)
{
string dir_path = @"G:\TestImg";//读取路径
String write_path = "G:\\TestImg2";//存储路径
String[] filenames=Directory.GetFiles(dir_path);
for (int i = 0; i < filenames.Length; i++) {
ResizeImg(filenames[i], write_path, i + ".png", 200, 300);
}
Console.ReadKey();
}
运行结果
完整代码
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;
using OpenCvSharp.CPlusPlus;
using System.Runtime.InteropServices;
using System.IO;
namespace ResizeTest
{
class Program
{
static void Main(string[] args)
{
string dir_path = @"G:\TestImg";//读取路径
String write_path = "G:\\TestImg2";//存储路径
String[] filenames=Directory.GetFiles(dir_path);
for (int i = 0; i < filenames.Length; i++) {
ResizeImg(filenames[i], write_path, i + ".png", 200, 300);
}
Console.ReadKey();
}
public static void ResizeImg(String read_path,String write_path,String filename,double width,double height) {
Mat img1 = new Mat(read_path);
Mat img2 = img1;
OpenCvSharp.CPlusPlus.Size size = new OpenCvSharp.CPlusPlus.Size(width, height);
Cv2.Resize(img1, img2, size, 0, 0);
Cv2.ImWrite(write_path+"\\"+ filename, img2);
}
}
}
以上是 C#使用OpenCv图像批处理并改变图片大小并且重命名 的全部内容, 来源链接: utcz.com/z/356208.html