Pick random coordinates in Numpy array based on condition
<p>I have used convolution2d to generate some statistics on conditions of local patterns. To be complete, I'm working with images and the value 0.5 is my 'gray-screen', I cannot use masks before this unfortunately (dependence on some other packages). I want to add new objects to my image, but it should overlap at least 75% of non-gray-screen. Let's assume the new object is square, I mask the image on gray-screen versus the rest, do a 2-d convolution with a n by n matrix filled with 1s so I can get the sum of the number of gray-scale pixels in that patch. This all works, so I have a matrix with suitable places to place my new object. How do I efficiently pick a random one from this matrix?</p>

<p>Here is a small example with a 5x5 image and a 2x2 convolution matrix, where I want a random coordinate in my last matrix with a 1 (because there is at most 1 0.5 in that patch)</p>

<p>Image:</p>

<pre><code>1    0.5  0.5  0    1
0.5  0.5  0    1    1
0.5  0.5  1    1    0.5
0.5  1    0    0    1
1    1    0    0    1
</code></pre>

<p>Convolution matrix:</p>

<pre><code>1    1 
1    1 
</code></pre>

<p>Convoluted image:</p>

<pre><code>3    3    1    0
4    2    0    1
3    1    0    1
1    0    0    0
</code></pre>

<p>Conditioned on &lt;= 1:</p>

<pre><code>0    0    1    1
0    0    1    1
0    1    1    1
1    1    1    1
</code></pre>

<p>How do I get a uniformly distributed coordinate of the 1s efficiently?</p>

<p><code>np.where</code> and <code>np.random.randint</code> should do the trick :</p>

<pre><code>#we grab the indexes of the ones
x,y = np.where(convoluted_image &lt;=1)
#we chose one index randomly
i = np.random.randint(len(x))
random_pos = [x[i],y[i]]
</code></pre>

python numpy