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. 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.

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.

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. When changing the file type to .png this problem was corrected.

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;
链接地址: http://www.djcxy.com/p/15880.html

上一篇: linq查询其中int ID属于List <int>

下一篇: 设置彩色像素的Opencv最终会模糊相邻像素