Skip to content

Palette

kkrmno edited this page Apr 10, 2021 · 1 revision

Introduction

To create a png image that uses a palette first create an image with a single channel:

#A 200x200 image filled with black
img = Imgrb::Image.new(200,200,0)

Then set a palette for the image (or do so at a later stage):

#A palette with two entries. Entry 0 is black (0,0,0) and entry 1 is red (255,0,0).
img.set_palette(0,0,0,255,0,0)

Now you can set the values of the image to the palette indexes you have available (i.e. 0 or 1 in this case).

#Set a pixel in the center to the red palette color
img.set_pixel(100,100,1)

Predefined Palettes

There are some predefined palettes available in the Imgrb::Palettes module. Here is an example using the HSV palette:

require 'imgrb'

#Create an image of a white disk on a black background
img = Imgrb::Image.new(400,400,0)
img.draw_disk!(200,200,100,255)
img.save("disk.png")

#Compute the gradient of the disk image as well as the gradient magnitude
grad_x, grad_y = img.gradient
grad_mag = ((grad_x**2 + grad_y**2)**0.5)

#Compute the direction of the gradient. Ignore places where the gradient
#magnitude is small.
theta = (-grad_y).atan2(grad_x)
theta.collect_to_image_with_coord! do |val, x, y|
  if grad_mag[y,x] < 0.001
    0
  else
    val
  end
end

#Rescale the directions to values between 0 and 255 and round to integers
theta = theta.rescale(0,255).round
#Add a palette using HSV values (256 entries)
theta.set_palette(Imgrb::Palettes::HSV)
theta.save("disk_hsv.png")

Clone this wiki locally