OpenCV杂项图像变换(1)自适应阈值处理函数adaptiveThreshold()的使用

  • 操作系统:ubuntu22.04
  • OpenCV版本:OpenCV4.9
  • IDE:Visual Studio Code
  • 编程语言:C++11

算法描述

函数对数组应用自适应阈值。

该函数根据以下公式将灰度图像转换为二值图像:

  • 对于 THRESH_BINARY:
    t e x t d s t ( x , y ) = { maxValue 如果 src ( x , y ) > T ( x , y ) 0 否则 \\text{dst}(x, y) =\begin{cases}\ \text{maxValue} & \text{如果 } \text{src}(x, y) > T(x, y) \\ 0 & \text{否则} \end{cases} textdst(x,y)={ maxValue0如果 src(x,y)>T(x,y)否则

  • 对于THRESH_BINARY_INV:
    dst ( x , y ) = { 0 如果 src ( x , y ) > T ( x , y ) maxValue 否则 \text{dst}(x, y) = \begin{cases} 0 & \text{如果 } \text{src}(x, y) > T(x, y) \\ \text{maxValue} & \text{否则} \end{cases} dst(x,y)={0maxValue如果 src(x,y)>T(x,y)否则

    其中 T ( x , y ) T(x,y) T(x,y) 是为每个像素单独计算的阈值(参见 adaptiveMethod 参数)。

adaptiveThreshold() 函数是 OpenCV 中用于实现自适应阈值处理的一种方法。这种处理方式特别适用于照明条件变化较大的场景,因为它能够根据图像局部区域的亮度自动调整阈值。

该函数可以原地处理图像

函数原型

cpp 复制代码
void cv::adaptiveThreshold	
(
	InputArray 	src,
	OutputArray 	dst,
	double 	maxValue,
	int 	adaptiveMethod,
	int 	thresholdType,
	int 	blockSize,
	double 	C 
)		

参数

  • 参数src 源 8 位单通道图像。
  • 参数dst 目标图像,具有与 src 相同的大小和类型。
  • 参数maxValue 分配给满足条件的像素的非零值。
  • 参数adaptiveMethod 使用的自适应阈值算法,参见 AdaptiveThresholdTypes。使用 BORDER_REPLICATE | BORDER_ISOLATED 来处理边界。
  • 参数thresholdType 阈值类型,必须是 THRESH_BINARY 或 THRESH_BINARY_INV,参见 ThresholdTypes。
  • 参数blockSize 用于计算像素阈值的像素邻域大小:3, 5, 7 等等。
  • 参数C 从均值或加权均值中减去的常数(参见下面的详细信息)。通常它是正数,但也可能是零或负数。

代码示例

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

using namespace cv;

int main(int argc, char** argv)
{
    // 读取图像
    Mat image = imread("/media/dingxin/data/study/OpenCV/sources/images/sun2.jpg", IMREAD_GRAYSCALE);
    
    if (image.empty()) {
        std::cerr << "Error: Could not open or find the image." << std::endl;
        return -1;
    }
    
    // 创建输出图像
    Mat binaryImage;
    
    // 应用自适应阈值处理
    adaptiveThreshold(image, binaryImage, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 3, 2);
    
    // 显示结果
    namedWindow("Original Image", WINDOW_NORMAL);
    imshow("Original Image", image);
    
    namedWindow("Binary Image", WINDOW_NORMAL);
    imshow("Binary Image", binaryImage);
    
    waitKey(0);
    
    return 0;
}

运行结果

相关推荐
桦说编程7 分钟前
我让 AI 加了一个开关,结果代码走了原本不该走的分支
人工智能·代码规范
fly spider7 分钟前
AI 到底是怎么访问网页的?从爬虫、Browser Agent 到 Computer Use
人工智能·爬虫
Lee川39 分钟前
RAG 实战:从一篇掘金文章出发,拆解检索增强生成的全链路
前端·人工智能·后端
码农小旋风44 分钟前
Codex小白入门使用教程
人工智能·chatgpt·claude
Lee川1 小时前
MCP 高德地图实战:当 AI 学会使用工具,一个协议如何重塑大模型的行动边界
前端·人工智能·后端
凌杰1 小时前
AI 学习笔记:Agent 的应用演示
人工智能
程序员cxuan1 小时前
Codex 把我家烂网给优化后,我 TM 直接原地起飞了。
人工智能·后端·程序员
IT_陈寒1 小时前
Redis批量删除踩了坑,原来DEL命令不是万能的
前端·人工智能·后端
xinhuanjieyi1 小时前
gpt-sovits测试语音克隆
人工智能·gpt
星辰AI1 小时前
Transformers 架构核心原理:从注意力机制到 GPT
人工智能·ai·语言模型