C#+OpenCV基础(一)_加载创建复制保存图片
1、加载
(1)加载彩图
/// <summary>
/// 加载图片
/// ImreadModes.AnyColor:任意图像
/// ImreadModes.Color:三通道
/// ImreadModes.Grayscale:灰度图
/// </summary>
/// <param name="imgPath">图片路径</param>
public static Mat LoadImg(string imgPath, ImreadModes mode = ImreadModes.AnyColor)
{
return new Mat(imgPath, mode);
}
(2)加载灰度图
/// <summary>
/// 加载图片 - 灰度图片
/// </summary>
/// <param name="imgPath">图片路径</param>
public static Mat LoadImg_GRAY(string imgPath)
{
return new Mat(imgPath, ImreadModes.Grayscale);
}
2、创建
(1)常见方式
Mat mat1 = new Mat();
Mat mat1 = new Mat(width, height, MatType.CV_8UC1); // 宽,高,样式
(2)创建全零矩阵
Mat mat2=Mat.Zeros(mat1.Size(), mat1.Type());
(3)创建全1矩阵
Mat kernel = Mat.Ones(10, 10, MatType.CV_8UC1);
(4)创建一张纯色或雪花图片
/// <summary>
/// 创建一张图片
/// 纯色、随机雪花
/// </summary>
/// <param name="w">宽</param>
/// <param name="h">高</param>
/// <param name="isSolidColor">是否是纯色;true=纯色,false=随机雪花</param>
/// <param name="scalar">纯色时的颜色;Scalar.White 或Scalar.FromVec3b(new Vec3b() { Item0=0,Item1=0,Item2=0})</param>
/// <returns></returns>
public static Mat CreateImg(int width, int height, bool isSolidColor, Scalar scalar)
{
if (isSolidColor)
{
Mat mat = new Mat(width, height, MatType.CV_8UC1, scalar); //
return mat;
}
else
{
Mat mat = new Mat(width, height, MatType.CV_8UC1); //
Random random = new Random();
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
byte blue = (byte)(random.NextDouble() * 256);
byte green = (byte)(random.NextDouble() * 256);
byte red = (byte)(random.NextDouble() * 256);
Vec3b color = new Vec3b(blue, green, red);
mat.At<Vec3b>(i, j) = color;
}
}
return mat;
}
}
3、复制(深复制)
Mat dstMat = new Mat();
mat.CopyTo(dstMat); // 图像mat深层复制给图像dstMat
4、保存
/// <summary>
/// 保存图片
/// </summary>
/// <param name="imgPath">图片路径</param>
public static bool SaveImg(Mat mat, string imgPath)
{
return mat.SaveImage(imgPath);
}
本文来自博客园,作者:꧁执笔小白꧂,转载请注明原文链接:https://www.cnblogs.com/qq2806933146xiaobai/p/18294219