Was playing with some Ruby code to re-order pixels of an image and came across a weird effect.
The code below loads up an image, reads the pixels into an array, re-orders the pixels (using Array.sort
in an unintended, but apparently valid way) and then creates another image to which it writes out the re-ordered pixels, using the same dimensions from the original image.
According to this: How does Ruby's max function order duplicates? not-stable means the result is unpredictable. However every time I run the code with the same input, I get the same output, so in that sense the result of the sorting in this case is predictable.
What does it mean that the sorting algorithm is not stable and how does it apply in this case?
The code has only been tested on a Mac using: ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin16].
require 'rmagick'
include Magick
img = ImageList.new("images/test-image.jpg")
pixels = img.get_pixels(0,0,img.columns,img.rows)
# https://apidock.com/ruby/Array/sort
# The block must implement a comparison between a and b and
# * <0 when b follows a,
# * 0 when a and b are equivalent,
# * >0 when a follows b
# The result is not guaranteed to be stable.
# When the comparison of two elements returns 0, the order of the elements is unpredictable.
pixels = pixels.sort {|p| 1 }
out_img = Magick::Image.new(img.columns, img.rows)
out_img.store_pixels(0,0, img.columns, img.rows, pixels)
out_img.write("images/test-image-out.jpg")
Also, here's a related question: https://dsp.stackexchange.com/questions/60106/how-would-you-interpret-the-pattern-in-this-picture-generated-by-re-sorting-pi