/*------------------------------------------------------------------------
 *
 * Copyright (c) 1997-1998 by Cornell University.
 * 
 * See the file "license.txt" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * sobel.c
 *
 * Steve Weiss sweiss@cs.cornell.edu
 *
 * Performs Sobel edge detection on the input image.  The input image's
 * dimensions must be multiple of 8.
 *
 *------------------------------------------------------------------------
 */
#include <dvmbasic.h>
#include <dvmpnm.h>
#include <dvmvision.h>

void ReadPGM(char *, PnmHdr **, ByteImage **);
void WritePBM8(PnmHdr *, BitImage *, char *);

int main(int argc, char *argv[])
{
    PnmHdr *hdr;
    ByteImage *buf;
    ByteImage *smth, *e1, *e2;
    BitImage *bit1, *bit2, *edge;
    int w, h, t1, t2;

    if (argc != 3) {
        fprintf(stderr, "usage : %s input output\n", argv[0]);
	exit(1);
    }

    ReadPGM (argv[1], &hdr, &buf);
    w = PnmHdrGetWidth (hdr);
    h = PnmHdrGetHeight (hdr);
    
    e1   = ByteNew(w, h);
    e2   = ByteNew(w, h);
    edge = BitNew(w, h);
    bit1 = BitNew(w, h);
    bit2 = BitNew(w, h);
    smth = ByteNew(w, h);

    /*
     * We smooth the image, perform edge detection.  We will get two
     * bit images corresponding to the vertical and horizontal edge
     * respectively.  We then union these two to get the final edge
     * image. 
     */
    ByteSmooth(buf, smth, 2);
    ByteEdgeDetectSobel(smth, e1, e2, 90, &t1, &t2);
    BitMakeFromThreshold8(e1, bit1, t1, 0);
    BitMakeFromThreshold8(e2, bit2, t2, 0);
    BitUnion8(bit1, bit2, edge);
    WritePBM8(hdr, edge, argv[2]);

    ByteFree(buf);
    ByteFree(smth);
    BitFree(e1);
    BitFree(e2);
    BitFree(edge);
    BitFree(bit1);
    BitFree(bit2);

    return 0;
}