Algorithm principle
Robert operator, also known as Roberts edge detection operator, is an operator that uses local difference operators to find edges. Robert operator is used to solve the gradient in the diagonal direction of the image to find edges, as shown below:
Gradient calculation:
Calculation illustration:
The first convolution calculation result of the pixel at (0, 0) is: |120×1+125×(-1)|=5
Algorithm implementation
Code implementation (pure algorithm):
if (fileDialog.ShowDialog() == DialogResult.OK)
{
picFile = fileDialog.FileName;
inputMat = Cv2.ImRead(picFile, ImreadModes.Grayscale);
outMat = new Mat(new Size(inputMat.Cols, inputMat.Rows), inputMat.Type());
for (int i = 0; i < inputMat.Rows - 1; i++)
{
for (int j = 0; j < inputMat.Cols - 1; j++)
{
var left_up = inputMat.Get<byte>(i, j);
var right_down= inputMat.Get<byte>(i+1, j+1);
var result = Math.Abs(left_up - right_down);
outMat.Set<byte>(i, j, OpenCvSharp.Internal.Util.SaturateCast.ToByte(result));
}
}
picBox_Display.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(inputMat);
picBox_After.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(outMat);
}
In the same way, define the following operator to retain the edge from the upper right to the lower left direction.
OpenCV API implementation
if (fileDialog.ShowDialog() == DialogResult.OK)
{
picFile = fileDialog.FileName;
inputMat = Cv2.ImRead(picFile, ImreadModes.Grayscale);
outMat = new Mat(new Size(inputMat.Cols, inputMat.Rows), inputMat.Type());
//左上到右下方向滤波器
InputArray kernel = InputArray.Create<int>(new int[2, 2] {
{
1, 0}, {
0, -1 } });
Cv2.Filter2D(inputMat, outMat, MatType.CV_16SC1, kernel);
//矩阵取绝对值
Cv2.ConvertScaleAbs(outMat, outMat);
picBox_Display.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(inputMat);
picBox_After.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(outMat);
}
Additional instructions:
- The OpenCV library used in this case in .NET is OpenCvSharp4
- The edge extraction of the entire image can be obtained by adding the pictures from the upper left to the lower right and the upper right to the lower left directions;