opencvsharp计算两个轮廓点集的交集
时间: 2023-06-22 12:41:36 浏览: 243
使用OpenCvSharp可以计算两个轮廓点集的交集,方法是先将两个轮廓点集转为轮廓,然后使用OpenCvSharp中的IntersectConvexConvex()方法计算它们的交集。示例代码如下:
```
using OpenCvSharp;
using System.Collections.Generic;
// 读取图像
Mat src1 = new Mat("image1.jpg", ImreadModes.Color);
Mat src2 = new Mat("image2.jpg", ImreadModes.Color);
// 灰度化
Mat gray1 = new Mat();
Mat gray2 = new Mat();
Cv2.CvtColor(src1, gray1, ColorConversionCodes.BGR2GRAY);
Cv2.CvtColor(src2, gray2, ColorConversionCodes.BGR2GRAY);
// 二值化
Mat binary1 = new Mat();
Mat binary2 = new Mat();
Cv2.Threshold(gray1, binary1, 0, 255, ThresholdTypes.Binary);
Cv2.Threshold(gray2, binary2, 0, 255, ThresholdTypes.Binary);
// 查找轮廓
List<Point[]> contours1 = new List<Point[]>();
Mat hierarchy1 = new Mat();
Cv2.FindContours(binary1, contours1, hierarchy1, RetrievalModes.List, ContourApproximationModes.ApproxSimple);
List<Point[]> contours2 = new List<Point[]>();
Mat hierarchy2 = new Mat();
Cv2.FindContours(binary2, contours2, hierarchy2, RetrievalModes.List, ContourApproximationModes.ApproxSimple);
// 将轮廓点集转为轮廓
List<Point> contour1 = new List<Point>();
foreach (Point[] points in contours1)
{
contour1.AddRange(points);
}
Point[] contourArray1 = contour1.ToArray();
Mat contourMat1 = new Mat(contourArray1.Length, 1, MatType.CV_32SC2, contourArray1);
List<Point> contour2 = new List<Point>();
foreach (Point[] points in contours2)
{
contour2.AddRange(points);
}
Point[] contourArray2 = contour2.ToArray();
Mat contourMat2 = new Mat(contourArray2.Length, 1, MatType.CV_32SC2, contourArray2);
// 计算交集
Mat intersection = new Mat();
Cv2.IntersectConvexConvex(contourMat1, contourMat2, intersection);
// 显示结果
Mat result = src1.Clone();
Cv2.DrawContours(result, new Point[][] { intersection.ToPointArray() }, -1, Scalar.Red, -1);
Cv2.ImShow("result", result);
Cv2.WaitKey(0);
Cv2.DestroyAllWindows();
```
其中,Cv2.IntersectConvexConvex()方法的第一个参数和第二个参数分别是两个轮廓,第三个参数是计算结果。计算结果是一个Mat类型的矩阵,需要将其转换为轮廓才能绘制。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)