Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get random pixel index from binary image with value 1 in python?

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.

like image 879
vishnu saini Avatar asked Sep 18 '25 01:09

vishnu saini


2 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.

like image 106
Błotosmętek Avatar answered Sep 20 '25 14:09

Błotosmętek


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])] 
like image 35
N_Divyasri Avatar answered Sep 20 '25 15:09

N_Divyasri