Search code examples
c++qtgrayscaleqimagepixel-manipulation

Qt - displaying unsigned char after pixel manipulation


I'm trying to display my manipulated pixels (gray scale them) which is represented as unsigned char unsuccefully.

Here is the code:

#include "mainwindow.h"
#include <QApplication>
#include "qimage.h"
#include <QImage>
#include <QLabel>
#include <QColor>
#include "qcolor.h"
#include <Qdebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    int height;
    int width;
    unsigned char *p, *p_begin;
    QImage img("C:\\Users\\Owner\\Pictures\\2013-09-26\\IMG_0836.JPG");
    height = img.height();
    width = img.width();

    p = (unsigned char *)malloc(height * width * sizeof(unsigned char));
    p_begin = p;

    for (int row = 0; row < height; ++row)
    {
        for (int col = 0; col < width; ++col)
        {
            QColor clrCurrent( img.pixel( col, row ));
            *p = (unsigned char)((clrCurrent.green() * 0.587) + (clrCurrent.blue() * 0.114) + (clrCurrent.red() * 0.299));
            p++;
        }
    }

    p = p_begin;
    for ( int row = 0; row < height; ++row )
    {
        for (int col = 0; col < width; ++col)
        {
            QColor clrCurrent(img.pixel(col, row));

            clrCurrent.setBlue((int)(*p));
            clrCurrent.setGreen((int)(*p));
            clrCurrent.setRed((int)(*p));
            p++;
        }

    }
    QLabel myLabel;
    myLabel.setPixmap(QPixmap::fromImage(img));
    myLabel.show();

    return a.exec();
}

I dont really know why but the picture which represented is the original picture and not the manipulated one, which should be gray scaleded. I tried to find over the net with no luck, any ideas? Thx in advance.


Solution

  • This part of code:

    QColor clrCurrent(img.pixel(col, row));
    
    clrCurrent.setBlue((int)(*p));
    clrCurrent.setGreen((int)(*p));
    clrCurrent.setRed((int)(*p));
    p++;
    

    doesn't change img. It just take pixel color to temporary object, change that object, then this object is just destroyed without influence to the image.

    I recommend you to check function scanLine of QImage. And then change color of pixels in one for loop on the place. This will works much faster and will change image.