diff --git a/pipi/context.c b/pipi/context.c index 666c4e4..23cc941 100644 --- a/pipi/context.c +++ b/pipi/context.c @@ -304,6 +304,26 @@ int pipi_command(pipi_context_t *ctx, char const *cmd, ...) pipi_free(src); ctx->images[ctx->nimages - 1] = dst; } + else if(!strcmp(cmd, "threshold")) + { + pipi_image_t *src, *dst; + char const *arg; + va_list ap; + double val; + + if(ctx->nimages < 1) + return -1; + va_start(ap, cmd); + arg = va_arg(ap, char const *); + va_end(ap); + val = atof(arg); + src = ctx->images[ctx->nimages - 1]; + dst = pipi_threshold(src, val); + if(dst == NULL) + return -1; + pipi_free(src); + ctx->images[ctx->nimages - 1] = dst; + } else if(!strcmp(cmd, "mean")) { pipi_image_t *dst; diff --git a/pipi/filter/color.c b/pipi/filter/color.c index 30806cf..14eb28c 100644 --- a/pipi/filter/color.c +++ b/pipi/filter/color.c @@ -243,3 +243,47 @@ pipi_image_t *pipi_invert(pipi_image_t *src) return dst; } +pipi_image_t *pipi_threshold(pipi_image_t *src, double val) +{ + pipi_image_t *dst; + pipi_pixels_t *srcp, *dstp; + float *srcdata, *dstdata; + int x, y, w, h, gray; + + w = src->w; + h = src->h; + + gray = (src->last_modified == PIPI_PIXELS_Y_F); + + srcp = gray ? pipi_getpixels(src, PIPI_PIXELS_Y_F) + : pipi_getpixels(src, PIPI_PIXELS_RGBA_F); + srcdata = (float *)srcp->pixels; + + dst = pipi_new(w, h); + dstp = gray ? pipi_getpixels(dst, PIPI_PIXELS_Y_F) + : pipi_getpixels(dst, PIPI_PIXELS_RGBA_F); + dstdata = (float *)dstp->pixels; + + for(y = 0; y < h; y++) + { + for(x = 0; x < w; x++) + { + if(gray) + { + dstdata[y * w + x] = srcdata[y * w + x] < val ? 0. : 1.; + } + else + { + int d = 4 * (y * w + x); + + dstdata[d] = srcdata[d] < val ? 0. : 1.; + dstdata[d + 1] = srcdata[d + 1] < val ? 0. : 1.; + dstdata[d + 2] = srcdata[d + 2] < val ? 0. : 1.; + dstdata[d + 3] = srcdata[d + 3] < val ? 0. : 1.; + } + } + } + + return dst; +} + diff --git a/pipi/pipi.h b/pipi/pipi.h index 9ce37ba..865a644 100644 --- a/pipi/pipi.h +++ b/pipi/pipi.h @@ -126,6 +126,7 @@ extern pipi_image_t *pipi_brightness(pipi_image_t *, double); extern pipi_image_t *pipi_contrast(pipi_image_t *, double); extern pipi_image_t *pipi_autocontrast(pipi_image_t *); extern pipi_image_t *pipi_invert(pipi_image_t *); +extern pipi_image_t *pipi_threshold(pipi_image_t *, double); extern pipi_image_t *pipi_median(pipi_image_t *, int); extern pipi_image_t *pipi_median_ext(pipi_image_t *, int, int); extern pipi_image_t *pipi_dilate(pipi_image_t *); diff --git a/src/pipi.c b/src/pipi.c index 664e9e3..96ad731 100644 --- a/src/pipi.c +++ b/src/pipi.c @@ -112,6 +112,14 @@ int main(int argc, char *argv[]) if(pipi_command(ctx, "invert") != 0) return EXIT_FAILURE; } + else if(!strcmp(argv[0], "--threshold")) + { + if(argv[1] == NULL) + return EXIT_FAILURE; + if(pipi_command(ctx, "threshold", argv[1]) != 0) + return EXIT_FAILURE; + argv++; + } else if(!strcmp(argv[0], "--dilate")) { if(pipi_command(ctx, "dilate") != 0)