我正在尝试在OpenCV中设置CV_8UC3
类型图像的像素值。我知道如何使用单个通道图像CV_8UC1
执行此操作,但在使用三通道图像执行相同操作时,像素值最终会模糊到相邻像素,即使它们未被更改。
这是我使用单通道图像的方式:
Mat tmp(5, 5, CV_8UC1, Scalar(0));
uchar *tmp_p = tmp.ptr();
tmp_p[0] = (uchar)255;
imwrite("tmp.jpg", tmp);
生成的图像正如您所期望的那样,只是第一个像素已经从黑色变为白色,而所有其他像素都保持不变。
以下是我期望用三通道图像进行的操作:
Mat tmp(5, 5, CV_8UC3, Scalar(0));
uchar *tmp_p = tmp.ptr();
tmp_p[0] = (uchar)255;
imwrite("tmp.jpg", tmp);
此过程的预期结果应在图像的左上角产生一个蓝色像素。然而,相邻的3个像素似乎与我设置的像素值“模糊”。
如果有人知道为什么会出现这种模糊的像素,我非常感谢我能得到的任何帮助。
答案 0 :(得分:0)
事实证明问题出在图像文件格式中。我输出的图像为.jpg
,正在修改像素。将文件类型更改为.png
时,此问题已得到纠正。
现在我的代码是在输出到文件之前以及在输出的文件中重新读取之后打印到原始图像的控制台。
// create a small black image and
// change the color of the first pixel to blue
Mat tmp(5, 5, CV_8UC3, Scalar(0));
uchar *tmp_p = tmp.ptr();
tmp_p[0] = (uchar)255;
// output values to the console
cout << tmp << endl << endl;
// write out image to a file then re-read back in
#define CORRECTMETHOD // comment out this line to see what was wrong before
#ifdef CORRECTMETHOD
imwrite("tmp.png", tmp);
tmp = imread("tmp.png");
#else
imwrite("tmp.jpg", tmp);
tmp = imread("tmp.jpg");
#endif
// print out values to console (these values
// should match the original image created above)
cout << tmp << endl;