Command `rand_sum`

The recent thread from @prawnsushi (Channel Shuffle) made me think about the creation of a command that would generate a sequence of strictly positive, random, integers that all sum to a user-defined value.
It turned out doing this was not as trivial as it appeared at the first glance :slight_smile:

So, after many tries, I’ve ended up with a new command rand_sum, that fills an image with random integers (>0) so that their sum is prescribed.
This command should be available after a filter update (gmic update).
It can be used for instance like this:

$ gmic 16,16 rand_sum. 1024

gmic_rand_sum


Well, what is the relation with the post from @prawnsushi ?
You actually need such a command if you want to split an image with a fixed number of parts, but with random blocs. For instance, for a splitting along the X-axis, you first need a sequence of N values such that their sum is equal to the width of the image to split.
Then, you compute the accumulation of these values and you get corresponding coordinates of the consecutive columns to extract from your image:

foo :
  sp colorful
  8 rand_sum. {w#0} cumulate. 
  repeat w { +columns[0] {1,[i[$>-1],i[$>]-1]} } 
  rm[0,1]

return this list of random blocs of image columns:


What kind of funny things we can do with this?
Once your image has been splitted, you can manipulate the list of blocks then merge them again.
For instance, if you mirror the block :

foo :
  sp colorful

  # Random split along-X
  32 rand_sum. {w#0} cumulate. repeat w { +columns[0] {1,[i[$>-1],i[$>]-1]} } rm[0,1]
  mirror x a x

  # Random split along-Y
  32 rand_sum. {h#0} cumulate. repeat w { +rows[0] {1,[i[$>-1],i[$>]-1]} } rm[0,1]
  mirror y a y

creates this:

Another funny stuff : you can decompose your image into channels, randomly split/mirror/recompose them twice and remerge them at the end :

foo :
  sp colorful
  rgb2lab
  repeat 2 {
    s c
    foreach {
      16 rand_sum. {h#0} cumulate. repeat w { +rows[0] {1,[i[$>-1],i[$>]-1]} } rm[0,1]
      mirror y a y
    }
    a c
  }
  lab2rgb

So, finally it looks like we can have a lot of fun with such a math command :slight_smile:
Do you have other ideas of use?

1 Like

Repeating the last operation generates a nice video glitch effect :

2 Likes

With Channel Shuffle i’m also using sort_list to mix everything up. It’s kinda fun with an alpha channel mixed in.