当前位置:网站首页>Image pixel read / write operation

Image pixel read / write operation

2022-07-07 12:46:00 When will we get ashore?

The sample code is as follows :

void demo::pixel_demo(Mat &image)
{
    int w = image.cols;
    int h = image.rows;
    int dims = image.channels();
    for (int i = 0; i < h; i++)
    {
        for (int j = 0; j < w; j++)
        {
            if (dims == 1)// Grayscale image
            {
                int p = image.at<uchar>(i, j);
                image.at<uchar>(i, j) = 255 - p;
            }
            if (dims == 3)// Color images
            {
                Vec3b g = image.at<Vec3b>(i, j);
                image.at<Vec3b>(i, j)[0] = 255 - g[0];
                image.at<Vec3b>(i, j)[1] = 255 - g[1];
                image.at<Vec3b>(i, j)[2] = 255 - g[2];
            }
        }
    }
    imshow(" Pixel image ", image);
}

This time is mainly for further study Mat( matrix )

adopt image.at<uchar>(i,j) Images can be obtained image In position (i,j) The pixel size of , Because gray image pixels have only one value ,uchar It means a unsigned char Size .

stay opencv in Vec3b A list of three numbers , Also exist Vec3i and Vec3f.

give the result as follows :

Here is how to change pixels by pointer

void demo::pixel_demo(Mat &image)
{
    int w = image.cols;
    int h = image.rows;
    int dims = image.channels(); 

for (int i = 0; i < h; i++)
    {
        uchar*p = image.ptr<uchar>(i);
        for (int j = 0; j < w; j++)
        {
            if (dims == 1)
            {
                *p++ = 255 - *p;// First assign and then add
            }
            if (dims == 3)
            {
                *p++ = 255 - *p;// First assign and then add
                *p++ = 255 - *p;// First assign and then add
                *p++ = 255 - *p;// First assign and then add
            }
        }
    }
    imshow(" Pixel image ", image);

}

The result is the same :

over!!! 

原网站

版权声明
本文为[When will we get ashore?]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071032234963.html