OpenCV 阈值法

1.概述

在深度学习出现之前,图像中的阈值法处理主要有二值阈值法、自适应阈值法、Ostu阈值法。

2.理论对比

3.代码实现

cpp 复制代码
#include <iostream>
#include <opencv2/opencv.hpp>

int main(int argc, char** argv) {
    if(argc != 2) {
        std::cerr << "Usage: " << argv[0] << " <image_path>" << std::endl;
        return -1;
    }

    // Load the image
    cv::Mat image = cv::imread(argv[1], cv::IMREAD_GRAYSCALE);
    if(image.empty()) {
        std::cerr << "Error: Couldn't read the image. Check the path and try again." << std::endl;
        return -1;
    }
    cv::imshow("Original Image", image);

    // Binary Thresholding
    cv::Mat binaryThresholded;
    cv::threshold(image, binaryThresholded, 127, 255, cv::THRESH_BINARY);
    cv::imshow("Binary Thresholding", binaryThresholded);

    // Adaptive Thresholding
    cv::Mat adaptiveThresholded;
    cv::adaptiveThreshold(image, adaptiveThresholded, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, 11, 2);
    cv::imshow("Adaptive Thresholding", adaptiveThresholded);

    // Otsu's Thresholding
    cv::Mat otsuThresholded;
    cv::threshold(image, otsuThresholded, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
    cv::imshow("Otsu's Thresholding", otsuThresholded);

    // Wait for a key press and then close
    cv::waitKey(0);
    
    return 0;
}
相关推荐
陈彬深大几秒前
《AI 渐进编程》之二十三:自适应调度——什么时候启用多Agent流水线
人工智能
invicinble几秒前
搭建智能体--skill和mcp的进一步理解
人工智能
周末程序猿11 分钟前
LLM智能路由实践:通过 Harness 工程节约模型成本
人工智能·agent
冬奇Lab13 分钟前
代码库知识库系列(04):三种 Chunking 策略对比——AST 精确分割反而输了?
人工智能
宋哥转AI1 小时前
深入理解 AI Agent 02|混合检索与重排序实战:BM25、RRF 与 Cross-Encoder 的工程实践
人工智能
LaughingZhu1 小时前
Product Hunt 每日热榜 | 2026-08-01
人工智能·深度学习·神经网络·搜索引擎·百度
小燕子~~1 小时前
PS 怎么调整图片尺寸?4 种方法避免拉伸变形与放大失真
图像处理·人工智能·ai·aigc·photoshop
小K讲AI营销1 小时前
AI 链定价逻辑切换:用“估值透支“框架重估一个月跌三成
人工智能
龙山云仓2 小时前
八一亮剑 · 造化进行时(AI-类人)
人工智能
小赵AI手记2 小时前
技术拆解(十五)具身智能:RT-2为什么能听懂“灭绝动物”?VLM知识如何变成动作
人工智能·机器人