You need to enable JavaScript to run this app. 在Opencvsharp中如何将提取到的Mat Contours转换为Bitmap?
优惠活动
大模型
产品
解决方案
定价
更多

在Opencvsharp中如何将提取到的Mat Contours转换为Bitmap?

OpenCvSharp轮廓转Bitmap报错解决方案

错误原因

  • FindContours()返回的contoursQuery数组中每个Mat是存储轮廓坐标点的2通道结构,不属于可直接转Bitmap的1/3/4通道图像类Mat,通道数不符合要求触发报错
  • 循环判断条件i <= contoursQuery.Length存在数组越界风险,需调整为i < contoursQuery.Length
  • 原代码中images.add、toBitmap写法不符合C#大小写规范,正确应为Add、ToBitmap

修复思路

需要先把每个轮廓单独绘制到空白图像画布上,再将画布转为Bitmap,不能直接转换轮廓点存储Mat。

修复后代码

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog getImag = new OpenFileDialog();
    getImag.Filter = "PNG,JPG|*.png;*.jpg";

    DialogResult result = getImag.ShowDialog();
    string Source_Logo_Link = string.Empty;

    if (result == DialogResult.OK)
    {
        Source_Logo_Link = getImag.FileName;
        Mat src = new OpenCvSharp.Mat(Source_Logo_Link);
        Mat gray = src.CvtColor(ColorConversionCodes.BGR2GRAY);
        Mat binary = gray.Threshold(0, 255, ThresholdTypes.Otsu);
        
        Mat[] contoursQuery;
        OutputArray hierarchyQ = InputOutputArray.Create(new List<Vec4i>());
        binary.FindContours(out contoursQuery, hierarchyQ, RetrievalModes.CComp, ContourApproximationModes.ApproxTC89KCOS);

        List<Bitmap> images = new List<Bitmap>();
        for (int i = 0; i < contoursQuery.Length; i++)
        {
            // 创建和原图大小一致的单通道空白画布,背景为黑
            Mat contourCanvas = Mat.Zeros(binary.Size(), MatType.CV_8UC1);
            // 绘制当前轮廓到画布,最后参数-1为填充轮廓,改为正数则是描边粗细
            Cv2.DrawContours(contourCanvas, contoursQuery, i, Scalar.White, -1);
            // 绘制完成后再转Bitmap
            images.Add(contourCanvas.ToBitmap());
            // 释放临时Mat资源避免内存泄漏
            contourCanvas.Dispose();
        }
        
        // 释放OpenCV相关资源
        src.Dispose();
        gray.Dispose();
        binary.Dispose();
        hierarchyQ.Dispose();
        foreach (var c in contoursQuery) c.Dispose();
    }    
}

内容的提问来源于stack exchange,提问作者Ammar albush

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 14:39:03