FloatImg4PythonBinding/funcs/histogram.c

91 lines
1.9 KiB
C

/*
* FLOATIMG
* calculer un histogramme et l'afficher
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../floatimg.h"
extern int verbosity;
/* --------------------------------------------------------------------- */
int fimg_calcul_histo(FloatImg *src, long *ghist, int sz)
{
float maxval;
int x, y, idx;
float rgb[3], moy;
#if DEBUG_LEVEL
fprintf(stderr, ">>> %s ( %p %p %d )\n", __func__, src, ghist, sz);
#endif
maxval = fimg_get_maxvalue(src);
fprintf(stderr, "maximum is %f\n", maxval);
for (y=0; y<src->height; y++) {
for(x=0; x<src->width; x++) {
fimg_get_rgb(src, x, y, rgb);
moy = (rgb[0]+rgb[1]+rgb[2]) / 3.0;
/* ok, here the had math part ... */
idx = (int)( (moy*sz) / maxval);
/* sanity check */
if (idx<0 || idx>=sz) {
fprintf(stderr, "idx = %d, error\n", idx);
abort();
}
ghist[idx]++;
}
}
return -66;
}
/* --------------------------------------------------------------------- */
int fimg_essai_histo(FloatImg *src, char *outpic, int nbslices)
{
long *histo;
int foo;
FILE *pipe;
fprintf(stderr, ">>> %s ( %p '%s' %d )\n", __func__, src, outpic, nbslices);
if (NULL==(histo=calloc(nbslices, sizeof(long)))) {
fprintf(stderr, "OUT OF MEMORY\n");
abort();
}
foo = fimg_calcul_histo(src, histo, nbslices);
// for (foo=0; foo<NSLICES; foo++) {
// printf("%7d %ld\n", foo, histo[foo]);
// }
pipe = popen("gnuplot", "w");
if (NULL==pipe) {
fprintf(stderr, "%s: error running gnuplot\n", __func__);
return -17;
}
fprintf(pipe, "set term png size 1024,512\n");
fprintf(pipe, "set grid\n");
fprintf(pipe, "set output \"%s\"\n", outpic);
fprintf(pipe, "plot '/dev/stdin' with lines\n");
for (foo=0; foo<nbslices; foo++) {
fprintf(pipe, "%d %ld\n", foo, histo[foo]);
}
pclose(pipe); // and not fclose (see man page)
free(histo);
return 0;
}
/* --------------------------------------------------------------------- */