5

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?

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)

Image:

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

Convolution matrix:

1    1 
1    1 

Convoluted image:

3    3    1    0
4    2    0    1
3    1    0    1
1    0    0    0

Conditioned on <= 1:

0    0    1    1
0    0    1    1
0    1    1    1
1    1    1    1

How do I get a uniformly distributed coordinate of the 1s efficiently?

1 Answer 1

13

np.where and np.random.randint should do the trick :

#we grab the indexes of the ones
x,y = np.where(convoluted_image <=1)
#we chose one index randomly
i = np.random.randint(len(x))
random_pos = [x[i],y[i]]
Sign up to request clarification or add additional context in comments.

1 Comment

this is awesome

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.