【opencvsharp】斑点检测 条码解码 图像操作 图像旋转/翻转/缩放 透视变换 图像显示控件 demo笔记

该博客展示了多种图像处理技术,包括斑点检测、条码解码、图像操作(如二值化、子区域、大小调整、放大缩小、对称、色彩空间转换)、直方图绘制以及透视和仿射变换。通过OpenCvSharp库实现,涵盖了图像识别和处理的多个关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//斑点检测
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;
using OpenCvSharp.Blob;

namespace KeyboardLabeling
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = new Mat("../../keyboard.png");
            Mat bin = new Mat();
            Mat binary = new Mat();

            src = src.SubMat(new Rect(300, 300, 1000, 1000)); //裁剪图像

            Cv2.CvtColor(src, bin, ColorConversionCodes.BGR2GRAY); // gray
            Cv2.Threshold(bin, binary, 125, 255, ThresholdTypes.BinaryInv); //二值化

            Mat result = new Mat(src.Size(), MatType.CV_8UC3);
            CvBlobs blobs = new CvBlobs();

            blobs.Label(binary);//斑点检测
            blobs.RenderBlobs(src, result);//渲染斑点

            int text = 1; //数字
            foreach (var item in blobs)
            {
                if (item.Value.Area > 40000) // 检查标签区域
                {
                    CvBlob b = item.Value;

                    Cv2.Circle(result, b.Contour.StartingPoint, 8, Scalar.Red, 2, LineTypes.AntiAlias);
                    Cv2.PutText(result, text.ToString(), new Point(b.Centroid.X, b.Centroid.Y),  //修改标签编号设置
                        HersheyFonts.HersheyComplex, 1, Scalar.Yellow, 2, LineTypes.AntiAlias);
                    text++;
                }
            }
            Cv2.Resize(src, src, new Size(416, 430));
            Cv2.Resize(binary, binary, new Size(416, 430));
            Cv2.Resize(result, result, new Size(416, 430));
            Cv2.ImShow("src", src);
            Cv2.ImShow("binary", binary);
            Cv2.ImShow("result", result);
            Cv2.WaitKey(0);

        }
    }
}

斑点检测 

条码解码: 

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;
using OpenCvSharp.Blob;
using ZXing;

namespace QRcodeApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = Cv2.ImRead("../../qrcode2.png");//读取二维码

            // create a barcode reader instance创建条形码阅读器实例
            var barcodeReader = new BarcodeReader();

            //创建内存位图  create an in memory bitmap
            var barcodeBitmap = (Bitmap)Bitmap.FromFile("../../qrcode2.png");

            //从内存位图中解码条形码 decode the barcode from the in memory bitmap
            var barcodeResult = barcodeReader.Decode(barcodeBitmap);

            //将结果输出到控制台 output results to consoles
            Console.WriteLine($"Decoded barcode text: {barcodeResult?.Text}");
            Console.WriteLine($"Barcode format: {barcodeResult?.BarcodeFormat}");


            Cv2.ImShow("src", src);

            Cv2.WaitKey(0);
            Cv2.DestroyAllWindows();

        }
    }
}

条码二维码解码2:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZXing;
using ZXing.Common;


namespace QRcodeApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public string decoded;
        
        private void button1_Click(object sender, EventArgs e)
        {
            pictureBox1.Image = Bitmap.FromFile("../../qrcode.png");//加载显示二维码图片
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

            BarcodeReader reader = new BarcodeReader(); 
            Result result = reader.Decode((Bitmap)pictureBox1.Image);//解码 二维码
            if (result != null)
            {
                decoded = "Decode : " + result.ToString() + "\r\n Type : " + result.BarcodeFormat.ToString();
                if (decoded != "")
                {
                    textBox1.Text = decoded;
                }
            }
            else 
                MessageBox.Show("没检测到条形码或二维码!");
        }
    }
}

图像处理:

// 图像操作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace ImagePreprocessing
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src1 = new Mat("../../opencv.png", ImreadModes.ReducedColor2);
            Mat src2 = src1.Flip(FlipMode.Y);

            Mat and = new Mat();
            Mat or = new Mat();
            Mat xor = new Mat();
            Mat not = new Mat();
            Mat compare = new Mat();

            Cv2.BitwiseAnd(src1, src2, and);
            Cv2.BitwiseOr(src1, src2, or);
            Cv2.BitwiseXor(src1, src2, xor);
            Cv2.BitwiseNot(src1, not);
            Cv2.Compare(src1, src2, compare, CmpTypes.EQ);

            Cv2.ImShow("and", and);
            Cv2.ImShow("or", or);
            Cv2.ImShow("xor", xor);
            Cv2.ImShow("not", not);
            Cv2.ImShow("compare", compare);
            Cv2.WaitKey(0);
        }
    }
}

// 图像操作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace ImagePreprocessing
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = new Mat("../../opencv.png", ImreadModes.ReducedColor2);
            Mat val = new Mat(src.Size(), MatType.CV_8UC3, new Scalar(0, 0, 30));

            Mat add = new Mat();
            Mat sub = new Mat();
            Mat mul = new Mat();
            Mat div = new Mat();
            Mat max = new Mat();
            Mat min = new Mat();
            Mat abs = new Mat();
            Mat absdiff = new Mat();

            Cv2.Add(src, val, add);
            Cv2.Subtract(src, val, sub);
            Cv2.Multiply(src, val, mul);
            Cv2.Divide(src, val, div);
            Cv2.Max(src, mul, max);
            Cv2.Min(src, mul, min);
            abs = Cv2.Abs(mul);
            Cv2.Absdiff(src, mul, absdiff);

            Cv2.ImShow("add", add);
            Cv2.ImShow("sub", sub);
            Cv2.ImShow("mul", mul);
            Cv2.ImShow("div", div);
            Cv2.ImShow("max", max);
            Cv2.ImShow("min", min);
            Cv2.ImShow("abs", abs);
            Cv2.ImShow("absdiff", absdiff);
            Cv2.WaitKey(0);
        }
    }
}

//二值化
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace ImagePreprocessing
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = new Mat("../../opencv.png");
            Mat gray = new Mat();
            Mat binary = new Mat();

            Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);
            Cv2.Threshold(gray, binary, 150, 255, ThresholdTypes.Binary);

            Cv2.ImShow("src", src);
            Cv2.ImShow("dst", binary);
            Cv2.WaitKey(0);
        }
    }
}


// 图像子区域
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace ImagePreprocessing
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = new Mat("../../opencv.png");
            Mat dst = src.SubMat(new Rect(100, 100, 100, 100));

            Cv2.ImShow("src", src);
            Cv2.ImShow("dst", dst);
            Cv2.WaitKey(0);
        }
    }
}

// 图像大小调整
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace ImagePreprocessing
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = new Mat("../../opencv.png");
            Mat dst = new Mat();

            Cv2.Resize(src, dst, new Size(500, 250));

            Cv2.ImShow("src", src);
            Cv2.ImShow("dst", dst);
            Cv2.WaitKey(0);
        }
    }
}

// 放大缩小
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace ImagePreprocessing
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = new Mat("../../opencv.png", ImreadModes.ReducedColor2);
            Mat pyrUp = new Mat();
            Mat pyrDown = new Mat();

            Cv2.PyrUp(src, pyrUp);
            Cv2.PyrDown(src, pyrDown);

            Cv2.ImShow("pyrUp", pyrUp);
            Cv2.ImShow("pyrDown", pyrDown);
            Cv2.WaitKey(0);
        }
    }
}


// 对称
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace ImagePreprocessing
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = Cv2.ImRead("../../opencv.png");
            Mat dst = new Mat(src.Size(), MatType.CV_8UC3);

            Cv2.Flip(src, dst, FlipMode.Y);

            Cv2.ImShow("dst", dst);
            Cv2.WaitKey(0);
            Cv2.DestroyAllWindows();
        }
    }
}

//色彩空间转换
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace ImagePreprocessing
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = Cv2.ImRead("../../opencv.png");
            Mat dst = new Mat(src.Size(), MatType.CV_8UC1);

            Cv2.CvtColor(src, dst, ColorConversionCodes.BGR2GRAY);

            Cv2.ImShow("dst", dst);
            Cv2.WaitKey(0);
            Cv2.DestroyAllWindows();
        }
    }
}

直方图:color  gray

// 直方图(color)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace Histogram
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = Cv2.ImRead("../../opencv.png");
            Mat color = new Mat();
            Mat histB = new Mat();
            Mat histG = new Mat();
            Mat histR = new Mat();
            Mat resultB = Mat.Ones(new Size(256, src.Height), MatType.CV_8UC3);
            Mat resultG = Mat.Ones(new Size(256, src.Height), MatType.CV_8UC3);
            Mat resultR = Mat.Ones(new Size(256, src.Height), MatType.CV_8UC3);

            Cv2.CvtColor(src, color, ColorConversionCodes.BGR2BGRA);

            Cv2.CalcHist(new Mat[] { color }, new int[] { 0 }, null, histB, 1, new int[] { 256 }, new Rangef[] { new Rangef(0, 256) });
            Cv2.Normalize(histB, histB, 0, 255, NormTypes.MinMax);

            Cv2.CalcHist(new Mat[] { color }, new int[] { 1 }, null, histG, 1, new int[] { 256 }, new Rangef[] { new Rangef(0, 256) });
            Cv2.Normalize(histG, histG, 0, 255, NormTypes.MinMax);

            Cv2.CalcHist(new Mat[] { color }, new int[] { 2 }, null, histR, 1, new int[] { 256 }, new Rangef[] { new Rangef(0, 256) });
            Cv2.Normalize(histR, histR, 0, 255, NormTypes.MinMax);

            for (int i = 0; i < histB.Rows; i++)
            {
                Cv2.Line(resultB, new Point(i, src.Height), new Point(i, src.Height - histB.Get<float>(i)), Scalar.Blue);
            }
            for (int i = 0; i < histG.Rows; i++)
            {
                Cv2.Line(resultG, new Point(i, src.Height), new Point(i, src.Height - histG.Get<float>(i)), Scalar.Green);
            }
            for (int i = 0; i < histR.Rows; i++)
            {
                Cv2.Line(resultR, new Point(i, src.Height), new Point(i, src.Height - histR.Get<float>(i)), Scalar.Red);
            }

            Cv2.ImShow("img", color);
            Cv2.ImShow("Blue", resultB);
            Cv2.ImShow("Green", resultG);
            Cv2.ImShow("Red", resultR);
            Cv2.WaitKey(0);
            Cv2.DestroyAllWindows();
        }
    }
}
// 直方图(gray)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace Histogram
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = Cv2.ImRead("../../opencv.png");
            Mat gray = new Mat();
            Mat hist = new Mat();
            Mat result = Mat.Ones(new Size(256, src.Height), MatType.CV_8UC1);
            Mat dst = new Mat();

            Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);
            Cv2.CalcHist(new Mat[] { gray }, new int[] { 0 }, null, hist, 1, new int[] { 256 }, new Rangef[] { new Rangef(0, 256) });
            Cv2.Normalize(hist, hist, 0, 255, NormTypes.MinMax);

            for (int i = 0; i < hist.Rows; i++)
            {
                Cv2.Line(result, new Point(i, src.Height), new Point(i, src.Height - hist.Get<float>(i)), Scalar.White);
            }

            Cv2.ImShow("img", gray);
            Cv2.ImShow("histogram", result);
            Cv2.WaitKey(0);
            Cv2.DestroyAllWindows();
        }
    }
}

显示图像:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine(Cv2.GetVersionString());

            Mat image = Cv2.ImRead("../../opencv.png");
            Cv2.ImShow("image", image);
            Cv2.WaitKey(0);
            Cv2.DestroyAllWindows();
        }
    }
}

透视变换:

//透视变换
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace Transformation
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = Cv2.ImRead("../../opencv.png");
            Mat dst = new Mat();

            List<Point2f> src_pts = new List<Point2f>()
            {
                new Point2f(0.0f, 0.0f),
                new Point2f(0.0f, src.Height),
                new Point2f(src.Width, src.Height),
                new Point2f(src.Width, 0.0f)
            };

            List<Point2f> dst_pts = new List<Point2f>()
            {
               new Point2f(50.0f, 50.0f),
               new Point2f(0.0f, src.Height),
               new Point2f(src.Width, src.Height),
               new Point2f(src.Width - 100.0f, 0.0f)
            };

            Mat matrix = Cv2.GetPerspectiveTransform(src_pts, dst_pts);
            Cv2.WarpPerspective(src, dst, matrix, new Size(src.Width, src.Height));

            Cv2.ImShow("src", src);
            Cv2.ImShow("dst", dst);
            Cv2.WaitKey(0);
        }
    }
}

仿射变换:

// 仿射变换(保持水平)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace Transformation
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = Cv2.ImRead("../../opencv.png");
            Mat dst = new Mat();

            List<Point2f> src_pts = new List<Point2f>()
            {
                new Point2f(0.0f, 0.0f),
                new Point2f(0.0f, src.Height),
                new Point2f(src.Width, src.Height)
            };

            List<Point2f> dst_pts = new List<Point2f>()
            {
               new Point2f(50.0f, 50.0f),
               new Point2f(0.0f, src.Height - 100.0f),
               new Point2f(src.Width - 50.0f, src.Height - 50.0f)
            };

            Mat matrix = Cv2.GetAffineTransform(src_pts, dst_pts);
            Cv2.WarpAffine(src, dst, matrix, new Size(src.Width, src.Height));

            Cv2.ImShow("src", src);
            Cv2.ImShow("dst", dst);
            Cv2.WaitKey(0);
        }
    }
}

图像旋转:

// 图像旋转
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace Transformation
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = Cv2.ImRead("../../opencv.png");
            Mat dst = new Mat();
            Mat dst2 = new Mat();
            Mat dst3 = new Mat();

            Mat matrix = Cv2.GetRotationMatrix2D(new Point2f(src.Width / 2, src.Height / 2), 90.0, 1.0);
            Mat matrix2 = Cv2.GetRotationMatrix2D(new Point2f(src.Width / 2, src.Height / 2), 180.0, 1.0);
            Mat matrix3 = Cv2.GetRotationMatrix2D(new Point2f(src.Width / 2, src.Height / 2), 100.0, 1.0);

            Cv2.WarpAffine(src, dst, matrix, new Size(src.Width, src.Height)); // 아핀변환 함수를 적용
            Cv2.WarpAffine(src, dst2, matrix2, new Size(src.Width, src.Height));
            Cv2.WarpAffine(src, dst3, matrix3, new Size(src.Width, src.Height));

            Cv2.ImShow("src", src);
            Cv2.ImShow("dst", dst);
            Cv2.ImShow("dst2", dst2);
            Cv2.ImShow("dst3", dst3);

            Cv2.WaitKey(0);
            Cv2.DestroyAllWindows();
        }
    }
}

图像对称翻转:

// 图像对称
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace Transformation
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = Cv2.ImRead("../../opencv.png");
            Mat dst = new Mat(src.Size(), MatType.CV_8UC3);
            Mat dst2 = new Mat(src.Size(), MatType.CV_8UC3);
            Mat dst3 = new Mat(src.Size(), MatType.CV_8UC3);

            Cv2.Flip(src, dst, FlipMode.Y); // Y轴对称
            Cv2.Flip(src, dst2, FlipMode.X); //X轴对称
            Cv2.Flip(src, dst3, FlipMode.XY); // XY轴对称

            Cv2.ImShow("src", src);
            Cv2.ImShow("dst", dst);
            Cv2.ImShow("dst2", dst2);
            Cv2.ImShow("dst3", dst3);
            Cv2.WaitKey(0);
            Cv2.DestroyAllWindows();
        }
    }
}

图像大小调整:

// 图像大小调整
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace Transformation
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = Cv2.ImRead("../../opencv.png");
            Mat dst = new Mat();
            Mat dst2 = new Mat();

            Cv2.Resize(src, dst, new Size(500, 250)); // 绝对大小
            Cv2.Resize(src, dst2, new Size(0, 0), 0.5, 0.5); // 相对大小

            Cv2.ImShow("src", src);
            Cv2.ImShow("dst", dst);
            Cv2.ImShow("dst2", dst2);
            Cv2.WaitKey(0);
        }
    }
}

图像缩放:

//图像缩放
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCvSharp;

namespace Transformation
{
    class Program
    {
        static void Main(string[] args)
        {
            Mat src = Cv2.ImRead("../../opencv.png");
            Mat dst = new Mat(src.Size(), MatType.CV_8UC3);
            Mat dst2 = new Mat(src.Size(), MatType.CV_8UC3);

            // Cv2.PyrUp(src, dst, new Size(src.Width * 2 + 1, src.Height * 2 - 1));
            Cv2.PyrUp(src, dst);
            Cv2.PyrDown(src, dst2); //减少 4 倍
            Cv2.PyrDown(dst2, dst2); //减少 16 倍

            Cv2.ImShow("src", src);
            Cv2.ImShow("dst", dst);
            Cv2.ImShow("dst2", dst2);

            Cv2.WaitKey(0);
            Cv2.DestroyAllWindows();
        }
    }
}

OpenCvSharp.UserInterface.PictureBoxIpl控件显示图像:

            using (IplImage ipl = new IplImage("../../opencv.png", LoadMode.AnyColor))
            {
                pictureBoxIpl1.ImageIpl = ipl;
            }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值