# Laboratory: Drawing with Palettes

Summary: In this laboratory, you will explore the use of palettes to more efficiently store images and the effects the approximations such palettes require have on images.

## Preparation

a. This laboratory requires a wide variety of procedures, some introduced in this reading, some introduced in previous readings, and some of which you've written. We have reproduced all of those procedures at the end of this reading. Copy them into your definitions pane (or your library).

b. We'll do some work with reading and writing images. Create a 10x10 image called `canvas` for such experimentation and fill it with random colors.

c. We'll also do some work with existing images. Load an image of your choice and call it `picture`.

## Exercises

### Exercise 1: Experiments with the Simple Encoding

As you may recall from the reading, `rgb->approx` approximates an RGB color by converting it to a number between 0 and 255 that represents a nearby color. Another function, `approx->rgb` converts the number to that nearby color.

a. Pick five colors and ensure that `rgb->approx` converts each to a number between 0 and 255. Try to pick colors that are not at the extremes (that is, that have components whose values are not just 0 and 255). You may find it easiest to do this process with `map`.

````>` `(map rgb->approx (list ....))`
```

b. Convert those approximations back to RGB colors with `rgb->approx`. Then, compare those values to the original colors. You might want to try something like the following:

````>` `(define colors (list ...))`
`>` `(map rgb->string colors)`
`>` `(map rgb->cname colors)`
`>` `(define encodings (map rgb->approx colors))`
`>` `(define approximations (map approx->rgb encodings))`
`>` `(map rgb->string approximations)`
`>` `(map rgb->cname approximations)`
```

c. What do you notice anything special about the component values of these various colors?

d. Note that we can approximate an RGB color by encoding it and then decoding it. Write a procedure, `rgb.approximate` that does just that.

e. Using `image.map`, apply `rgb.approximate` to `canvas` (which should contain random colors).

````>` `(define approximated (image.map rgb.approximate canvas))`
`>` `(image.show approximated)`
```

f. How good is the approximation? What could you do to improve the approximation?

g. Using `image.map`, apply `rgb.approximate` to `picture`.

h. Does this experiment change your perspective on the success of the approximation?

### Exercise 2: Rainbow Palettes

As you may recall, `palette.encode-color` encodes a color using a color palette (a list of colors) and `palette.decode-color` decodes a color using a palette.

a. Add the following definition of a simple color palette to your definitions window.

```(define rainbow-plus
(list color.red
color.orange
color.yellow
color.green
color.blue
color.indigo
color.violet
color.black
color.white))```

b. Using that palette, encode the same colors you encoded in exercise 1. Are these encodings better or worse? Why?

c. Write a procedure, `(palette.select palette color)`, that selects the color in `palette` used to represent `color`.

d. See what happens if you apply that procedure to `canvas`. What does that tell you about the usefulness of this palette?

e. See what happens if you apply that procedure to `picture`. What does that tell you about the usefulness of this palette?

### Exercise 3: Random Palettes

Clearly, using a small palette of fairly restricted colors is not our best approach for approximating an image. What can we do instead? We might simply choose a random palette.

a. Write a procedure, `(palette.random n)`, that builds a list of `n` randomly-generated colors. (It's okay if the same color appears twice in the palette.)

b. Using that procedure, build a series of palettes, `palette-2`, with two colors, `palette-4`, with 4 colors, `palette-8`, with 8 colors, `palette-16`, with 16 colors, and `palette-32`, with 32 colors.

c. Here's a procedure, `palette.map`, which “maps” a palette onto an image by converting each color in the image to the closest color in the palette.

```;;; Procedure:
;;;   palette.map
;;; Parameters:
;;;   palette, a color palette
;;;   image, an image
;;; Purpose:
;;;;  Compuate a new image by converting each pixel in image to the
;;;   nearest color in palette.
;;; Produces:
;;;   new-image, an image
;;; Preconditions:
;;; Postconditions:
;;;   Each pixel in new-image is in palette.
;;;   new-image is the same width and height as image.
;;;   For each column and row in image, (image.get new-image row col) is
;;;     relatively close to (image.get image row col).
;;;     (In particular, it is at least as close as any other color
;;;     in palette).
(define palette.map
(lambda (palette image)
(image.map (lambda (color) (rgb.closest color palette)) image)))
```

Using that procedure, map each of your palettes onto canvas.

d. As you may recall, `image.map` can take a while with larger images. Let's see the effect of palette size on the amount of time it takes to apply a palette to `picture` First, map `palette-2` onto `picture` and, using a clock, determine approximately how many seconds it takes. Next, map `palette-4` onto `picture` and, using a clock, determine approximately how many seconds it takes. Then, predict how long it will take to map palettes of size 8 and 16. If you have time, check those results experimentally.

### Exercise 4: Random Palettes, Revisited

a. Because the current implementation of palettes makes it slow to apply a palette to a large image, we'll need a relatively small image to work with. However, we want a sensible image, rather than a random image. Pick a 64x64 square from `picture`, copy it, create a new 64x64 image called `selection`, and paste into that image.

b. Map `palette-16` onto `selection`. Do you consider that a reasonable approximation?

c. A better strategy for selecting random colors is to randomly select colors from the image, not colors from the complete color space. Write a procedure, `(image->palette image n)`, that randomly selects `n` colors from `image`.

d. Using that procedure, build a palette of 8 colors from `selection`, and call that palette. `sel-8`.

e. Map `sel-8` onto `selection`. Is the result better or worse than the result you got in step b?

### Exercise 5: Storing with Palettes

Although we've been exploring palettes by looking at what happens when we use them interactively with images, most frequently palettes are used when saving and restoring files.

a. Write `(palette.save-image palette image filename)`, which saves an image to a file. In writing this procedure, you may want to use `image.write-pixmap` as a pattern for how to write an image to a file.

```;;; Procedure:
;;;   image.write-pixmap
;;; Parameters:
;;;   image, an image
;;;   filename, a string
;;; Purpose:
;;;   Writes the pixmap information on image to the file.
;;; Produces:
;;;   [Nothing; Called for the side effect.]
;;; Preconditions:
;;;   filename is a valid file name.
;;; Postconditions:
;;;   The file named by filename now contains a sequence of integers,
;;;   one for each RGB color in image.
(define image.write-pixmap
(lambda (image filename)
(let ((width (image.width image))
(height (image.height image))
(port (open-output-file filename)))
(write width port)
(newline port)
(write height port)
(newline port)
(let kernel ((col 0)
(row 0))
(cond
((>= row height)
(close-output-port port)
image)
((>= col width)
(kernel 0 (+ row 1)))
(else
(rgb.write (image.get-pixel image col row) port)
(kernel (+ col 1) row)))))))

```

b. Write `(palette.load-image palette filename)`, which load an image from a file, assuming that the image was stored using the same palette. In writing this procedure, you may want to use `image.read-pixmap` as a pattern for how to read an image from a file.

```;;; Procedure:
;;; Parameters:
;;;   filename, a string
;;; Purpose:
;;;   Read pixmap data from the specified file, returning a new
;;;   image from that data.
;;; Produces:
;;;   image, an image.
;;; Preconditions:
;;;   filename names a file.
;;;   That file was created by image.write-pixmap.
;;; Postconditions:
;;;   image contains teh same colors in the same positions as the image
;;;   previously written with image.write-pixmap.
(lambda (filename)
(let* ((port (open-input-file filename))
(image (image.new width height)))
(let kernel ((col 0)
(row 0))
(cond
((> (+ col row) (+ (- width 1) (- height 1)))
(close-input-port port)
(if (not (eof-object? next-color))
image)
((eof-object? (peek-char port))
(close-input-port port)
(throw "image.read-pixmap!: Premature end of file."))
((>= col width)
(kernel 0 (+ row 1)))
(else
(cond
((eof-object? next-color)
(close-input-port port)
(throw "image.read-pixmap!: Premature end of file."))
(else
(image.set-pixel! image col row next-color)
(kernel (+ col 1) row))))))))))
```

## For Those With Extra Time

### Extra 1: More Efficient Encoding

One disadvantage of the current version of `palette.encode-color` is that it ends up scanning the list of colors twice: once to find the closest color and once to find the index of that color. We might instead write a procedure that does the two activities simultaneously.

The following provides one implementation of that technique.

```;;; Procedure:
;;;   rgb.index-of-closest
;;; Parameters:
;;;   color, an RGB color
;;;   colors, a list of RGB colors
;;; Purpose:
;;;   Determine the index of the  element of colors that is closest to
;;;   color
;;; Produces:
;;;   index, an integer
;;; Preconditions:
;;;   colors is nonempty.
;;; Postconditions:
;;;   0 <= index < (length colors)
;;;   (rgb.distance color (list-ref colors index)) <= (rgb.distance color c)
;;;     for all c in colors
(define rgb.index-of-closest
(lambda (color colors)
(let kernel ((remaining-colors (cdr colors))
(closest-so-far (car colors))
(index-of-csf 0)
(skipped 1))
(cond
((null? remaining-colors)
index-of-csf)
((< (rgb.distance color (car remaining-colors))
(rgb.distance color closest-so-far))
(kernel (cdr remaining-colors)
(car remaining-colors)
skipped
(+ skipped 1)))
(else
(kernel (cdr remaining-colors)
closest-so-far
index-of-csf
(+ skipped 1)))))))
```

a. Confirm, using a variety of examples, that it seems to work correctly.

b. Explain, in your own words, how this procedure works.

c. Rewrite `palette.encode-color` to use `rgb.index-of-closest`.

d. Rerun one of your timing tests to determine whether this change had any effect.

### Extra 2: Storing Palettes

Accuracy requires that our image file include not just the indices into the palette, but also the palette itself. Rewrite `palette.save-image` and `palette.load-image` to use this technique.

You may find the following procedures helpful.

```;;; Procedure:
;;;   rgb-list.write
;;; Parameters:
;;;   colors, a list of RGB colors
;;;   outport, an output port
;;; Purpose:
;;;   Writes the elements of colors to outport.
;;; Produces:
;;;   [Nothing; called for the side effect]
;;; Preconditions:
;;;   outport is open for writing
;;; Postconditions:
;;;   The file associated with outport now contains all the colors in
;;;   colors.
(define rgb-list.write
(lambda (colors outport)
(foreach! (lambda (color) (rgb.write color outport))
colors)))

;;; Procedure:
;;; Parameters:
;;;   source, an input port
;;;   n, a non-negative integer
;;; Purpose:
;;;   Reads n RGB colors from source, returning them as a list.
;;; Produces:
;;;   colors, a list of RGB colors
;;; Preconditions:
;;;   source is open for reading
;;; Postconditions:
;;;   colors contains the first n colors in source.
(lambda (source n)
(if (> n 0)
null)))
```

## Explorations

### Exploration 1: Switching Palettes

You can obtain some very interesting effects by encoding an image using one palette and then decoding it using another.

a. Define two palettes, each with sixteen colors. Name them `pal` and `lette`.

b. Rather than storing the image to a file and then reloading it using the new palette, we will use `image.map` to build a new version of the image. modify the image.

````>` ```(image.map (lambda (color) (palette.decode lette (image.encode pal color)))
canvas```
```

## Useful Procedures

```; +--------------------------+----------------------------------------
; | Approximating RGB Colors |
; +--------------------------+

;;; Procedure:
;;;   rgb->approx
;;; Parameters:
;;;   color, an rgb color
;;; Purpose:
;;;   Convert color to an encoded approximation.
;;; Produces:
;;;   approx, an approximation
;;; Preconditions:
;;; Postconditions:
;;;   0 <= approx < 256
;;;   (approx->rgb approx) is relatively near color.
(define rgb->approx
(let ((scale (/ 5 255)))
(lambda (color)
(->int (+ (* 36 (round (* scale (rgb.red color))))
(* 6 (round (* scale (rgb.green color))))
(round (* scale (rgb.blue color))))))))

;;; Procedure:
;;;   approx->rgb
;;; Parameters:
;;;   approx, an integer
;;; Purpose:
;;;   Convert an encoded approximation to a color.
;;; Produces:
;;;   color.
;;; Preconditions:
;;;   0 <= approx < 256
;;;   approx was created by rgb->approx
;;; Postconditions:
;;;   color is close to the original value
;;;   (approx->rgb color) = approx.
(define approx->rgb
(let* ((scale (/ 255 5))
(component (lambda (c) (round (* scale c)))))
(lambda (approx)
(rgb.new (component
(/ (- approx (remainder approx 36)) 36))
(component
(/ (- (remainder approx 36) (remainder approx 6)) 6))
(component
(remainder approx 6))))))

; +------------------------+------------------------------------------
; | Palette-Based Encoding |
; +------------------------+

;;; Procedure:
;;;   palette.encode-color
;;; Parameters:
;;;   palette, a nonempty list of RGB colors
;;;   color, an RGB color
;;; Purpose:
;;;   Determine a number that appropriately encodes color using
;;;   the given palette.
;;; Produces:
;;;   encoding, an integer
;;; Preconditions:
;;; Postconditions:
;;;   0 <= encoding < (length palette)
;;;   (rgb.distance color (list-ref palette encoding)) <=
;;;     (rgb.distance color (list-ref palette i))
;;;     for all i, 0 <= i < (length palette)
(define palette.encode-color
(lambda (palette color)
(list.index-of palette (rgb.closest color palette))))

;;; Procedure:
;;;   palette.decode-color
;;; Parameters:
;;;   palette, a nonempty list of RGB colors
;;;   code, an integer
;;; Purpose:
;;;   Converts an encoding (created by palette.encode-color) back
;;;   to a color.
;;; Produces:
;;;   color, an RGB color
;;; Preconditions:
;;;   0 <= code < (length palette)
;;;   code was created with (rgb.encode some-color)
;;; Postconditions:
;;;   color is close to some-color
(define palette.decode-color
(lambda (palette code)
(list-ref palette code)))

; +---------------------+---------------------------------------------
; | Reading and Writing |
; +---------------------+

;;; Procedure:
;;;   rgb.write
;;; Parameters:
;;;   color, an rgb color
;;;   port, the port to which to write the color
;;; Purpose:
;;;   Write the color to the specified port
;;; Preconditions:
;;;   port is open for writing.
;;; Postconditions:
;;;   When read with rgb.read, the data just appended to the file
;;;   will give color.

(define rgb.write
(lambda (color port)
(int.write (rgb.red color) port)
(int.write (rgb.green color) port)
(int.write (rgb.blue color) port)))

;;; Procedure:
;;; Parameters:
;;;   port, the name of an input port
;;; Purpose:
;;;   Reads an RGB color from the file.
;;; Produces:
;;;   color, an RGB color (or <eof>, if the port is at the end of
;;;     the file)
;;; Preconditions:
;;;   port is open for reading.
;;;   port is at the place in a file after which the next data was
;;;     written by rgb.write.
;;; Postconditions:
;;;   color is the color written by the call to rgb.write mentioned
;;;     in the preconditions.

(lambda (port)
(if (eof-object? blue)
blue
(rgb.new red green blue)))))

; +-------------------------+-----------------------------------------
; | Miscellaneous Utilities |
; +-------------------------+

;;; Procedure:
;;;   iota
;;; Parameters:
;;;   n, an integer
;;; Purpose:
;;;   Create a list of integers between 0 and n-1, inclusive.
;;; Produces:
;;;   ints, a list of integers.
;;; Preconditions:
;;;   n >= 0
;;; Postconditions:
;;;   (length ints) = n
;;;   For all i, 0 <= i < n, (list-ref ints i) = i
(define iota
(lambda (n)
(let kernel ((i 0))
(if (= i n)
null
(cons i (kernel (+ i 1)))))))

;;; Procedure:
;;;   image.random-fill!
;;; Parameters:
;;;   image, an image
;;; Purpose:
;;;   Fills the image with a random set of colors.
;;; Produces:
;;;   [Nothing; called for the side effect]
;;; Preconditions:
;;;   image identifies a valid image.
;;; Postconditions:
;;;   Every pixel in the image has an unpredictable color.
(define image.random-fill!
(lambda (image)
(region.compute-pixels! image 0 0
(- (image.width image) 1) (- (image.height image) 1)
(lambda (pos)
(rgb.new (random 255) (random 255) (random 255))))))

;;; Procedure:
;;;   file.size
;;; Parameters:
;;;   filename, a string
;;; Purpose:
;;;   Determines the number of characters in the file.
;;; Produces:
;;;   s, an integer.
;;; Preconditions:
;;;   filename names a valid file.
;;; Postconditions:
;;;   s is the size of file.  That is,
;;;    s read-char commands from file will succeed.
;;;    The s+1st read from file will fail.
(define file.size
(lambda (fname)
(file.size-kernel (open-input-file fname) 0)))

(define file.size-kernel
(lambda (source size)
(cond
(close-input-port source)
size)
(else
(file.size-kernel source (+ size 1))))))

;;; Procedure:
;;;   rgb.distance
;;; Parameters:
;;;   color1, an RGB color
;;;   color2, an RGB color
;;; Purpose:
;;;   Compute the distance between two colors
;;; Produces:
;;;   distance, a number
;;; Preconditions:
;;; Postconditions:
;;;   distance provides a reasonable metric for color distance.  In
;;;   particular, two colors likely to be perceived as similar will
;;;   have a smaller distance than two colors likely to be perceived
;;;   as different.
(define rgb.distance
(lambda (color1 color2)
(+ (square (- (rgb.red color1) (rgb.red color2)))
(square (- (rgb.green color1) (rgb.green color2)))
(square (- (rgb.blue color1) (rgb.blue color2))))))

;;; Procedure:
;;;   rgb.closer
;;; Parameters:
;;;   color, an RGB color
;;;   estimate1, an RGB color
;;;   estimate2, an RGB color
;;; Purpose:
;;;   Determines which of estimate1 and estimate2 is closer to color.
;;; Produces:
;;;   closer, an RGB color
;;; Preconditions:
;;; Postconditions:
;;;   closer is either estimate1 or estimate2
;;;   (rgb.distance color closer) <= (rgb.distance color estimate1)
;;;   (rgb.distance color closer) <= (rgb.distance color estimate2)
(define rgb.closer
(lambda (color estimate1 estimate2)
(if (<= (rgb.distance color estimate1) (rgb.distance color estimate2))
estimate1
estimate2)))

;;; Procedure:
;;;   rgb.closest
;;; Parameters:
;;;   color, an RGB color
;;;   colors, a list of RGB colors
;;; Purpose:
;;;   Determine the element of colors that is closest to
;;;   color
;;; Produces:
;;;   closest, an RGB color
;;; Preconditions:
;;;   colors is nonempty.
;;; Postconditions:
;;;   closest is an element of colors.
;;;   (rgb.distance color closest) <= (rgb.distance color c)
;;;     for all c in colors
(define rgb.closest
(lambda (color colors)
(let kernel ((remaining-colors (cdr colors))
(closest-so-far (car colors)))
(if (null? remaining-colors)
closest-so-far
(kernel (cdr remaining-colors)
(rgb.closer color closest-so-far (car remaining-colors)))))))

;;; Procedure:
;;;   list.index-of
;;; Parameters:
;;;   lst, a list of values
;;;   val, a value
;;; Purpose:
;;;   Find an index of val in lst.
;;; Produces:
;;;   index, a number (or #f)
;;; Preconditions:
;;; Postconditions:
;;;   If there exists a value in lst equal to val, then
;;;     (list-ref lst index) equals val
;;;   If no such value exists, then
;;;     index is #f
(define list.index-of
(lambda (lst val)
(cond
((null? lst)
#f)
((equal? val (car lst))
0)
(else
(+ 1 (list.index-of (cdr lst) val))))))
```

Samuel A. Rebelsky, rebelsky@grinnell.edu

Copyright © 2007 Janet Davis, Matthew Kluber, and Samuel A. Rebelsky. (Selected materials copyright by John David Stone and Henry Walker and used by permission.)

This material is based upon work partially supported by the National Science Foundation under Grant No. CCLI-0633090. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Science Foundation.

This work is licensed under a Creative Commons Attribution-NonCommercial 2.5 License. To view a copy of this license, visit `http://creativecommons.org/licenses/by-nc/2.5/` or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.