Qt中的图像转换器,彩色图像为黑白色

dep*_*oul 3 c++ qt

我正在尝试制作一个简单的程序,将彩色图像转换为黑白图像.

到目前为止,我已经做到了.

void ObradaSlike::convert_picture_to_bw()
{
    QImage image;
    image.load(fileModel->fileInfo(listView->currentIndex()).absoluteFilePath());

    QSize sizeImage = image.size();
    int width = sizeImage.width(), height = sizeImage.height();

    QRgb color;
    int value;

    for (int f1=0; f1<width; f1++) {
        for (int f2=0; f2<height; f2++) {
            color = image.pixel(f1, f2);
            image.setPixel(f1, f2, QColor((qRed(color) + qGreen(color) + qBlue(color))/3).rgb());
        }
    }
    sceneGraphics->clear();
    sceneGraphics->addPixmap(QPixmap::fromImage(image));
}
Run Code Online (Sandbox Code Playgroud)

我认为代码应该可以工作,但是存在问题.

这段代码的问题在于我总是得到黑白图像.你知道怎么解决这个问题.

谢谢.

Wil*_*ean 8

试试这个:

int gray = qGray(color);
image.setPixel(f1, f2, qRgb(gray, gray, gray));
Run Code Online (Sandbox Code Playgroud)

请注意,qGray()实际上使用公式计算亮度(r*11 + g*16 + b*5)/32.

如果你想获得正常平均值,就像你现在想做的那样:

int gray = (qRed(color) + qGreen(color) + qBlue(color))/3;
image.setPixel(f1, f2, qRgb(gray, gray, gray));
Run Code Online (Sandbox Code Playgroud)