opencvsharp物料分拣示例代码
时间: 2023-08-27 18:07:07 浏览: 76
Opencvsharp示例代码
3星 · 编辑精心推荐
以下是使用OpenCvSharp进行物料分拣的示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;
namespace MaterialSorting
{
class Program
{
static void Main(string[] args)
{
// Load the image
Mat src = Cv2.ImRead("input.jpg");
// Convert to grayscale
Mat gray = new Mat();
Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);
// Threshold the image
Mat thresh = new Mat();
Cv2.Threshold(gray, thresh, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
// Find contours
Point[][] contours;
HierarchyIndex[] hierarchy;
Cv2.FindContours(thresh, out contours, out hierarchy, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);
// Loop through each contour
for (int i = 0; i < contours.Length; i++)
{
// Get bounding rectangle
Rect rect = Cv2.BoundingRect(contours[i]);
// Draw rectangle on the original image
Cv2.Rectangle(src, rect, new Scalar(0, 255, 0), 2);
// Calculate aspect ratio
double aspectRatio = (double)rect.Width / rect.Height;
// Determine if it is a square or a rectangle
if (aspectRatio >= 0.9 && aspectRatio <= 1.1)
{
// Square
Cv2.PutText(src, "Square", new Point(rect.X, rect.Y - 10), HersheyFonts.HersheyPlain, 1, new Scalar(0, 255, 0), 2);
}
else
{
// Rectangle
Cv2.PutText(src, "Rectangle", new Point(rect.X, rect.Y - 10), HersheyFonts.HersheyPlain, 1, new Scalar(0, 255, 0), 2);
}
}
// Save the output image
Cv2.ImWrite("output.jpg", src);
}
}
}
```
该代码首先加载输入图像,然后将其转换为灰度图像并进行阈值处理。接下来,使用FindContours方法查找轮廓,并通过循环遍历每个轮廓来找到包围矩形和它的宽高比,以确定它是正方形还是矩形。最后,将包围矩形和文本绘制在原始图像上,并将结果保存为输出图像。
阅读全文