Opencv(C++)笔记--图像的二值化、修改对比度和亮度

1--二值化代码

# include
# include
using namespace cv;

int main(int argc, char *argv[]){
    Mat src = imread("./test1.jpg");
    Mat gray;
    Mat bin;
    Mat ibin;

    // 灰度图转化
    cvtColor(src, gray, COLOR_BGR2GRAY);

    //二进制阈值化
    threshold(gray, bin, 100, 255, THRESH_BINARY);

    //二进制反阈值化
    threshold(gray, ibin, 100, 255, THRESH_BINARY_INV);



    namedWindow("src");
    namedWindow("bin");
    namedWindow("ibin");
    imshow("bin", bin);
    imshow("src", src);
    imshow("ibin", ibin);

    waitKey(0);
    printf("All Done!\n");

    return 0;
}
cmake_minimum_required(VERSION 3.24)  # 指定 cmake的 最小版本
project(test) # 设置项目名称

find_package(Opencv REQUIRED)
INCLUDE_DIRECTORIES(${OpenCV_INCLUDE_DIRS})
add_executable(main main.cpp) # 生成可执行文件
target_link_libraries(main ${OpenCV_LIBS}) # 设置target需要链接的库

2--二值化结果

Opencv(C++)笔记--图像的二值化、修改对比度和亮度_第1张图片

3--修改对比度和亮度代码

# include
# include
using namespace cv;

void ChangeGain(Mat &src, Mat &des, float a, int b){
    //g(r, c) = a*f(r, c) + b
    des.create(src.rows, src.cols, src.type());
    for (int r = 0; r < src.rows; r++){
        for (int c = 0; c < src.cols; c++){
            for (int i = 0; i < 3; i++){
                des.at(r, c)[i] = saturate_cast(a * src.at(r, c)[i] + b);
            }
        }
    }
}
int main(int argc, char *argv[]){
    Mat src = imread("./test1.jpg");
    Mat des;
    ChangeGain(src, des, 2.0, 50);

    namedWindow("src");
    namedWindow("des");
    imshow("src", src);
    imshow("des", des);
    waitKey(0);
    printf("All Done!\n");

    return 0;
}

4--修改对比度和亮度结果

5--知识点

①修改对比度和亮度的公式:g(i, j) = a * f(i, j) + b;

对比度a的取值范围一般为(1.0 ~ 3.0),亮度b的取值范围一般为(0 ~ 100);

②saturate_cast是OpenCV防止溢出的一个函数,当像素值超过255时,修正为255,当像素值为负数时,修正为0;

你可能感兴趣的:(Opencv(C++)学习笔记,opencv,c++,计算机视觉)