Ali
Ali

Reputation: 33

Convert pixel data to image in C++

I have a program that generates an 8-bit image with the following structure:

struct int8image
{
  int width;
  int height;
  unsigned char* image;
};

Upon dumping the pixel data (int8image.image) to a text file, I got this output:

0605 0606 0606 0605 0606 0506 0606 0606
0606 0605 0606 0506 0606 0606 0606 0606
0606 0606 0606 0606 0606 0505 0606 0706
0606 0606 0606 0606 0606 0606 0706 0706
.....

How would I go about converting this into a view-able image (the format doesn't matter)?

Upvotes: 1

Views: 3886

Answers (4)

Mark Setchell
Mark Setchell

Reputation: 207375

You can convert the image with ImageMagick at the command line. It is installed on most Linux distros and available for OS X (ideally via homebrew) and also Windows.

If you want to convert it to a PNG, you can run this:

convert -size 1392x1040 -depth 8 image.gray -auto-level image.png

enter image description here

Your image is very low contrast, so I added -auto-level to stretch it. Your image is greyscale.

You can also achieve the same processing with the ImageMagick C++ library here.

Upvotes: 2

Shepard
Shepard

Reputation: 811

Another alternative is to use the LodePNG library, it is very easy to setup because it has no dependencies, you can simply put the source files into your project and compile with it. It is very easy to use and allows you to save that data into a loseless PNG image.

Upvotes: 0

mark
mark

Reputation: 5459

A library is most flexible, but if you're looking for quick and dirty, you can write out a simple 54-byte BMP header for RGB24 and assuming your data is gray scale, simply repeat the octet for each of the 3 components of each pixel. Or if you want to be able to write the image data a bit more directly, write the BMP header for a palletized image, and your pallet is essentially the 256-entry gray scale (000000,010101,020202...ffffff). Pretty straightforward either way if you look up the BMP header format.

Upvotes: 0

RyanP
RyanP

Reputation: 1918

I would use OpenCV. You can convert your structure to a cv::Mat using width and height as dimensions. Then you can use OpenCV functions to view the image or write out a bmp, png, tiff, or jpg fairly easily. Given that you have unsigned char data, I assume it is already 8-bit grayscale so it'd look like this.

int8image testData;

// Do stuff in your program so that testData contains an image.

// Define a cv::Mat object with a pointer to the data and the data type set
// as "CV_8U" which means 8-bit unsigned data
cv::Mat image( testData.height, testData.width, CV_8U, testData.image );

// Write the image to a bitmap in the current working directory named 
// "test.bmp". This is just an example of one way you could write it out.
cv::imwrite( "test.bmp", image );

Upvotes: 1

Related Questions