当前位置 主页 > 网站技术 > 代码类 > 最大化 缩小

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

    栏目:代码类 时间:2020-02-05 15:13

    添加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);
        }
      }
    
      
    }

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持IIS7站长之家。

    下一篇:没有了