Skip to content

Instantly share code, notes, and snippets.

@angstyloop
Last active March 7, 2023 00:38
Show Gist options
  • Save angstyloop/7d14dcd9b0bdc57cffb849282a74c354 to your computer and use it in GitHub Desktop.
Save angstyloop/7d14dcd9b0bdc57cffb849282a74c354 to your computer and use it in GitHub Desktop.
Threshold an image with VIPS in C, revised version of threshold.c. Uses a built-in VIPS relational operator instead of thresholding by hand.
/** threshold1.c
*
* COMPILE
*
* gcc -o threshold1 threshold1.c `pkg-config vips --cflags --libs`
*
* EXAMPLE
*
* ./threshold1 128 in.png out.png
*/
#include <vips/vips.h>
int main (int argc, char** argv) {
if (argc != 4) {
printf("USAGE: %s <THRESHOLD (0-255) <INPUT_IMAGE>", argv[0]);
vips_error_exit(NULL);
}
if (VIPS_INIT(argv[0]))
vips_error_exit(NULL);
VipsImage *in, *out;
double threshold = strtod(argv[1], NULL);
if (!(in = vips_image_new_from_file(argv[2],
"access", VIPS_ACCESS_SEQUENTIAL,
NULL)))
vips_error_exit(NULL);
if (vips_colourspace(in, &out, VIPS_INTERPRETATION_B_W, NULL))
vips_error_exit(NULL);
g_object_unref(in);
in = out;
if (vips_extract_band(in, &out, 0, "n", 1, NULL))
vips_error_exit(NULL);
g_object_unref(in);
in = out;
if (vips_moreeq_const1(in, &out, threshold, NULL))
vips_error_exit(NULL);
g_object_unref(in);
in = out;
if (vips_image_write_to_file(in, argv[3], NULL))
vips_error_exit(NULL);
g_object_unref(in);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment