Incredibly concise shape sorter

// shapesorter.c - Identifies the type of blob in a PGM file
// written by Ted Burke - last modified 21-11-2011

#include <stdio.h>

int main(int argc, char *argv[])
	FILE *f;
	char line[200];
	int n=0,w,h,x,y,th=150,bp=0,ym,xm,histogram[256]={0},p[400][640]; // declare variables
	if(argc > 1) f=fopen(argv[1],"r"); else f=fopen("input.pgm","r"); // open input file
	fscanf(f,"%[^\n]\n%[^\n]\n%d %d\n%[^\n]\n",line,line,&w,&h,line); // read file header
	for(y=0;y<h;++y) for(x=0;x<w;++x) histogram[fscanf(f,"%d",&p[y][x])*p[y][x]]++; // read pixels
	fclose(f); f=fopen("histogram.csv", "w"); // close input file and open histogram file
	for(x=0;x<256;++x) fprintf(f,"%d, %d\n",x,histogram[x]); fclose(f); // print histogram data
	for(y=0;y<h;++y) for(x=0;x<w;++x) if(p[y][x]<=th) ++bp; // count dark pixels
	for(y=0;y<h;++y) for(x=0;x<w;++x) if((n+=(p[y][x]<=th))==bp/2) ym=y; // find centre y
	for(x=0;x<w;++x) for(y=0;y<h;++y) if((n-=(p[y][x]<=th))==bp/2) xm=x; // find centre x
	for(y=ym-10;y<ym+10;++y) for(x=xm-10;x<xm+10;++x)
		p[y][x]=255*((y<ym||(y==ym&&x<=xm))==(p[ym][xm]<=th)); // draw square
	if(argc > 2) f=fopen(argv[2],"w"); else	f=fopen("output.pgm","w"); // open output file
	fprintf(f, "P2\n# PGM blob file\n%d %d\n255\n", w, h); // print file header
	for(y=-1;++y<h;fprintf(f,"\n")) for(x=0;x<w;++x) fprintf(f,"%d ",p[y][x]); // print pixel data
	fclose(f); // close output file
	return 0; // exit normally
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s