C#使用OpenCv图像批处理并改变图片大小并且重命名

编辑: admin 分类: c#语言 发布时间: 2022-03-12 来源:互联网

添加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.T【本文由:专业的印度服务器 提供,感谢支持】ext;
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);
    }
  }

  
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持海外IDC网。