Plan 9 from Bell Labs’s /usr/web/sources/contrib/maht/imgfs/convolute.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


#include <u.h>
#include <libc.h>
#include <bio.h>
#include <ndb.h>
#include <fcall.h>
#include <thread.h>
#include <9p.h>
#include <draw.h>


#include "mapbook.h"

#include "ifslib.h"
#include "import_ppm.h"
#include "convolute.h"
#include "imgfs.h"

void
print_convolution(Conv *c) {
	int i, j, k;
	k = 0;
	for(i = 0; i < c->h; i++) {
		for(j = 0; j < c->w; j++) {
			print("%0.3f	", c->v[k++]);
		}
		print("\n");
	}
}

Conv *
parse_conv(char *size, char *values) {
	Conv *c;
	char *wh[2];
	int nc = 0;

	c = (Conv*)mallocz(sizeof(Conv), 1);

	if(2 == getfields(size, wh, 2, 0, "x")) {
		c->w = atoi(wh[0]);
		c->h = atoi(wh[1]);
		nc = c->w * c->h;
	}
	if(!(nc > 0)) {
		c->error = "Convolution WxH invalid";
		return c;
	}

	c->v = (double*)calloc(sizeof(double), nc);
	char **tokens = (char**)calloc(sizeof(char*), nc);

	if(nc != getfields(values, tokens, nc, 1, "\t ")) {
		c->error = "Incorrect number of convolution values supplied";
		return c;
	}

	int i;
	for(i = 0; i < nc; i++)
		c->v[i] = atof(tokens[i]);

	free(tokens);

	return c;	
}


char *
convolute(Aux *aux, int id, char *size, char *values) {
	char *error;
	Conv *c = parse_conv(size, values);
	if(c->error) {
		error = strdup(c->error);
		free(c);
		return error;
	}

	int x, y, px, py, srcy, cy;
	int i, j, m, n;
	double d, pv;
	Bitmap *src = get_bitmap(aux->mapbook, id);
	Bitmap *blank = blank_bitmap(aux->mapbook);

	for(y = 0; y < aux->mapbook->height; y++) {
		srcy = y * aux->mapbook->width;
		for(x = 0; x < aux->mapbook->width; x++) {
			d = 0;
			pv = 0;
			for(i = 0, m = -(c->h/2); i < c->h; i++, m++) {
				py = y + m;
				cy = i * c->w;
				if(py >= 0 && py < aux->mapbook->height) 
					for(j = 0, n = -(c->w/2); j < c->w; j++, n++) {
						px = x + n;
						if(px >= 0 && px < aux->mapbook->width) {
							pv += c->v[cy + j] * src->data[py * aux->mapbook->width + px];
							d += c->v[cy + j];
						}
					}
			}
			if(d > 0)
				pv /= d;
			blank->data[srcy + x] = min_int(255, pv);
		}
	}
	
//	free(src->data);
	src->data = blank->data;
//	free(blank);

	return nil;
}


Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to [email protected].