Cross Validated Asked by C. Wang on December 29, 2021
I have a 2D image, each pixel of it representing a probability. Now I want to randomly select a point from the image, such that the probability of the position of the point follows the pdf of the image.
I am going to assume that your image is coded numerically as an $n times m$ matrix of intensity values that are equal to the probabilities. This means you have a probability matrix:
$$boldsymbol{P} = begin{bmatrix} p_{11} & p_{12} & cdots & p_{1m} \ p_{21} & p_{22} & cdots & p_{2m} \ vdots & vdots & ddots & vdots \ p_{n1} & p_{n2} & cdots & p_{nm} \ end{bmatrix}.$$
If you don't already have this matrix, first generate it by normalising the intensities of the pixels, so that they add up to one. Assuming you have this probability matrix, you can generate a random point with these probabilities by using the multinomial distribution $X sim text{Mu}(1, boldsymbol{P})$. To implement this you will need to map the positions in this matrix format to a single vector of ordered positions (e.g., reading left-to-right across each row), then generate a random value, and then map it back to matrix coordinates (e.g., using modular arithmetic). It is simple to create a vectorised function in R
to generate an arbitrary number of points from your image:
#Generate k random matrix points from image matrix
#The input object IMAGE is assumed to be your intensity matrix
#The output is a k x 2 matrix of coordinates for each of k coordinates
GENERATE <- function(IMAGE, k) { n <- nrow(IMAGE);
m <- ncol(IMAGE);
OUTPUT <- data.frame(Row = rep(0,k),
Column = rep(0,k));
RAND <- sample(1:(n*m), size = k, replace = TRUE,
prob = as.vector(IMAGE))
OUTPUT$Row <- 1 + RAND %/% n;
OUTPUT$Column <- RAND %% n;
OUTPUT }
This function takes an input matrix IMAGE
and a number k
and it generates a data frame with $k$ generated values using the image matrix for the probabilities. For each generated value there is a specified Row
and Column
generated.
Answered by Ben on December 29, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP