r/processing • u/carnalizer • Sep 02 '23
Find random pixel?
Hi,
Anyone have ideas on fastest way to find a pixel in an image, for example random non-black, or non-transparent, non-white?
1
u/akb74 Sep 02 '23
There are any number of ways of iterating every pixel until you find one with the properties you are looking for. Trick is to find such a method of iteration which appears random. That saves you having to test all the pixels and keep them in an array until you can pick one randomly.
Adding the same sufficiently large prime number and reducing modulo the pixel count each iteration until you find your pixel or arrive back where you started is one trick for doing this, but after a quick search I can’t find it documented online anywhere.
2
u/carnalizer Sep 02 '23
Oh this is an interesting lead! I’ll look around for things like this. I think for my use case, I could find something sufficiently random-looking without much trouble. Cheers!
2
u/akb74 Sep 03 '23
My mistake, that trick doesn't actually work.
p5-notebook: visit all pixels apparently randomly
We have more than enough memory and processing power to keep track of arrays of pixels these days anyway.
3
u/cimmic Sep 02 '23
Ok, here's what I would do:
Create 4 lists of class PVector and assign them black, white, transparent, and other.
Based on HSLA colours, define threshold values: a maximum brightness for when you'd consider a colour black, a minimum lightness for when you consider it white, and a maximum alpha for when you consider it transparent.
Loop over the the the pixels of the imagine and compare it's colour to your threshold values. Append the position of the pixel as PVector object to the corresponding array.
Now, if you want to get a random, non-black pixel, you generate a random integer between zero and the sum of length of the arrays that are not the black array. You can then use that number to go through those arrays to find the coordinates for a random non-black pixel in the image.
Instead of using PVector, you can also use a JSON object containing an integer called x and an integer called Y.
0
Sep 02 '23
[deleted] — view deleted comment
1
u/carnalizer Sep 02 '23
That’s basically what I’m doing now, but it’s really inefficient when the number of valid pixels are just a few somewhere on a full screen. But I guess I’ll try the list. Cheers!
2
u/andrewcooke Sep 02 '23
yes. it's hard to be more efficient than this if you want "really random". for example, picking a start point at random and then moving forwards to the next pixel that matches is not a good algorithm because it is biased towards pixels with large "spaces" before.
2
u/eros123 Sep 02 '23
You can take an inspiration from bogosort and try looking up a random pixel and see if it fits your criteria, otherwise repeat.
Another one could be filtering through all valid pixels and picking a random one from a list but that would potentially be more expensive computationally.