一、概述:
人类能够观察到的光的波长范围是有限的,并且人类视觉有一个特点,只能分辨出二十几种灰度,也就是说即使采集到的灰度图像分辨率超级高,有上百个灰度级,但是很遗憾,人们只能看出二十几个,也就是说信息损失了五十倍。但人类视觉对彩色的分辨能力相当强,能够分辨出几千种色度,所以在实际应用中,可以将灰度图转变成彩虹图或者伪彩图等根据需求的彩色图。
二、彩虹图:
主要思路:把灰度图对应的0~255的数值分别转成彩虹色:红、橙、黄、绿、青、蓝,这里没有使用紫色,是因为紫色的效果并不好。
//彩虹图的颜色分配取一下值 // R G B gray //---------------------------------- // 红 255, 0, 0 255 // 橙 255, 127, 0 204 // 黄 255, 255, 0 153 // 绿 0, 255, 0 102 // 青 0, 255, 255 51 // 蓝 0, 0, 255 0
代码:
Mat gray2rainbow(const Mat& scaledGray) { Mat outputRainbow(scaledGray.size(), CV_8UC3); unsigned char grayValue; for (int y = 0; y < scaledGray.rows; y++) for (int x = 0; x < scaledGray.cols; x++) { grayValue = scaledGray.at(y, x); Vec3b& pixel = outputRainbow.at (y, x); if (grayValue <= 51) { pixel[0] = 255; pixel[1] = grayValue * 5; pixel[2] = 0; } else if (grayValue <= 102) { grayValue -= 51; pixel[0] = 255 - grayValue * 5; pixel[1] = 255; pixel[2] = 0; } else if (grayValue <= 153) { grayValue -= 102; pixel[0] = 0; pixel[1] = 255; pixel[2] = grayValue * 5; } else if (grayValue <= 204) { grayValue -= 153; pixel[0] = 0; pixel[1] = 255 - static_cast char>(grayValue * 128.0 / 51 + 0.5); pixel[2] = 255; } else if (grayValue <= 255) { grayValue -= 204; pixel[0] = 0; pixel[1] = 127 - static_cast char>(grayValue * 127.0 / 51 + 0.5); pixel[2] = 255; } } return outputRainbow; }
三、伪彩图
伪彩色图片的处理,就是用RGB三色交叉,不同的彩色表示不同的灰度值,将一幅灰度图转变成为一幅彩色图片。
Mat gray2pseudocolor(const Mat& scaledGray) { Mat outputPseudocolor(scaledGray.size(), CV_8UC3); unsigned char grayValue; for (int y = 0; y < scaledGray.rows; y++) for (int x = 0; x < scaledGray.cols; x++) { grayValue = scaledGray.at(y, x); Vec3b& pixel = outputPseudocolor.at (y, x); pixel[0] = abs(255 - grayValue); pixel[1] = abs(127 - grayValue); pixel[2] = abs(0 - grayValue); } return outputPseudocolor; }
四、铜色图
将R去0,G、B两色交叉。
Mat gray2CopperColor(const Mat& scaledGray) { Mat outputCopperColor(scaledGray.size(), CV_8UC3); unsigned char grayValue; for (int y = 0; y < scaledGray.rows; y++) for (int x = 0; x < scaledGray.cols; x++) { grayValue = scaledGray.at(y, x); Vec3b& pixel = outputCopperColor.at (y, x); pixel[0] = abs(0); pixel[1] = abs(grayValue); pixel[2] = abs(grayValue); } return outputCopperColor; }
五、灰度反转
将图像进行灰度反转处理,即将灰度值为x的像素点转变为255-x。
利用Opencv中bitwise_not()函数可实现,没必要一个像素点一个像素点处理。
Mat gray2disColor(const Mat& scaledGray) { Mat disColor(scaledGray.size(), CV_8UC3); bitwise_not(disColor, scaledGray); return disColor; }
六、灰度图
将一幅彩色图片转换为灰度图
Mat scaleGray(const Mat& inputGray) { Mat outputGray(inputGray.size(), CV_8U); unsigned char grayValue, maxValue = 1; for (int y = 0; y < inputGray.rows; y++) for (int x = 0; x < inputGray.cols; x ++) { grayValue = inputGray.at(y, x); maxValue = max(maxValue, grayValue); } float scale = 255.0 / maxValue; for (int y = 0; y < inputGray.rows; y++) for (int x = 0; x < inputGray.cols; x ++) { outputGray.at (y, x) = static_cast char>(inputGray.at (y, x) * scale + 0.5); } return outputGray; }
七、完整代码
略