由于如果要在灰度图上进行标记效果不好,而且比较模糊。因此要想在图像得到一个比较好的标记,我们选择把灰度图转化为伪灰度图的三通道图像上进行标记。
Mat QuickDemo::grayImage_mask_print(Mat& image)
{
// 输入图像image是单通道的灰度图
int h = image.rows;
int w = image.cols;
int dims = image.channels();
// 将单通道灰度图转换成为伪灰度图的三通道图像
Mat image_bgr;
cvtColor(image, image_bgr, COLOR_GRAY2BGR);
for (int row = 0; row < h; row++)
{
for (int col = 0; col < w; col++) {
if (image.at<uchar>(row, col) > 0 && image.at<uchar>(row, col) < 40) {
image_bgr.at<Vec3b>(row, col)[0] = 0;
image_bgr.at<Vec3b>(row, col)[1] = 0;
image_bgr.at<Vec3b>(row, col)[2] = 255;
}
}
}
return image_bgr;
}
测试函数如下:
int main(int argc, char** argv) {
Mat src = imread("D:\\testImage\\4.BMP");
Mat pt = src;
if (src.empty()) {
printf("could not load image...");
return -1;
}
imshow("原图", src);
Mat image_gray;
cvtColor(src, image_gray, COLOR_BGR2GRAY);
Mat image_bgr;
cvtColor(image_gray, image_bgr, COLOR_GRAY2BGR);
namedWindow("输入窗口", WINDOW_FREERATIO);
imshow("输入窗口", image_bgr);
int gray_dims = image_gray.channels();
int bgr_dims = image_bgr.channels();
cout << "image_gray的通道数:" << gray_dims << endl;
cout << "image_bgr的通道数:" << bgr_dims << endl;
QuickDemo qd;
Mat new_image = qd.grayImage_mask_print(image_gray);
namedWindow("new_image", WINDOW_FREERATIO);
imshow("new_image", new_image);
waitKey(0);
return 0;
}
上图分别是通道数图、原图、灰度图以及摸一个像素的标记图