Image merging in C

Viewed 46

I want to create a new image by merging two images.

My idea behind merging

Every image has 3 channels, red, green, blue. So, I want to pickup one red pixel of 1st image and and one red pixel of 2nd image and find out the average of them. The same process will be applicable to green and blue channels. I will also use loop so that I can find the average of all pixel and store them in another image pointer. Then I will display the 3rd image.

The code block for that

#include <stdio.h>
#include <stdlib.h>

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
int main() {

    int width, height, channels;
     //read image using stbi_load function
     unsigned char *apple = stbi_load("apple.jpg", &width, &height, &channels, 0);
     unsigned char *orange = stbi_load("orange.jpg", &width, &height, &channels, 0);

     size_t img_size = width * height * channels;
     size_t new_img_size = width * height * channels;
     unsigned char *new_img = malloc(new_img_size);
     for(unsigned char *p = apple, *q = orange, *pg = new_img; p != apple + img_size && q!=orange + img_size; p += channels , q += channels, pg+=channels) {
        
         *pg       = (unsigned char) (*p + *q)/2;         
         *(pg + 1) = (unsigned char)  (*(p+1) + *(q+1))/2;       
        *(pg + 2) = (unsigned char) (*(p+2)+*(q+2))/2;
     }
     stbi_write_jpg("new_image.jpg", width, height, channels, new_img, 100);
}

So, here I took three pointers *p, *q and *pg. *p loop over the apple image, *q loop over the orange image and *pg is the pointer of the output image. *pg = (unsigned char) (*p + *q)/2; in this line I find out the average from two input images for 1st channel and store it in the output image. Same thing is replicated for 2nd and 3rd channel.

My goal is to merge the two images. However, the output image is only the image of the 1st input image of different color.

Output enter image description here

Input images:

enter image description here

enter image description here

I think there are some logical errors in my code that I could not figure out. Any help should be appreciated.

0 Answers
Related