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.
4 Answers
I'd suggest making a list of coordinates of all non-zero pixels (by checking all pixels in the image), then using random.shuffle on the list and taking the first 100 elements.
4 Comments
random.shuffle, otherwise it might be better to use random.choice.coordinates = np.argwhere(img) print(coordinates.shape) random.shuffle(coordinates) print(coordinates[0:100])After importing necessary libraries like
import cv2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
gray_img = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE) # grayscale
gray_img[i,j] will give pixel value at (i,j) position
Try to send all these values into a file in this format
i_positition,j_position,value_of_pixel
path = os.getcwd() + '/filename.txt'
data = pd.read_csv(path, header=None, names=['i', 'j', 'value'])
positive = data[data['value'].isin([1])]
negative = data[data['value'].isin([0])]
positive data frame contains all the pixel positions whose value is 1.
positive['i'] ,positive['j'] will give you list of (i,j) values of all the pixels whose value is 1.
i_val=np.asarray(positive['i'])
j_val=np.asarray(positive['j'])
Now you can randomly select any value from i_val & j_val arrays.
Note: Make sure that your pixel values will be 1 or 0. If your values are 0 and 255 then change this command
positive = data[data['value'].isin([255])]
1 Comment
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 :)
PIL--> Python Imaging Library module might help you.