objective – What are the causes of this repetition pattern in an image? (when reorganizing its pixels by their intensity – code included)

Just out of curiosity, I played with the RGB coordinates and pixels of the images. Then, for some reason, I decided to get all the pixels of an image, to get the coordinates / RGB values ​​of each pixel (for example, RGB (120, 30, 15)), to add the coordinates (for example, 120 + 30 + 15 = 165). ), then sort the pixels in ascending order according to this number (the sum of the coordinates / RGB values ​​of the pixel).

So, to be able to visualize this, I have "printed" the pixels on another image of the same dimensions as the original, but with the rearranged pixels as content. See an example below (and the corresponding Ruby code).

You will notice that the output image has a very well defined pattern. I've tried the same thing (rearrange the pixels by R + G + B) with a lot of different images, and there is always a similar pattern of repeating smaller versions of the same image.

Why does this happen? What explains the pattern of the image when the pixels are rearranged?

Original image:
enter the description of the image here

Image with rearranged pixels:
enter the description of the image here

# Ruby code
require 'rmagick'
include Magick

img = ImageList.new("images/test-image.jpg")
pixels = img.get_pixels(0,0,img.columns,img.rows)

# Sort pixels by total intensity
pixels = pixels.sort {|p| p.red + p.green + p.blue}

out_img = Magick::Image.new(img.columns, img.rows)
out_img.store_pixels(0,0, img.columns, img.rows, pixels)

@ cthom06 understood it in the comments. The code above uses sort instead of sort_by to sort the pixel array. Always curious to know what sort made.

Someone answered the question on dsp: How would you interpret the pattern in this picture? (generated by re-sorting the pixels according to their RGB value)

When using sort_by, the output image looks like this:
enter the description of the image here