天天看點

opencv提高圖像對比度

// 提高圖檔亮度和對比度.cpp: 定義控制台應用程式的入口點。
//

#include "stdafx.h"
#include "opencv2/opencv.hpp"
#include "opencv2/highgui.hpp"
using namespace std;
using namespace  cv;


int main()
{   
    Mat src,dest;
    src = imread("test.jpg");

    namedWindow("src", CV_WINDOW_AUTOSIZE);
    imshow("src", src);

    dest = Mat::zeros(src.size(), src.type());
    int width = src.cols;
    int height = src.rows;
    int channels = src.channels();

    int alphe = ; //(alphe > 1)
    int beta = -;// 負數對比度越高
    Mat m1;
    src.convertTo(m1, CV_32F); //将原始圖檔資料(CV_8U類型)轉換成CV_32類型,以提高操作的精度
    for (int row = ; row < height;row++) {
        for (int col = ; col < width; col++) {
            if (channels == ) { //對于3通道
                float b = m1.at<Vec3f>(row,col)[];
                float g = m1.at<Vec3f>(row, col)[];
                float r = m1.at<Vec3f>(row, col)[];

                dest.at<Vec3b>(row, col)[] = saturate_cast<uchar>(alphe * b + beta);
                dest.at<Vec3b>(row, col)[] = saturate_cast<uchar>(alphe * g + beta);
                dest.at<Vec3b>(row, col)[] = saturate_cast<uchar>(alphe * r + beta);
            }
            else if (channels == ){ //對于單通道
                int pix = src.at<uchar>(row, col);
                dest.at<uchar>(row,col) = saturate_cast<uchar>(alphe * pix + beta);
            }
        }
    }
    namedWindow("change");
    imshow("change",dest);
    waitKey();

    return ;
}