OpenCVSharp 4.5 图像阈值

这篇博客通过C#的OpenCVSharp4库,详细介绍了如何手敲代码来运行OpenCV官方的图像阈值处理教程。作者创建了一个名为`Threshold_Demo`的函数,使用`Cv2.Threshold`进行不同类型的阈值操作,并通过创建滑块来调整阈值类型和值,实现实时预览效果。博客中提供了完整的代码示例,涵盖了从读取图像到显示处理结果的整个过程。

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

OpenCVSharp 4.5 跑一遍OpenCV官方教程(全为手敲代码,如有雷同都是我的错)

阈值

OpenCV教程链接:https://docs.opencv.org/4.5.0/db/d8e/tutorial_threshold.html

核心语句

  • threshold
using OpenCvSharp;
using System;

namespace ConsoleApp1
{
    class tutorial9 : ITutorial
    {

        static int threshold_value = 0;
        static int threshold_type = 3;
        static int max_value = 255;
        static int max_type = 4;
        static int max_binary_value = 255;
        static Mat src, src_gray, dst;
        static string window_name = "Threshold Demo";
        static string trackbar_type = "Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted";
        static string trackbar_value = "Value";

        static void Threshold_Demo(int pos , IntPtr userdata)
        {
            /* 0: Binary
             1: Binary Inverted
             2: Threshold Truncated
             3: Threshold to Zero
             4: Threshold to Zero Inverted
            */

            Cv2.Threshold(src_gray, dst, threshold_value, max_binary_value,  (ThresholdTypes)threshold_type);
            Cv2.ImShow(window_name, dst);
        }

        public void Run()
        {
            string imageName = "I:\\csharp\\images\\stuff.jpg";
            src = Cv2.ImRead(imageName, ImreadModes.Color); // Load an image
            if (src.Empty())
            {
                Console.WriteLine("Cannot read the image:{0}", imageName);
                return;
            }
            src_gray = new Mat();
            dst = new Mat();
            Cv2.CvtColor(src, src_gray, ColorConversionCodes.BGR2GRAY); // Convert the image to Gray
            Cv2.NamedWindow(window_name, WindowFlags.AutoSize); // Create a window to display results
            Cv2.CreateTrackbar(trackbar_type,
                            window_name, ref threshold_type,
                            max_type, Threshold_Demo); // Create a Trackbar to choose type of Threshold
            Cv2.CreateTrackbar(trackbar_value,
                            window_name, ref threshold_value,
                            max_value, Threshold_Demo); // Create a Trackbar to choose Threshold value
            Threshold_Demo(0, IntPtr.Zero); // Call the function to initialize
            Cv2.WaitKey();
        }
    }    
}

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值