Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you turn a .png file into a 2-d matrix?

Tags:

c

png

I am working on a project for a Bio-medical Imaging course (Note: it is a non-programming course, so asking for programming help is not cheating. Asking for conceptual help with planning would be cheating.) where I need to manipulate an image using different mathematical transforms. I am writing in C so it can be as fast as possible. I have finished the code for the mathematical transforms, but I have realized that I do not know how to turn a grayscale .png file into a 2-d matrix/array to compute with, and I do not know how to display a .png file in C. Can anyone help me?

I'm trying to turn the "image.png" image into a 2d array where each entry in the array has a value between 0 - 255 and corresponds with each pixel in "image.png". I also want to turn a 2d array where each entry corresponds to a pixel in the image and has a value between 0 - 255 into a new "image_two.png" file.

I'm a somewhat new programmer. I have a solid base in python programming, but C is new for me. I have done a lot of research and I have found a lot of people talking about using "this library" or "that library", or also "this library", but how do I use a downloaded library in C? It's unfamiliar territory for me as a python programmer :(

I'm using Ubuntu 12.04

To reiterate:

  • How do you read a grayscale .png image as a 2-d array/matrix in C?

  • How do you display a 2-d array/matrix as a grayscale image in C?

  • How do you use a downloaded library in C code (specifically for the two questions above)? I found out how to use these libraries.

EDIT: I am still having trouble figuring out how to create a grayscale 2d array out of a .png file and how to make a .png file out of a grayscale 2d matrix. Can anyone else help?

like image 955
Paul Terwilliger Avatar asked Apr 27 '13 22:04

Paul Terwilliger


2 Answers

You can use a more general purpose image handling library and you might find it easier to use. I recommend FreeImage http://freeimage.sourceforge.net/. See the pixel access section of the manual to get access to the pixel data. You can then work with it directly or copy it into your own matrix.

like image 155
denver Avatar answered Nov 20 '22 22:11

denver


To install a library in Linux, typically you will use the package manager. For example, in Debian (this includes Ubuntu) you might do:

$ apt-cache search libpng

You'll decide which package to install based on the results of running this command and then you will run

$ sudo apt-get install <package-name>

This command will likely install png.h in a location that is already included in gcc's search path. This means that to use png.h in your program, all you have to do is include it.

#include <png.h>

Skip to chapter 3 in the libpng manual for a walkthrough on reading a png file.

like image 30
danmcardle Avatar answered Nov 20 '22 21:11

danmcardle