Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

how to knoe the pixel value of a QImage or QPixmap



  • hello everyone.
    First of all thanks a lot for reading this post and being able to help.

    I would like to sve an image with pixel values from a QImage.

    My code looks like this:

                QImage img1(path_name_image); //Image creation //Ver como hacer con variable global.
    
                //Create matrix where each element will be a pixel value.
                matrix = new int *[img.width()];
    
                for(int i=0;i<img.width();++i)
                    matrix[i] = new int [img.height()];
    
                for(int i=0;i<img.width();++i){
                    for(int j=0;j<img.height();++j){
                        matrix[i][j] = QColor(img.pixel(i,j)).black() > 127 ? 0:1;
                        std::cout<<img1.pixel(i,j)<<std::endl;
                        std::cout<<matrix[i][j]<<std::endl;
                    }
                }
    

    But std::cout gives me values out of 0-256

    I think the problem is that .pixel(i,j) returns the color of the pixel at coordinates (x, y), but coordinates of scene I think....

    How can I get a matrix with pixel values right?


  • Moderators

    @AlvaroS
    you receive values from 0-255 (QRgb) because it returns a 8-bit RGB values (quad-truplets).
    If you want the specific color pass the returned value to QColor constructor or use qAlpha()/qRed()/qBlue()/... etc. on the value.



  • You can try using QImage::pixelColor()
    http://doc.qt.io/qt-5/qimage.html#pixelColor



  • @AlvaroS said:

    My code looks like this:

                QImage img1(path_name_image); //Image creation //Ver como hacer con variable global.
                        matrix[i][j] = QColor(img.pixel(i,j)).black() > 127 ? 0:1;
                        std::cout<<img1.pixel(i,j)<<std::endl;
    

    What is img? you declare only img1

    currently cout will print the QRgb Value of the colour and matrix will contain 1 if the pixel "blackness" (black component of cmyk encoding) is less than 50% or 0 otherwise

    @AlvaroS said:

    I think the problem is that .pixel(i,j) returns the color of the pixel at coordinates (x, y), but coordinates of scene I think....

    x and y are coordinates of the image (assuming img is a QImage)


Log in to reply