Code:borders-black-on-white.c

From the change wiki

Generates the image borders-black-on-white.png from raw data countries.data-int16-8640x4320

#define WIDTH 8640
#define HEIGHT 4320
#define IN_FILE "data/countries.data-int16-8640x4320"
#define OUT_FILE "data/borders-black-on-white.png"

#include <stdio.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

int main() {
 short          *in = malloc(WIDTH*HEIGHT*sizeof(short));
 unsigned char *out = malloc(WIDTH*HEIGHT*sizeof(unsigned char));
 if (!in || !out) {
  printf("Not enough memory\n");
  free(in); free(out);
  return 1;
 }
 
 // load data
 printf("Reading %s\n", IN_FILE);
 FILE *f = fopen(IN_FILE,"r");  if (!f) { perror(IN_FILE); return 2; }
 if (!fread(in, sizeof(in[0]), WIDTH*HEIGHT, f)) printf("Input file is incomplete. Output will probably be garbage lol\n");
 fclose(f);
 
 // simplest edge-detection algorithm i can think of lol
 printf("Detecting edges\n");
 int i; for (i=0; i<WIDTH; i++) out[i]=255;
 for (; i<WIDTH*(HEIGHT-1); i++) {
  if (in[i] != in[i+1]
   || in[i] != in[i-1]
   || in[i] != in[i-WIDTH]
   || in[i] != in[i+WIDTH]) out[i]=0;
  else out[i]=255;
 }
 for (; i<WIDTH*HEIGHT; i++) out[i]=255; // top and bottom rows of pixels are ignored, for simplicity sake. The dataset doesn't have edges there anyway.
 
 // write file and done
 int r=0;
 printf("Writing %s\n", OUT_FILE);
 free(in);
 if (!stbi_write_png(OUT_FILE, WIDTH, HEIGHT, 1, out, WIDTH)) { perror(OUT_FILE); r=3; }
 free(out);
 return r;
}