Skip to content

Instantly share code, notes, and snippets.

@serg06
Last active January 21, 2020 20:40
Show Gist options
  • Save serg06/bef17f8661c7d5496c5457ae58b30a10 to your computer and use it in GitHub Desktop.
Save serg06/bef17f8661c7d5496c5457ae58b30a10 to your computer and use it in GitHub Desktop.
Little C program for making bright pixels in a .png file transparent. Useful for cleaning up a picture of a document. TODO: Maybe a fragment-deletion filter and a smoothing filter.
// Image-read library
// https://github.com/nothings/stb/blob/master/stb_image.h
#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_PNG
#include "stb_image.h"
// Image-write-library
// https://github.com/nothings/stb/blob/master/stb_image_write.h
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#include <stdio.h>
const char default_fname_in[] = "signature-in.png";
const char default_fname_out[] = "signature-out.png";
const float default_light_limit = 0.5;
int main(int argc, char** argv) {
char *fname_in;
char *fname_out;
float light_limit;
// get args
if (argc == 1) {
fname_in = default_fname_in;
fname_out = default_fname_out;
light_limit = default_light_limit;
}
else if (argc == 4) {
fname_in = argv[1];
fname_out = argv[2];
light_limit = atof(argv[3]);
}
else {
printf("Usage: ./executable [in.png, out.png, lightlimit (in [0.0, 1.0])]\n");
printf("Ex: ./executable signature-in.png signature-out.png 0.5\n");
exit(-1);
}
// print args
printf("Input file: %s\n", fname_in);
printf("Output file: %s\n", fname_out);
printf("Light limit: %f\n", light_limit);
// load image
int width, height, components;
unsigned char* image = stbi_load(fname_in, &width, &height, &components, 4);
if (image == NULL) {
printf("Unable to open file %s.\n", fname_in);
exit(-1);
}
// edit image
for (int i = 0; i < width*height; i++) {
// get pixel
unsigned char* pixel = image + i * 4;
// if pixel's too bright, make it invisible
if ((pixel[0] + pixel[1] + pixel[2]) / (float)(255 * 3) > light_limit) {
pixel[3] = 0;
}
}
// write it to output
stbi_write_png(fname_out, width, height, components, image, width * components);
// free
stbi_image_free(image);
printf("done!\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment