I have a binary image of large size (2000x2000). In this image most of the pixel values are zero and some of them are 1. I need to get only 100 randomly chosen pixel coordinates with value 1 from image. I am beginner in python, so please answer.
I have a binary image of large size (2000x2000). In this image most of the pixel values are zero and some of them are 1. I need to get only 100 randomly chosen pixel coordinates with value 1 from image. I am beginner in python, so please answer.
Use below code:
import numpy as np
y_idx, x_idx = np.where(image==1) #list of all the indices with pixel value 1
for i in range(0,100):
rand_idx = np.random.choice(x_idx) #randomly choose any element in the x_idx list
x = x_idx[rand_idx]
y = y_idx[rand_idx]
#--further code with x,y--
here is another answer that might save some memory storage, or at least a for loop..
import numpy as np
random_image = np.random.uniform(0, 1, size=(2000, 2000)) > 0.5
sel_index = np.random.choice(np.argwhere(random_image.ravel()).ravel(), size=100)
random_x, random_y = np.unravel_index(sel_index, random_bin.shape)
I just like the usage of unravel :)