OpenCV --- 修改图像的对比度、亮度 、RGB转Gray图像、修改图像的尺寸

#include 
#include 
#include 
#include 
#include 
using namespace cv;
using namespace std;

// 计时函数
void PrintMs(const char *text = "")
{
	static long long last = 0;
	long long cur = getTickCount();
	if (last == 0)
	{
		last = cur;
		return;
	}
	long long ms = 0;
	ms = ((double)(cur - last) / getTickFrequency()) * 1000;
	if (*text != 0)
	{
		printf("%s = %dms\n", text,ms);
	}
	last = getTickCount();
}

// RGB图像转Gray图像
void RGBToGray(Mat &src, Mat &des)
{
	// GRay = (R*30 + G*59 + B*11 +50)/100
	des.create(src.rows,src.cols,CV_8UC1);
	for (int r = 0; r < src.rows; r++)
	{
		for (int c = 0; c < src.cols; c++)
		{
			Vec3b &m = src.at(r, c);
			int gray = (m[2] * 30 + m[1] * 59 + m[0] * 11 + 50) / 100;
			des.at(r, c) = gray;
		}
	}
}

/改变图像的对比度和亮度/
///@para a float 对比度 1.0~3.0
///@para b int 亮度 0~100
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);
			}
		}
	}
}

// 改变图像的尺寸
void xresize(Mat &src, Mat &des, Size size)
{
	des.create(size, src.type());
	//映射的原图坐标
	int sx, sy = 0;
	float fx = (float)src.cols / des.cols;
	float fy = (float)src.rows / des.rows; 
	for (int x = 0; x < des.cols; x++)
	{
		sx = fx * x + 0.5;
		for (int y = 0; y (y, x) = src.at(sy, sx);
		}
	}

}

int main(int argc, char *argv[])
{
	Mat src = imread("1.png");
	src.create(3000, 4000, CV_8UC3);
	Mat gray;
	PrintMs("");
	cvtColor(src, gray, COLOR_BGR2GRAY);
	PrintMs("cvtColor1");

	cvtColor(src, gray, COLOR_BGR2GRAY);
	PrintMs("cvtColor2");
	Mat mygray;
	RGBToGray(src, mygray);
	PrintMs("RGBToGray");

	namedWindow("src");
	namedWindow("gray");
	namedWindow("mygray");

	imshow("src", src);
	imshow("gray", gray);
	imshow("mygray", mygray);

	waitKey(0);


	return 0;
}

 

你可能感兴趣的:(opencv,C++)