c++ - 将 PPM 图像转换为灰度 C++

标签 c++ pointers grayscale ppm

尝试通过索引包含像素数据的指针将 PPM 图像转换为灰度:

void PPMObject::greyScale()
{
    const float r = 0.299F;
    const float g = 0.587F;
    const float b = 0.114F;

    int size = this->width * this->height * 3;
    for (int i = 0; i < size; i++)
    {
        this->m_Ptr[i] = (this->m_Ptr[i] * r) + (this->m_Ptr[i] * g) + (this->m_Ptr[i] * b);
        this->m_Ptr[i+1] = (this->m_Ptr[i+1] * r) + (this->m_Ptr[i+1] * g) + (this->m_Ptr[i+1] * b);
        this->m_Ptr[i+2] = (this->m_Ptr[i+2] * r) + (this->m_Ptr[i+2] * g) + (this->m_Ptr[i+2] * b);
    }
}

在我使用 >> 重载读取 PPM 图像文件的地方:

istream& operator >>(istream &inputStream, PPMObject &other)
{
    inputStream >> other.magicNum >> other.width >> other.height >> other.maxColorValue;
    inputStream.get();
    size_t size = other.width * other.height * 3;
    other.m_Ptr = new char[size];
    inputStream.read(other.m_Ptr, size);
    return inputStream;
}

我写的数据如下:

ostream& operator <<(ostream &outputStream, const PPMObject &other)
{
    outputStream << other.magicNum  << " "
    << other.width          << " "
    << other.height         << " "
    << other.maxColorValue  << " "
    ;   
    outputStream.write(other.m_Ptr, other.width * other.height * 3);
    return outputStream;
}

读写PPM文件没有问题。

问题只是将 PPM 图像转换为灰度——索引不是方法。该文件未更改。

问题很可能是:如何从指针获取值来操作它们?

例如,字符指针中的像素位于何处?

平均 RGB 分量值当然是另一种方法,但我如何将平均值分配回指针?

最佳答案

在您的 greyScale() 函数中,您需要在每次执行循环时将 i 递增 3,因为每个像素占用 3 个字节并且您一次处理一个像素:

for (int i = 0; i < size; i+=3)

此外,您当前使用的公式将使值保持不变(忽略舍入和浮点错误)。

这个:

this->m_Ptr[i] = (this->m_Ptr[i] * r) + (this->m_Ptr[i] * g) + (this->m_Ptr[i] * b);

简化为:

 this->m_Ptr[i] = (this->m_Ptr[i] * 1.0F);

正确的公式是这样的(忽略转换并假设数据是 RGB 顺序):

for (int i = 0; i < size; i+=3)
{
    float greyscaleValue = (this->m_Ptr[i] * r) + (this->m_Ptr[i+1] * g) + (this->m_Ptr[i+2] * b);
    this->m_Ptr[i] = greyscaleValue;
    this->m_Ptr[i+1] = greyscaleValue;
    this->m_Ptr[i+2] = greyscaleValue;
}

关于c++ - 将 PPM 图像转换为灰度 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28923676/

相关文章:

c++ - 如何在 EC2 上对 OpenGL 进行单元测试

c++ - Qt3D 应用程序在按下任何按钮时触发系统声音

c++ - 带有单独 TU 的 x3 链接器错误

C、 Camel 文转蛇文

c++ - 如何 const 声明作为参数发送的 this 指针

c++ - 在 C++ 中生成和重用唯一 ID

c - MPI_Reduce 是否需要接收缓冲区的现有指针?

c++ - (C++) 奇怪的位图问题 - 灰度颜色

image - 为什么 imagesc 会改变颜色图 (MATLAB)

python - 将多个numpy图像转换为灰度