简体   繁体   English

OpenCV设置颜色像素最终模糊到相邻像素

[英]Opencv setting a color pixel ends up blurring to neighboring pixels

I'm trying to set the pixel value of a CV_8UC3 type image in OpenCV. 我正在尝试在OpenCV中设置CV_8UC3类型图像的像素值。 I know how to do this with a single channel image CV_8UC1 , but when doing the same thing with a three channel image the pixel value ends up blurring to the neighboring pixels even though they were not changed. 我知道如何使用单通道图像CV_8UC1进行此CV_8UC1 ,但是当对三通道图像执行相同操作时,像素值最终会模糊到相邻像素,即使它们没有更改。

This is how I do it with a single channel image: 这是我使用单个通道图像执行的操作:

Mat tmp(5, 5, CV_8UC1, Scalar(0));
uchar *tmp_p = tmp.ptr();
tmp_p[0] = (uchar)255;
imwrite("tmp.jpg", tmp);

The resulting image is as you would expect, just the very first pixel has been changed from black to white, while all of the other pixels were left alone. 生成的图像是您所期望的,只是第一个像素已从黑色更改为白色,而所有其他像素则保持不变。

The following is how I'd expect to do it with a three channel image: 以下是我希望通过三通道图像进行的操作:

Mat tmp(5, 5, CV_8UC3, Scalar(0));
uchar *tmp_p = tmp.ptr();
tmp_p[0] = (uchar)255;
imwrite("tmp.jpg", tmp);

The expected result from this process should yield a single blue pixel in the top left corner of the image. 此过程的预期结果应在图像的左上角产生一个蓝色像素。 However the neighboring 3 pixels have seemed to "blur" with the pixel value I set. 但是,相邻的3个像素似乎与我设置的像素值“模糊”。

If anyone knows why this blurring of pixels is happening I'd very much appreciate any help I can get. 如果有人知道为什么会出现这种像素模糊,我将非常感谢我能提供的任何帮助。

It turns out the problem was in the image file format. 原来问题出在图像文件格式。 I was outputting the image as .jpg which was modifying pixels. 我将图像输出为.jpg ,这正在修改像素。 When changing the file type to .png this problem was corrected. 将文件类型更改为.png此问题已得到纠正。

Here is my code now with prints to the console of the original image before outputting to a file as well as after re-reading in the file that was output. 这是我的代码,现在在输出到文件之前以及重新读取输出的文件之后,具有打印到原始图像的控制台的代码。

// 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM