#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();
}
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;
}
}
}
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转灰度图(自己实现和api实现两种)以及性能对比
最新推荐文章于 2024-06-17 15:33:29 发布
本文探讨了OpenCV库中`cvtColor`函数与自定义实现的RGB to Gray转换函数RGBToGray的性能对比。通过实例展示了如何使用OpenCV进行BGR到灰度的转换,并引入了自己编写的灰度转换方法,最后通过`PrintMs`函数测量了两个方法的时间效率。
摘要由CSDN通过智能技术生成