1

I am working on a mechanism that will allow me to get a two-dimensional array filled with binary data based on constBits() from QImage created with flag QImage::FormatMono.

I expect that square should be something like:

1111
1001
1001
1111

but i get this instead:

0001
0010
0100
1000

I am not quite imagine how to work with memory bit by bit or how to work with MSB-compressed string.

Here is the code that I use to get value of 1 pixel and represent it as binary:

uint ConnectedChecker::pixel(const QImage& img, const int x, const int y) const
{
    const uchar mask = 0x80 >> (x % 8);
    return img.constBits()[x*y / 8] & mask ? 1 : 0;
}

And loop, that i use to fill the array:

int* _in;

for(uint i = 0; i < _rowCount; ++i) {
   for(uint j = 0; j < _columnCount; ++j) {
       *((_in + i*_columnCount) + j) = pixel(image, i, j);
   }
}

1 Answer 1

1

The formula is not correct, you need instead something like

int a = y*img.bytesPerLine();
return (img.constBits()[a + x/8] >> (x & 7)) & 1;

The bytesPerLine() member function is needed to consider the QImage padding that is possibly added at the end of each scan line.

A side note: using an underscore _ at the beginning of identifiers is a bad idea (it can cause technical problems with global identifiers or with uppercase names, for example). It's also damn ugly. Why are you doing that?

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This is a global identifier. Initially declared in the class header. It's used for other operations in the class later.
@MikSer: global identifiers is a case in which a leading underscore is forbidden and can cause subtle problems. If you really really love that ugly underscore then place it at the end of the name rather than at the beginning (and never ever use two of them near each other, that's also forbidden anywhere).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.