Interpret image as ASCII text

CP1CP1
edited May 2016 in How To...

hi,

I am new to processing and looking for help / code examples turning an image into ASCII text via processing. I started using ASCII video by Ben Fry using my webcam generating ASCII images. This works fine :) Now I'm looking for a method using a picture (.jpg for example) as source instead of the live picture from my webcam. I already used search in this forum but I wasn't able to find a solution or code example for my issue. Maybe someone can help me with code examples or how I could modify Ben Fry's ASCII video for my needs.

regards CP1

Answers

  • You can just reuse this sketch, but instead of using the camera capture (which is a simple PImage), you can use the PImage produced by a loadImage().

    Note: avoid using backquote ` as apostrophe, it has a special meaning in this forum (displaying monospaced text), beside being incorrect in typography.

  • Here's a simplified example that should suit your needs:

    // the image to asciify
    PImage img;
    
    // sampling resolution: colors will be sampled every n pixels 
    // to determine which character to display
    int resolution = 9;
    
    // array to hold characters for pixel replacement
    char[] ascii;
    
    void setup() {
      img = loadImage("Penguins.jpg");
      size(img.width,img.height);
      background(255);
      fill(0);
      noStroke();
    
      // build up a character array that corresponds to brightness values
      ascii = new char[256];
      String letters = "MN@#$o;:,. ";
      for (int i = 0; i < 256; i++) {
        int index = int(map(i, 0, 256, 0, letters.length()));
        ascii[i] = letters.charAt(index);
      }
    
      PFont mono = createFont("Courier", resolution + 2);
      textFont(mono);
    
      asciify();
    }
    
    void asciify() {
      // since the text is just black and white, converting the image
      // to grayscale seems a little more accurate when calculating brightness
      img.filter(GRAY);
      img.loadPixels();
    
      // grab the color of every nth pixel in the image
      // and replace it with the character of similar brightness
      for (int y = 0; y < img.height; y += resolution) {
        for (int x = 0; x < img.width; x += resolution) {
          color pixel = img.pixels[y * img.width + x];
          text(ascii[int(brightness(pixel))], x, y);
        }
      }
    }
    

    When you create your sketch, create a folder within the sketch folder called "data" and drop your image file in there. I just used the stock "Penguins.jpg" image from my Windows installation. You can add a few more characters and change the sampling resolution to your liking, but the basic idea is all there.

Sign In or Register to comment.