C# - Opencv应用(3) 之矩阵Mat使用[图像截取粘贴、ROI操作、位运算、数学计算]
- 图像读取,大小、截取、位运算
- 图像ROI操作:粘贴+赋值、滤波
- 图像数学计算
- 部分结果如下:
1.图像读取,大小、截取、位运算
private static void showImg(string w_name,Mat img,int flg=0)
{
Cv2.NamedWindow(w_name, 0);
Cv2.ImShow(w_name, img);
Cv2.WaitKey(flg);
}
private static void SubMat()
{
var src = Cv2.ImRead("./images/Lenna.png");
if(src.Empty())
{
Console.WriteLine("请检查图像输入!\n");
}
else
{
Console.WriteLine("读取图像大小:[" + src.Rows + "," + src.Cols + "]");
}
showImg("src", src);
var small = new Mat();
Cv2.Resize(src, small, new Size(100, 100));
src[10, 110, 10, 110] = small;
showImg("src1", src);
src[370, 470, 400, 500] = small.T();
showImg("src2", src);
Mat part = src[200, 400, 200, 360];
Cv2.BitwiseNot(part, part);
part = src.SubMat(50, 100, 400, 450);
part.SetTo(128);
using (new Window("SubMat", src))
{
Cv2.WaitKey();
}
part.Dispose();
}
2. 图像ROI操作:粘贴+赋值、滤波
- 针对不同范围的区域即ROI进行不同的操作,根本上是像素/灰度值的改变
private void RowColRangeOperation()
{
using var src = Cv2.ImRead(ImagePath.Lenna);
Cv2.GaussianBlur(
src.RowRange(100, 200),
src.RowRange(200, 300),
new Size(7, 7), 20);
Cv2.GaussianBlur(
src.ColRange(200, 300),
src.ColRange(100, 200),
new Size(7, 7), 20);
using (new Window("RowColRangeOperation", src))
{
Cv2.WaitKey();
}
}
private void RowColOperation()
{
using var src = Cv2.ImRead(ImagePath.Lenna);
var rand = new Random();
for (int i = 0; i < 200; i++)
{
int c1 = rand.Next(100, 400);
int c2 = rand.Next(100, 400);
using Mat temp = src.Row(c1).Clone();
src.Row(c2).CopyTo(src.Row(c1));
temp.CopyTo(src.Row(c2));
}
((Mat)~src.ColRange(450, 500)).CopyTo(src.ColRange(0, 50));
src.RowRange(450, 460).SetTo(new Scalar(0, 0, 255));
using (new Window("RowColOperation", src))
{
Cv2.WaitKey();
}
}
3.图像数学计算
private static void ByMat()
{
double[,] av = {{1, 1},
{2, 3}};
double[] yv = { 10, 26 };
var a = new Mat(2, 2, MatType.CV_64FC1, av);
var y = new Mat(2, 1, MatType.CV_64FC1, yv);
var x = new Mat();
Cv2.Solve(a, y, x, DecompTypes.LU);
Console.WriteLine("ByMat:");
Console.WriteLine("X1 = {0}, X2 = {1}", x.At<double>(0), x.At<double>(1));
}
private static void ByNormalArray()
{
double[,] a = {{1, 1},
{2, 3}};
double[] y = { 10, 26 };
var x = new System.Collections.Generic.List<double>();
Cv2.Solve(
InputArray.Create(a), InputArray.Create(y),
OutputArray.Create(x),
DecompTypes.LU);
Console.WriteLine("ByNormalArray:");
Console.WriteLine("X1 = {0}, X2 = {1}", x[0], x[1]);
}
![C# - Opencv应用(3) 之矩阵Mat使用[图像截取粘贴、ROI操作、位运算、数学计算]_第1张图片](http://img.e-com-net.com/image/info8/e998d5e4124249a58e71f5143d7fedad.jpg)
完整代码
using System;
using OpenCvSharp;
namespace SamplesCore
{
class MatOperations
{
static void Main(string[] args)
{
ByMat();
ByNormalArray();
SubMat();
RowColRangeOperation();
RowColOperation();
return;
}
}
}