Developing an Image Processing Tool in C Language

Developing an Image Processing Tool in C Language

This article will demonstrate to readers how to develop a simple image processing tool using the C language. The functionalities we will implement include loading images, converting them to grayscale, and saving the processed images. This tutorial is suitable for beginners, and detailed code examples will be provided at the end of the article.

Environment Setup

Before we begin, please ensure that the following software is installed on your computer:

  • C Compiler: such as GCC or MinGW (for Windows users).
  • Image Processing Libraries: We will use the STB Image and STB Image Write libraries to read and save images. Both libraries are very lightweight and easy to use.

You can download the source code for these two libraries from GitHub and include them in your project.

Project Structure

We will create the following files in one directory:

image_processor/├── main.c├── stbi_image.h└── stbi_image_write.h

<span>main.c</span> is our main program file, while the other two header files are used for loading and saving images.

Loading and Saving Images

First, we need to include the necessary header files in <span>main.c</span> and define some basic methods to load and save images.

#include <stdio.h>#include <stdlib.h>#include "stb_image.h"#include "stb_image_write.h"// Function prototypesunsigned char* load_image(const char* filename, int* width, int* height, int* channels);void save_image(const char* filename, unsigned char* image, int width, int height);int main() {    // Main logic can be written here    return 0;}

Load Image Function

unsigned char* load_image(const char* filename, int* width, int* height, int* channels) {    unsigned char *img = stbi_load(filename, width, height, channels, 0);    if (img == NULL) {        printf("Error in loading the image\n");        exit(1);    }    return img;}

This function takes a filename parameter, reads the image, and returns a pointer to the pixel data of the image. It also outputs the width, height, and number of channels (color information).

Save Image Function

void save_image(const char* filename, unsigned char *image, int width, int height) {    if (stbi_write_png(filename, width ,height ,3 ,image ,width * 3)) {        printf("Image saved successfully as %s\n", filename);    } else {        printf("Failed to save the image\n");        exit(1);    }}

This function is responsible for writing the modified image data back to a new file. We choose the PNG format for saving because it supports lossless compression.

Convert Image to Grayscale

Next, we need to implement a method to convert a color image to grayscale. Here is the corresponding code:

void convert_to_grayscale(unsigned char *image_data,                           unsigned char *gray_data,                           int width,                           int height,                           int channels) {    for (int y = 0; y < height; y++) {        for (int x = 0; x < width; x++) {            // Get each color channel value R, G, B             unsigned char r = image_data[(y * width + x) * channels + 0];            unsigned char g = image_data[(y * width + x) * channels + 1];            unsigned char b = image_data[(y * width + x) * channels + 2];            // Calculate grayscale value using weighted average             gray_data[y * width + x] = (unsigned char)(0.299f*r + 0.587f*g + 0.114f*b);        }    }}

Here we calculate the grayscale value for each pixel by applying a weighted average to the RGB color channels. The result is stored in the <span>gray_data</span> array, which is a one-dimensional array where each element represents a pixel in the grayscale image.

Main Program Logic

Finally, add the complete flow in the <span>main()</span> function, including calls to the methods above and how to run the entire program:

int main() {    const char input_filename[] = "input.jpg";    const char output_filename[] = "output.png";    // Variables to store width, height, and number of channels     int img_width,img_height,img_channels;    // Load input image     unsigned char *image_data=load_image(input_filename,&img_width,&img_height,&img_channels);    // Check if the number of channels is correct     if(img_channels<3){        printf("Not a RGB or RGBA image!\n");        exit(1);    }    // Allocate enough space for the output     unsigned char *gray_data=(unsigned char*)malloc(sizeof(unsigned char)*img_width*img_height);    if(gray_data==NULL){        printf("Memory allocation failed!\n");        free(image_data);        exit(1);    }    // Convert to grayscale    convert_to_grayscale(image_data,(unsigned char *) gray_data,img_width,img_height,(size_t ) img_channels );    // Save the result    save_image(output_filename, gray_data, img_width, img_height);    free(image_data);    free(gray_data);    return EXIT_SUCCESS;}

Make sure to replace the input/output file names to match your system paths. When you run this program, it will read “input.jpg” and generate a grayscale image named “output.png”.

When the program execution is complete, you will have a processed image ready for use.

I hope these steps help you get started with simple image processing in C language.

Leave a Comment