Exercises Computer Graphics

Session 8 - Anti-aliasing Solutions

Solutions

Exercises:

Useful Links:

Introduction

All solutions for session 8.

Exercises

Exercise 1: anti-aliasing

  void drawAntiAliasedLine(int x1, int y1, int x2, int y2) {
    int t;
    int colour;

    if (abs(x2-x1)>abs(y2-y1)) {
      int i, dy, y;

      if (x1>x2) { t=x1; x1=x2; x2=t; t=y1; y1=y2; y2=t; } // swap
        dy = (1 << 16)*(y2-y1)/(x2-x1);
        y=y1 << 16;

        for (i=x1; i < x2; i++) {
          y+=dy;
          colour = (y >> 8)%256;
          stroke(colour);
          point(i, y>>16);
          stroke(255 - colour);
          point(i, (y>>16)+1);
        }
      } else {
        int i, dx, x;
        if (y1>y2) { t=x1; x1=x2; x2=t; t=y1; y1=y2; y2=t; } // swap
        dx = (1 << 16)*(x2-x1)/(y2-y1);
        x=x1 << 16;

        for (i=y1; i < y2; i++) {
          x+=dx;
          colour = (x>>8)%256;
          stroke(colour);
          point(x>>16, i);
          stroke(255 - colour);
          point((x>>16)+1, i);
        }
    }
  }

Exercise 2: Smoothing

  color calcMask(double[][] mask, int x, int y) {
    double avgR=0,avgG=0,avgB=0;
    color colour;
    double weight;
    int xstart = x - mask[0].length/2;
    int ystart = y - mask.length/2;

    for (int i=0; i < mask[0].length; i++)
      for (int j=0; j < mask.length; j++) {
        colour  = bmp.get(i+xstart, j+ystart);
        weight = mask[i][j];
        avgR += red(colour) * weight;
        avgG += green(colour) * weight;
        avgB += blue(colour) * weight;
      }
    return color((int)avgR, (int)avgG, (int)avgB);	
  }

  PImage smooth(PImage img, double[][] mask) {
    PImage smoothbmp = new PImage(img.width, img.height);
    // not strictly necessary to copy the entire original image, but this does
    // correctly set the borders of the image
    smoothbmp.copy(img, 0,0,img.width,img.height,0,0,img.width,img.height);

    int i,j;
    int xofs = mask[0].length / 2;
    int yofs = mask.length / 2;
    for (i=xofs; i< bmp.width-xofs; i++)
      for (j=yofs; j< bmp.height-yofs; j++) {
        smoothbmp.set(i,j,calcMask(mask,i,j));
      }
    return smoothbmp;
  }
Valid HTML 4.01 Transitional ©2008-2009 Tom Van Cutsem