最近需要绘制灰阶图,写了一个opencv绘制灰阶图的函数
cv::Mat MakeColorMap(int bkgWidth, int bkgHeight, int mapNum, char *savePath) {
if (savePath == NULL) {
char *defaultPath = (char *) "/data/colorMap.png";
savePath = defaultPath;
}
float mapWidth = (float) bkgWidth / ((float) mapNum);//色阶宽度
uchar pixel = 0;
cv::Mat img(bkgHeight, bkgWidth, CV_8UC4, cv::Scalar(0, 0, 0, 255));
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
int level = (int) (j / mapWidth);
pixel = (uchar) (level * ((255.0 / ((float) mapNum - 1.0))));
img.at<cv::Vec<uchar, 4>>(i, j) = cv::Scalar(pixel, pixel, pixel, 255);
}
}
imwrite(savePath, img); //保存生成的图片
return img;
}
比如绘制一个16色灰阶图
MakeColorMap(1280, 720, 2, (char *) "/work/colormap.bmp");
效果如下:
测一下显示器的质量吧,啧啧。