nolimits
nolimits

Reputation: 83

Loading image but nothing stored in its array (C++, stbi_load)

I want to display the values in the loaded 8 bit image for code analysis purpose and find that the loaded image has no values?

I have the following primary lines to help me:

#define CHANNEL_NUM 1 
int width, height, bpp;

uint8_t* image = stbi_load("FTTESTGS.bmp", &width, &height, &bpp, CHANNEL_NUM);
if (image == NULL) {printf("Error in loading the image\n");}

size_t n = sizeof(image) / sizeof(image[0]);
std::cout << "The size is " << n << '\n';

for (size_t i = 0; i < n; i++) {std::cout << image[i];}

std::cout << '\n' << "The largest element is " << *std::max_element(image, image + width * height) << '\n';

It compiles. No errors. My output is unfortunately showing me size of 8, no values, and the largest element is nothing.

The size is 8

The largest element is  

I am not sure where the problem lays. Any suggestions are welcomed! Here's a screenshot of the code:

enter image description here

Upvotes: 2

Views: 1998

Answers (1)

Kelemen M&#225;t&#233;
Kelemen M&#225;t&#233;

Reputation: 487

stb_image is written in C and so it relies on C arrays instead of the handy standard containers of C++. It looks like you don't have much experience with C arrays, so I suggest you read up on them.


As for the problem at hand, @paddy already mentioned that sizeof doesn't exactly do what you think it does. stbi_load allocates an array on the heap internally, loads the image data to it, and returns a pointer to the first element of that array. Since image is just a pointer (you even declared it as such), sizeof(image) gives you the size of a pointer in bytes (8 on a 64bit system).

As far as I know, you can't get the size of an array allocated in such a way but that's why stbi_load gives you the width and height of the loaded image:

size_t n = width * height * CHANNEL_NUM;

Another issue pointed out by @paddy is that couting an uint8_t will result in a character getting printed. You can read up on it here but long story short: a couple of unfortunate quirks in C++ lead to some integer types (int8_t and uint8_t) getting interpreted as chars (char and unsigned char). To avoid this, you have to explicitly cast them to an integer type that always behaves as an integer (```unsigned int`` for example) when printing. Check this out to see what I mean.

static_cast<unsigned int>( image[i] );

Upvotes: 3

Related Questions