二值化是逐像素处理,而逐像素处理会有很多效果,这主要是给人眼看的,因为像素值的变化,直观的就是图像变化,比如颜色。
OpenCV提供了一些图片,如下:
粗看是一些风格,细看一下,其实是各行颜色一致,看属性知道图像尺寸为256 * 30。
256是字节宽度,也是各通道取值范围。
所以,可以用查表法直接替代处理,即将上面一张图片作为输入,则各行就将原值的0-255映射成为图片相应列的值。图像尺寸设置为30,其实也无所谓多少行,至少一行就行,不过行数太少了,人看起来就感觉,行数多了,读到计算机内存里面处理也浪费。那就折衷选个30吧。
代码处理,这就看水平了,可以一次性全读入,也可以只读取需要的图片。
QString colorMapPath = THelper::File::GetPath_Resource() + "colorMap/";
QStringList fileNames;
THelper::File::BrowseDir(fileNames, colorMapPath, "*.*");
if (!COLORMAP_TABLE) {
if(fileNames.count() > 0) {
COLORMAP_TABLE = new cv::Vec3b[256 * fileNames.count()];
BYTE * pDst = (BYTE*)COLORMAP_TABLE;
foreach(QString fileName, fileNames) {
cv::Mat mat = CvHelper::MatFromFile(fileName);
if(mat.cols * mat.channels() == 256 * 3) {
memcpy(pDst, mat.data, 256 * 3);
pDst += 256 * 3;
}
}
}
}
最终的颜色变幻处理逻辑:
// 其它-颜色变幻
int paramIndex = 0;
FMapIndex = GetParamValue_Int(paramIndex++); // 0: 变幻颜色
Mat tempMat;
cvtColor(dstMat, tempMat, COLOR_BGR2GRAY);
dstMat = cv::Mat(tempMat.rows, tempMat.cols, CV_8UC3);
cv::Vec3b * table = COLORMAP_TABLE + 256 * FMapIndex;
BYTE * pTemp = tempMat.data;
cv::Vec3b * pDst = (cv::Vec3b*)dstMat.data;
for (int row = 0; row < tempMat.rows; ++row)
for (int col = 0; col < tempMat.cols; ++col)
* pDst++ = table[*pTemp++];
本质上还是逐像素处理,这里是查表法,核心逻辑就是* pDst++ = table[*pTemp++];
这个整明白后,那就可以自己设计一个图片作为查表输入,当然有一点点的美工基础更好。
OpenCV中,提供了一个applyColorMap函数,具体文档说明:
/** @brief Applies a GNU Octave/MATLAB equivalent colormap on a given image.
@param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3.
@param dst The result is the colormapped source image. Note: Mat::create is called on dst.
@param colormap The colormap to apply, see #ColormapTypes
*/
CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, int colormap);
继续查看ColormapTypes定义,可知其系统提供了22种颜色风格。
//! GNU Octave/MATLAB equivalent colormaps
enum ColormapTypes
{
COLORMAP_AUTUMN = 0, //!< 
COLORMAP_BONE = 1, //!< 
COLORMAP_JET = 2, //!< 
COLORMAP_WINTER = 3, //!< 
COLORMAP_RAINBOW = 4, //!< 
COLORMAP_OCEAN = 5, //!< 
COLORMAP_SUMMER = 6, //!< 
COLORMAP_SPRING = 7, //!< 
COLORMAP_COOL = 8, //!< 
COLORMAP_HSV = 9, //!< 
COLORMAP_PINK = 10, //!< 
COLORMAP_HOT = 11, //!< 
COLORMAP_PARULA = 12, //!< 
COLORMAP_MAGMA = 13, //!< 
COLORMAP_INFERNO = 14, //!< 
COLORMAP_PLASMA = 15, //!< 
COLORMAP_VIRIDIS = 16, //!< 
COLORMAP_CIVIDIS = 17, //!< 
COLORMAP_TWILIGHT = 18, //!< 
COLORMAP_TWILIGHT_SHIFTED = 19, //!< 
COLORMAP_TURBO = 20, //!< 
COLORMAP_DEEPGREEN = 21 //!< 
};
运行效果
OpenCV 4 功能 - 颜色变幻
不过,用applyColorMap的话,受到的制约就是只有这22种效果。也许OpenCV 5会更多一些。要想自由的话,还是直接查表处理,那里啥都有。