I am working my way through “The Go Programming Language” by Alan Donovan and Brian Kernighan. I am on exercise 3.6 which reads as
“Supersampling is a technique to reduce the effect of pixelation by computing the color value at several points within each pixel and taking the average. The simplest method is to divide each pixel into four “subpixels.” Implement it.”
Here is the code I am supposed to add this to
// This version has color.
// Uses supersampling
package main
import (
"image"
"image/color"
"image/png"
"math/cmplx"
"os"
)
func main() {
const (
xmin, ymin, xmax, ymax = -2, -2, +2, +2
width, height = 1024, 1024
)
img := image.NewRGBA(image.Rect(0, 0, width, height))
for py := 0; py < height; py++ {
y := float64(py)/height*(ymax-ymin) + ymin
for px := 0; px < width; px++ {
x := float64(px)/width*(xmax-xmin) + xmin
z := complex(x, y)
// image point (px, py) represents complex value z.
img.Set(px, py, mandelbrot(z))
}
}
png.Encode(os.Stdout, img) // NOTE: ignoring errors
}
func mandelbrot(z complex128) color.RGBA {
const iterations = 255
const contrast = 15
var v complex128
for n := uint8(0); n < iterations; n++ {
v = v*v + z
if cmplx.Abs(v) > 2 {
return color.RGBA{contrast*(n+2), contrast*(n+1), contrast*n, 255}
}
}
return color.RGBA{0, 0, 0, 255}
}
Now I have several questions.
-
Everything I read says a pixel is one solid color so how does breaking it into subpixels and sampling them help wouldn’t they all just be the color of the pixel that you broke up into subpixels ?
-
Do I need to wait until after
png.Encode()
runs and open the image and then run this on it or can I do this immediately after coloring the pixel ? I am wondering this because I am thinking perhaps that the encoding causes more then one color to be present in the pixel since my program only places one color in them. -
I have been looking through the packages and there documentation and I can figure out how to extract individual bit or parts of the RGBA value ( Example: I could extract hex value of G ). I can break it into sections of its underlying code but none of those things give me a complete color. Could someone point me in the right direction here ?
Any help would be greatly appreciated.