Skip to content

Instantly share code, notes, and snippets.

@gubatron
Last active June 27, 2023 10:56
Show Gist options
  • Save gubatron/c65128f97237731bf28b to your computer and use it in GitHub Desktop.
Save gubatron/c65128f97237731bf28b to your computer and use it in GitHub Desktop.
Playing with /dev/urandom Random Number generation and ImageMagick in C++ to visualize randomness or patterns.
#include <Magick++.h>
#include <random>
#include <iostream>
#define HEIGHT 1024
#define WIDTH 1024
#define RANDOM_POINTS 786432 //75% of the area if no points would repeat
using namespace Magick;
using namespace std;
/**
This program uses the /dev/urandom generator to map integers
into a 2D image, so that we can see if the random generator of
the system forms any sort of visual pattern (non-random)
See an output example here: http://i.imgur.com/vV3KAGv.png
*/
int main(int nargs, char** args) {
Geometry g1(HEIGHT, WIDTH);
Color WHITE = Color(MaxRGB, MaxRGB, MaxRGB, 0); //last is alpha, 0=opaque, MaxRGB=fully transparent
Color BLACK = Color(0, 0, 0, 0);
Image white_bg_image = Image(g1, WHITE);
white_bg_image.magick("png");
//initialize random device
std::mt19937 eng((std::random_device())()); //i believe this uses /dev/urandom in macosx
std::uniform_int_distribution<> dist(0, RAND_MAX); //RAND_MAX=2147483647
for (int i=0; i < RANDOM_POINTS; i++) {
int r = dist(eng); //generates random number
int x= r % WIDTH;
int y= (r / HEIGHT) % HEIGHT;
white_bg_image.pixelColor(x, y, BLACK);
}
white_bg_image.write("random_generator.png");
return 0;
}
/**
DEPENDENCY (ON MAC): brew install imagemagick
On other systems, after you have downloaded ImageMagick binaries, or you have compiled sources, you might want to set this on your environment
MAGICK_HOME=/usr/local/Cellar/imagemagick/6.8.9-7
MAGICK_INCLUDE=${MAGICK_HOME}/include
MAGICK_LIB=${MAGICK_HOME}/lib
replace for the adequate paths, and hack the below BUILD line to use those variables to make path specifying easier.
I generated the below line in part using a tip from the ImageMagick tutorial pdf
http://www.imagemagick.org/Magick++/tutorial/Magick++_tutorial.pdf
`Magick++-config --cppflags --cxxflags --ldflags --libs` will output all the flags you can pass to your compiler.
My g++ is actually a symlink to clang++
BUILD:
g++ -DMAGICKCORE_HDRI_ENABLE=0 -DMAGICKCORE_QUANTUM_DEPTH=16 -DMAGICKCORE_HDRI_EN\
ABLE=0 -DMAGICKCORE_QUANTUM_DEPTH=16 -DMAGICKCORE_HDRI_ENABLE=0 -DMAGICKCORE_QUANTUM_DEPTH=16 -I/usr/local/Cellar/imagemagick/6.8.9-7/include/ImageMagick-6 -\
L/usr/local/Cellar/imagemagick/6.8.9-7/lib -lMagick++-6.Q16 -lMagickWand-6.Q16 -lMagickCore-6.Q16 -L/usr/local/Cellar/imagemagick/6.8.9-7/lib -lMagick++-6.Q1\
6 -lMagickWand-6.Q16 -lMagickCore-6.Q16 -o random_generator_test random_generator_test.cpp
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment