c++ - 在数组中设置像素颜色

标签 c++ image-processing pixel

我有一个像素数组存储在一个 vector 中,如下所示:

typedef union RGBA
{
    std::uint32_t Colour;
    struct
    {
        std::uint8_t R, G, B, A;
    };
} *PRGB;

std::vector<RGBA> Pixels;  //My pixels are read into this vector.

我使用以下两个函数对其进行处理。一个用于阅读,另一个用于写作。 读取函数获取一个字节数组并将它们翻转并将它们存储到上面的结构中。它考虑了填充,因此它适用于 24 位和 32 位位图。写入函数将其翻转回来并将其写入字节数组。

void ReadPixels(const std::uint8_t* In, RGBA* Out)
{
    for (std::size_t I = 0; I < height; ++I)
    {
        for (std::size_t J = 0; J < width; ++J)
        {
            Out[(height - 1 - I) * width + J].B = *(In++);
            Out[(height - 1 - I) * width + J].G = *(In++);
            Out[(height - 1 - I) * width + J].R = *(In++);
            Out[(height - 1 - I) * width + J].A = (BitsPerPixel > 24 ? * (In++) : 0xFF);
        }
        if(BitsPerPixel == 24)
            In += (-width * 3) & 3;
    }
}

void WritePixels(const RGBA* In, std::uint8_t* Out)
{
    for (std::size_t I = 0; I < height; ++I)
    {
        for (std::size_t J = 0; J < width; ++J)
        {
            *(Out++) = In[(height - 1 - I) * width + J].B;
            *(Out++) = In[(height - 1 - I) * width + J].G;
            *(Out++) = In[(height - 1 - I) * width + J].R;

            if (BitsPerPixel > 24)
                *(Out++) = In[(height - 1 - I) * width + J].A;
        }
        if(BitsPerPixel == 24)
            Out += (-width * 3) & 3;
    }
}

问题是,如果我只想更改数组中的一个像素,我必须翻转整个图像并将其复制到 vector 中,使用以下方法更改像素:

inline void SetPixel(int X, int Y, std::uint32_t Color)
{
    Pixels[Y * width + X].Colour = Color;
}

然后将其翻转回数组中。有没有更好的方法来更改阵列中的单个像素而不必每次都这样做?

我试过这个公式(以便考虑填充):

ByteArray[((height - 1 - Y) * width + X) + (Y * ((-width * 3) & 3))] = Color;

但它不起作用。有什么想法吗?

最佳答案

你的下标->索引公式看起来全错了。

也许:

int stride = width * BitsPerPixel/8;
stride = ((stride - 1) & ~3) + 4; // round up to multiple of 4 bytes
RGBQUAD& selected_pixel = *reinterpret_cast<RGBQUAD*>(array + stride * (height - 1 - Y)) + X * BitsPerPixel/8);
selected_pixel.R = ...
...

关于c++ - 在数组中设置像素颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20624414/

相关文章:

c++ - 使用 CIMg 和 C++ 进行傅里叶滤波

python - 获取重复轮廓

c++ - 快速访问 jpeg 图像的像素值

cross-browser - Chrome 中的 CSS 像素完美

python-3.x - 如何使用opencv多次更改图像中4个像素的颜色?

python——测量像素亮度

c++ - term 不计算为采用 3 个参数的函数

c++ - 无效使用 void 表达式,怎么办?

c++ - 此代码中的段错误在哪里?

c++ - 将 lambda 作为参数注入(inject)到模板方法中