RGB图像灰度化

#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;

const int BGR_TO_GRAY_AVERAGING_SHIFT = 8;
const int BGR_TO_GRAY_ROUND_TERM = 1 << (BGR_TO_GRAY_AVERAGING_SHIFT - 1);
const int BLUE_TO_GRAY_WEIGHT = int(0.114*(1 << BGR_TO_GRAY_AVERAGING_SHIFT) + 0.5);
const int GREEN_TO_GRAY_WEIGHT = int(0.587*(1 << BGR_TO_GRAY_AVERAGING_SHIFT) + 0.5);
const int RED_TO_GRAY_WEIGHT = 255 - BLUE_TO_GRAY_WEIGHT - GREEN_TO_GRAY_WEIGHT;
void RGB2Y(unsigned char *Src, unsigned char *Dest, int Width, int Height, int Stride);

inline const unsigned char BgrToGray(int blue, int green, int red)
{
	return (BLUE_TO_GRAY_WEIGHT*blue + GREEN_TO_GRAY_WEIGHT * green +
		RED_TO_GRAY_WEIGHT * red ) >> BGR_TO_GRAY_AVERAGING_SHIFT;
}

void BgraToGray(const unsigned char * bgra, size_t width, size_t height, size_t bgraStride, unsigned char * gray, size_t grayStride) { for (size_t row = 0; row < height; ++row) { const unsigned char * pBgra = bgra + row*bgraStride; unsigned char * pGray = gray + row*grayStride; for (const uint8_t *pGrayEnd = pGray + width; pGray < pGrayEnd; pGray += 1, pBgra += 3) { *pGray = BgrToGray(pBgra[0], pBgra[1], pBgra[2]); } } } int main(int argc, char** argv) { Mat src = imread("C:/Users/lvmeng/Desktop/Image/hua.jpg", 1); int Height = src.rows; int Width = src.cols; unsigned char *Src = src.data; unsigned char *Dest = new unsigned char[Height * Width]; int64 st = cvGetTickCount(); BgraToGray(Src, Width, Height, Width * 3, Dest, Width); double duration = 1000*((cv::getTickCount() - st) / cv::getTickFrequency() ) ; printf("%.5f\n", duration); Mat dst(Height, Width, CV_8UC1, Dest); imshow("aaaaaa", dst); cvWaitKey(0); system("pause"); return 0; }

  RGB图像灰度化,很简单的代码,原理也很简单,没必要多解释!!!

posted @ 2020-03-30 16:34  盖世猪猪侠  阅读(242)  评论(0编辑  收藏  举报