简体   繁体   中英

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.

我建议制作一个所有非零像素的坐标列表(通过检查图像中的所有像素),然后在列表中使用random.shuffle并获取前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])] 

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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM