PDA

View Full Version : Exception (crash) when accessing QImage pixel



TheJim01
19th February 2010, 20:32
I'm still learning Qt, so as an exercise (and a tool for an upcoming project) I'm building a simple histogram widget. It's throwing an exception as it's parsing the image data, and I have no idea what could be causing it. I'm using 4.6.1 in XP Pro SP3.
void Histogrammer::analyzeImage(QImage *original)
{
// histogramData is a member variable -- an int array of size 256
initializeHistogramData(); // initializes the array to zeroes

for(int row = 0; row < original->height(); row++)
{
for(int col = 0; col < original->width(); col++)
{
histogramData[(QColor(original->pixel(row, col)).red() + QColor(original->pixel(row, col)).green() + QColor(original->pixel(row, col)).blue()) / 3]++;
}
}
}
I put the widget into a MainWindow application, and compile it (WidgetTester.exe). This works. ...for the first 10 pixels.

My image is 30px wide by 10px tall, and is a standard 24-bit Windows bitmap (I load my QImage using the "BMP" format as well). I put debug outputs into the code, and can confirm that it detects the dimensions correctly. I also put debug outputs in to detect the row/column it was currently working on, and can confirm it is scanning the first row, from left to right.

When it attempts to read the pixel at (0, 10), it throws:
An unhandled win32 exception occurred in WidgetTester.exe [3304]If I open the debugger (VS2008), I see:
Unhandled exception at 0x00000001 in WidgetTester.exe: 0xC0000005: Access violation reading location 0x00000001.I've parsed images in this way before, so I don't know why it would be complaining now. I have all the same rights to the image file that I'm using, as all of the previous images I've used.

Since this isn't the first time I've read pixels from a QImage, and trying a different image had the same effect, I figured it must be the array. I tried different ways of incrementing the histogramData entry (object += 1, and object = object + 1), but it still throws the same errors. It can't be going outside the bounds of the array, because--as a bitmap--the image's pixels have a maximum value of (255, 255, 255), which (obviously) averages to 255.

Could it be a problem with my runtime? Should I try re-installing Qt? Could it be a problem with threading (which I'm not messing with right now)? Can you tell I'm grasping at straws?

P.S. On Linux, the app just crashes, saying the application finished unexpectedly with a return code of 0.

Lykurg
19th February 2010, 20:56
You have to swap row and col! And using QImage::bits() is faster than using two for loops and QImage::pixel().

TheJim01
19th February 2010, 21:53
Oh boy, I feel dumb. Can you tell it has been a long week?

Thank you for the tip on QImage::bits. I didn't see that one, and it will definitely make parsing the data easier.