Converting colored image to black-white image



  • Hello.

    I am trying to make a simple program that converts colored images to black-white images.

    So far I have made this.

    @
    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));
    

    }
    @
    I think the code should work, but there is a problem.

    The problem with this code is that I always get blue-black images insted black-white images. Do you know how to fix this.

    Thanks.


  • Moderators

    Be aware that just averaging R, G, and B doesn't lead to a very nice gray scale conversion. (You're not doing that properly either, given the blue/black thing.) You should use QColor's non-member "qGray()":http://qt-project.org/doc/qt-4.8/qcolor.html#qGray-2 function to give you the gray value you're looking for.

    You could replace lines 14 and 15 above with
    @
    color = image.pixel(f1,f2);
    image.setPixel(f1,f2, qGray(color));
    @



  • I have tried what have you suggested mlong, but I am still getting blue-black images.

    Thanks.



  • Here is the solution:
    @
    int gray = (qRed(color) + qGreen(color) + qBlue(color))/3;
    image.setPixel(f1, f2, qRgb(gray, gray, gray));
    @

    or

    @
    int gray = qGray(color);
    image.setPixel(f1, f2, qRgb(gray, gray, gray));
    @


  • Moderators

    Ah, of course. I was thinking that qGray() returned a QRgb value. (I directed you to the docs, but didn't read them, myself, apparently.)

    Glad you got it working.

    Be sure and edit the original post to add [Solved] to the title. Thanks!



  • Before you work out your own code, why don't you see some others" template code or image processing software":http://www.rasteredge.com/dotnet-imaging/image-convert/.



  • [quote author="Chesterton WORD" date="1361957470"]Before you work out your own code, why don't you see some others" template code or image processing software":http://www.rasteredge.com/dotnet-imaging/image-convert/.[/quote]

    How does one integrate this .net application with a cross-platform Qt application exactly?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.