天天看點

opencv調節圖檔亮度對比度

// opencv2.cpp : 定義控制台應用程式的入口點。
 //#include "stdafx.h"
 //-----------------------------------【頭檔案包含部分】---------------------------------------
 //     描述:包含程式所依賴的頭檔案
 //----------------------------------------------------------------------------------------------
 #include <opencv2/core/core.hpp>
 #include<opencv2/highgui/highgui.hpp>
 #include"opencv2/imgproc/imgproc.hpp"
 #include <iostream>using namespace std;
 using namespace cv;static void ContrastAndBright(int, void *);
int m_Value; //對比度值
 int g_Value;  //亮度值
 Mat src_Image, dst_Image;int main()
 {
  //改變控制台前景色和背景色
  system("color5F");
  //讀入使用者提供的圖像
  src_Image = imread("test.jpg");
  if (!src_Image.data) { printf("讀取圖檔錯誤~!\n"); return false; }
  //将src_Image的大小和格式指派給dst_Image
  dst_Image = Mat::zeros(src_Image.size(), src_Image.type());
  //設定對比度和亮度的初值
  m_Value = 80;
  g_Value = 80;
  //建立視窗
  namedWindow("效果圖視窗", 1);
  //建立軌迹條
  createTrackbar("對比度:", "效果圖視窗", &m_Value, 300, ContrastAndBright);
  createTrackbar("亮   度:", "效果圖視窗", &g_Value, 200, ContrastAndBright);
  //調用回調函數
  ContrastAndBright(m_Value, 0);
  ContrastAndBright(g_Value, 0);
  //輸出一些幫助資訊
  cout << endl << "\t嗯。好了,請調整滾動條觀察圖像效果~\n\n"
   << "\t按下“q”鍵時,程式退出~!\n"
   << "\n\n\t\t\t\tby淺墨";
  //按下“q”鍵時,程式退出
  while (char(waitKey(1)) != 'q') {}
  return 0;
 } //-----------------------------【ContrastAndBright( )函數】------------------------------------
 //     描述:改變圖像對比度和亮度值的回調函數
 //-----------------------------------------------------------------------------------------------
 static void ContrastAndBright(int, void *)
 {
  //建立視窗
  namedWindow("原始圖視窗", 1);
  //三個for循環,執行運算 dst_Image(i,j) =a*src_Image(i,j) + b
  for (int y = 0; y < src_Image.rows; y++)
  {
   for (int x = 0; x < src_Image.cols; x++)
   {
    for (int c = 0; c < 3; c++)
    {
     dst_Image.at<Vec3b>(y, x)[c] = saturate_cast<uchar>((m_Value*0.01)*(src_Image.at<Vec3b>(y, x)[c]) + g_Value);
    }
   }
  }
  //顯示圖像
  imshow("原始圖視窗", src_Image);
  imshow("效果圖視窗", dst_Image);
 }