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

#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
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<Vec3b>(r, c);
			int gray = (m[2] * 30 + m[1] * 59 + m[0] * 11 + 50) / 100;
			des.at<uchar>(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<Vec3b>(r, c)[i] = saturate_cast<uchar>(a * src.at<Vec3b>(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 <des.rows; y++)
		{
			sy = fy * y + 0.5;
			des.at<Vec3b>(y, x) = src.at<Vec3b>(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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值