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'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.
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])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With