Convert QImage into binary Matrix
Unsolved
General and Desktop
-
char **matrix = new char* [image.width()]; for(int i=0;i<image.width();++i) matrix[i] = new char [image.height()]; for(int i=0;i<image.width();++i){ for(int j=0;j<image.height();++j) matrix[i][j] = QColor(image.pixel(i,j)).black() > 127 ? 0:1; }
Remember to delete the matrix to avoid memory leak or use something like QScopedArrayPointer
-
@VRonin Thanks a lot for answering me my friend.
Now I would like to write the image in a txt.
i do this:QString outputFilename = QFileDialog::getSaveFileName(this, "Guardar TXT", "/home", "files TXT (*.txt)"); QFile outputFile(outputFilename); outputFile.open(QIODevice::WriteOnly); if(!outputFile.isOpen()) //If the user have choosen a file then: { // } /* Point a QTextStream object at the file */ QTextStream outStream(&outputFile); outStream << &matrix;
but it writes just the memory direction, not the matrix... coudl you help me?
-
@AlvaroS The answer requires you to specify the format of the file, I'll use a MS Excel compatible one:
QTextStream outStream(&outputFile); for(int i=0;i<image.width();++i){ for(int j=0;j<image.height();++j){ if(j>0) outStream << '\t'; outStream << matrix[i][j]; } outStream << '\n'; }
Remember to delete the matrix!!!
-
-
Well, you can: you can treat matrix as an one-dimentional array.
-
Something like (didn't test):
for(int i=0;i<(image.width() * image.height()) / 8; ++i) quint8 byte = 0; for (j=0; j < 8; ++j) { byte |= (matrix[i*8 + j] ? 1 : 0)<<(7-j); } // Write byte to file // Don't forget to write (image.width() * image.height()) % 8 last pixels
-
slightly more refined solution using the fact that QImage uses "a matrix" internally
QDataStream outStream(&outputFile); outStream << image.height()<< image.width(); /* You need this to recover the image size, if not needed remove*/ QImage testImage= image.convertToFormat(QImage::Format_Mono,Qt::MonoOnly); /* 1 bit= 1 pixel*/ testImage.invertPixels(); /* black is 1 and white is 0 normally, you need the opposite so invert*/ const int bytesInWidth = testImage.width()/8 + (testImage.width()%8>0 ? 1:0); /*This is image.width()/8 rounded up */ for(int i=0;i<testImage.height();++i) outStream.writeRawData((const char*)(testImage.constScanLine(i)),bytesInWidth);