零件分类——c#

using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.GraphicsInterface;
using IFoxCAD.Cad;
using System.Globalization;
using System.Security.Cryptography;
using System.Windows.Forms;
using System.Windows.Markup;
using Path = System.IO.Path;
namespace IfoxDemo
{
    public class 零件()
    {
        [CommandMethod("xx")]
        public void 零件分类()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            var curs = Z.PickList<Curve>(true);
            if (curs.Count ==0) return;
            List<小线线> 小线线集合 = new List<小线线>();
            curs.ForEach(x => 小线线集合.Add(new 小线线(x)));
            小线线集合.Sort((x1, x2) => { 
                double len1 = x1.GetLength();
                double len2 = x2.GetLength();
                return  (len2.CompareTo(len1)); //降序
            });
            //循环遍历线,找出上级和下级关系
            for (int i = 0; i < 小线线集合.Count; i++)
            {
                //第一层循环只遍历闭合的线,不闭合的线不需要遍历了,肯定不是最上级
                if (!小线线集合[i].closed) continue;
                //有上级了就不用比较了,已经找分组归属了,不需要知道下级是谁。
                if (小线线集合[i].上级.Count > 0) continue;
                for ( int j = i+1; j < 小线线集合.Count; j++)
                {
                    //如果包围盒没交集,就不需要比较了
                    if (!小线线集合[i].cur.GeometricExtents.Extents3dHit(小线线集合[j].cur.GeometricExtents)) continue;
                    //判断线完全在曲线内
                    var a = 小线线集合[j].cur.MiddlePoint().Point3dInCurveRayway(小线线集合[i].cur);
                    var b = 小线线集合[j].cur.StartPoint.Point3dInCurveRayway(小线线集合[i].cur);
                    if ( a || b  )//因为图有问题,有一个点在就算
                        //if (小线线集合[j].cur.线完全在曲线内射线法3个点(小线线集合[i].cur))
                    {
                        小线线集合[i].下级.Add(小线线集合[j]);
                        小线线集合[j].上级.Add(小线线集合[i]);
                    }
                }
            }
            //找到每组的老大(最上级),改颜色,或其他操作
            var 老大们 = 小线线集合.Where(x => x.上级.Count == 0).ToList();
            int count = 0;
             List<Curve> 一组curve = new List<Curve>();
            foreach (var 老大 in 老大们)
            {
                一组curve.Add(老大.cur);
                var colorindex = (count + 1) % 7;
                老大.cur.ColorIndex = colorindex;
                //老大.cur.Color = ColorName.RandColor;
                //老大.cur.LineWeight = LineWeight.LineWeight050;
                //老大.cur.Layer = "0";
                foreach (var item in 老大.下级)
                {
                    item.cur.ColorIndex = 老大.cur.ColorIndex;
                   // item.cur.ColorIndex = count;
                    一组curve.Add(item.cur);
                }
                count++;
                Z.eAddtoMS(一组curve);
               // db.AddEntityToModeSpace(一组curve.ToArray() );
                一组curve.Clear();
            }
        }
    }
    public class  小线线
    {
        public Curve cur;
        public bool closed;
        public double GetLength(){return cur.GetLength(); }
        public List<小线线> 上级 = new List<小线线>();
        public List<小线线> 下级 = new List<小线线>();
        public 小线线(Curve cur)
        {
           this.cur = cur;
           this.closed = cur.Closed||cur.StartPoint.isEqualspt(cur.EndPoint);
        }
    }
}

public static bool 包围盒包含或相交(this Extents3d ext1, Extents3d ext2)
{
    return
     ext1.MaxPoint.X >= ext2.MinPoint.X &&
     ext1.MinPoint.X <= ext2.MaxPoint.X &&
     ext1.MaxPoint.Y >= ext2.MinPoint.Y &&
     ext1.MinPoint.Y <= ext2.MaxPoint.Y ||
     ext2.MaxPoint.X >= ext1.MinPoint.X &&
     ext2.MinPoint.X <= ext1.MaxPoint.X &&
     ext2.MaxPoint.Y >= ext1.MinPoint.Y &&
     ext2.MinPoint.Y <= ext1.MaxPoint.Y;
}

<think>我们正在使用OpenCvSharp库进行Blob分析。在OpenCV中,Blob检测通常使用`SimpleBlobDetector`类。以下步骤将展示如何在C#中使用OpenCvSharp实现Blob检测。 步骤: 1. 创建`SimpleBlobDetector`参数对象并设置相关参数(如阈值、面积、圆形度、凸性、惯性比等)。 2. 根据参数创建`SimpleBlobDetector`对象。 3. 读取图像并转换为合适的格式(通常转换为灰度图像)。 4. 使用`Detect`方法检测Blob。 5. 在图像上绘制检测到的Blob(例如,绘制关键点)。 6. 显示结果。 示例代码: ```csharp using OpenCvSharp; using System; namespace BlobDetectionExample { class Program { static void Main(string[] args) { // 读取图像 using (Mat image = Cv2.ImRead("blob.jpg", ImreadModes.Color)) { if (image.Empty()) { Console.WriteLine("Could not open or find the image!"); return; } // 转换为灰度图像 Mat grayImage = new Mat(); Cv2.CvtColor(image, grayImage, ColorConversionCodes.BGR2GRAY); // 设置SimpleBlobDetector参数 SimpleBlobDetector.Params parameters = new SimpleBlobDetector.Params(); // 调整阈值:例如,阈值从50到220,步长为10 parameters.MinThreshold = 50; parameters.MaxThreshold = 220; parameters.ThresholdStep = 10; // 按面积过滤 parameters.FilterByArea = true; parameters.MinArea = 100; // 最小面积(像素) parameters.MaxArea = 10000; // 最大面积 // 按圆形度过滤(圆形的程度) parameters.FilterByCircularity = true; parameters.MinCircularity = 0.7f; // 圆形度最小值 // 按凸性过滤(斑点是否凸出) parameters.FilterByConvexity = true; parameters.MinConvexity = 0.8f; // 凸性最小值 // 按惯性比过滤(衡量形状的伸长程度,圆形的惯性比接近1,细长的接近0) parameters.FilterByInertia = true; parameters.MinInertiaRatio = 0.01f; // 创建SimpleBlobDetector using (SimpleBlobDetector detector = SimpleBlobDetector.Create(parameters)) { // 检测Blob KeyPoint[] keypoints = detector.Detect(grayImage); // 在图像上绘制检测到的Blob Mat resultImage = new Mat(); Cv2.DrawKeypoints(image, keypoints, resultImage, Scalar.Red, DrawMatchesFlags.DrawRichKeypoints); // 显示原始图像和检测结果 Cv2.ImShow("Original Image", image); Cv2.ImShow("Blob Detection", resultImage); Cv2.WaitKey(0); } // 释放资源 grayImage.Dispose(); } } } } ``` 说明: - `SimpleBlobDetector.Params`用于设置检测参数,可以根据需要调整。 - 通过设置不同的过滤条件(如面积、圆形度、凸性、惯性比等)来筛选出感兴趣的Blob。 - `Detect`方法返回一个`KeyPoint`数组,每个`KeyPoint`代表检测到的一个Blob。 - 使用`DrawKeypoints`方法将检测到的Blob绘制在原图上。 注意事项: - 图像路径需要正确(示例中为"blob.jpg")。 - 参数设置对检测结果影响很大,需要根据实际图像调整。 相关问题: 1. 如何调整SimpleBlobDetector的参数以优化Blob检测? 2. 如何过滤掉不需要的Blob(例如按大小或形状)? 3. 除了SimpleBlobDetector,OpenCVSharp中还有哪些Blob检测方法? 4. 如何将检测到的Blob保存到文件? </think>### C#基于OpenCvSharp实现Blob分析的方法 在OpenCvSharp中进行Blob(斑点)分析主要通过`SimpleBlobDetector`类实现,以下是完整的实现步骤和代码示例: #### 📌 实现步骤 1. **参数配置**:设置Blob检测的过滤条件(如面积、圆形度等) 2. **创建检测器**:实例化`SimpleBlobDetector` 3. **图像预处理**:转换为灰度图并进行二值化 4. **斑点检测**:调用`Detect`方法获取关键点集合 5. **结果绘制**:在原图上标记检测到的斑点 #### 💻 完整代码示例 ```csharp using OpenCvSharp; using System; using System.Collections.Generic; class BlobDetection { static void Main() { // 1. 读取图像 using Mat image = Cv2.ImRead("blob_sample.jpg", ImreadModes.Color); if (image.Empty()) throw new Exception("图像加载失败"); // 2. 转换为灰度图 using Mat gray = new Mat(); Cv2.CvtColor(image, gray, ColorConversionCodes.BGR2GRAY); // 3. 配置Blob检测参数 var blobParams = new SimpleBlobDetector.Params { // 阈值设置 MinThreshold = 50, MaxThreshold = 220, ThresholdStep = 10, // 面积过滤(像素) FilterByArea = true, MinArea = 100, MaxArea = 5000, // 圆形度过滤 (1=正圆) FilterByCircularity = true, MinCircularity = 0.7f, // 凸性过滤 FilterByConvexity = true, MinConvexity = 0.8f, // 惯性比过滤(椭圆度) FilterByInertia = true, MinInertiaRatio = 0.01f }; // 4. 创建检测器并执行斑点检测 using var detector = SimpleBlobDetector.Create(blobParams); KeyPoint[] keyPoints = detector.Detect(gray); Console.WriteLine($"检测到斑点数量: {keyPoints.Length}"); // 5. 在原始图像绘制结果 var resultImage = image.Clone(); Cv2.DrawKeypoints( image: image, keypoints: keyPoints, outImage: resultImage, color: Scalar.Red, flags: DrawMatchesFlags.DrawRichKeypoints ); // 6. 显示结果 Cv2.ImShow("Blob检测结果", resultImage); Cv2.WaitKey(0); Cv2.DestroyAllWindows(); } } ``` #### ⚙ 关键参数说明 | 参数类型 | 属性 | 作用 | |---------|------|------| | **阈值** | `MinThreshold/MaxThreshold` | 控制斑点亮度范围 | | **面积过滤** | `MinArea/MaxArea` | 过滤过大/过小斑点 | | **形状过滤** | `MinCircularity` | 筛选接近圆形的斑点 | | **凸性过滤** | `MinConvexity` | 排除凹形或不规则斑点 | | **惯性比** | `MinInertiaRatio` | 控制斑点的椭圆度 | #### 💡 使用建议 1. 预处理时建议先进行`高斯模糊`减少噪声: ```csharp Cv2.GaussianBlur(gray, gray, new Size(5, 5), 0); ``` 2. 对于暗背景亮斑点场景,可使用`反转二值化`: ```csharp Cv2.Threshold(gray, gray, 128, 255, ThresholdTypes.BinaryInv); ``` 3. 检测工业零件时,合理设置`MinArea`可有效过滤噪点 > 💡 **技巧**:调用`Cv2.GetStructuringElement`创建形态学结构元素,通过开运算(`MorphologyEx`)进一步优化斑点形状[^4] #### 🌐 典型应用场景 1. 工业零件尺寸检测 2. 生物细胞计数 3. 机器人视觉定位 4. 材料表面缺陷分析 --- ### 📚 相关问题 1. 如何优化Blob检测在不同光照条件下的稳定性? 2. 怎样区分重叠斑点和单个大斑点? 3. Blob检测与轮廓检测有何本质区别? 4. 在实时视频流中如何实现高效的Blob跟踪? 5. OpenCvSharp中除`SimpleBlobDetector`外还有哪些斑点检测算法?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山水CAD插件定制

你的鼓励是我创作最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值