Reputation: 113
I couldn't found anything on this task while Googling, but I can't imagine no one has thought of doing this. Is there a way to generate random 2d data in the form of a letter of choice? So basically a function letter_random_data(letter)
that would output x
and y
coordinates (within some boundaries) that together with some noise form the chosen letter.
Upvotes: 0
Views: 161
Reputation: 44887
Here's one way to do it: Draw an image containing the letter (or text, more generally). Read the image into an array, and use it to accept or reject points drawn randomly in the box holding the image.
For example,
library(png)
getTextImage <- function(text) {
filename <- tempfile()
png(filename = filename)
plot.new()
cex <- 1
repeat {
if (strwidth(text, cex = 2*cex) > 1) break
if (strheight(text, cex = 2*cex) > 1) break
cex <- 2*cex
}
text(0.5, 0.5, text, cex = cex)
dev.off()
image <- readPNG(filename)
unlink(filename) # clean up file
if (length(dim(image)) == 3)
image <- image[,,1] # just keep one channel
image
}
randomText <- function(n, text) {
image <- getTextImage(text)
nx <- dim(image)[1]
ny <- dim(image)[2]
hits <- 0
x <- y <- numeric(n)
while (hits < n) {
tryx <- runif(1)
tryy <- runif(1)
keep <- image[round((nx-1)*tryx + 1), round((ny-1)*tryy + 1)] == 0
if (keep) {
hits <- hits + 1
# Need to rotate so it looks good
x[hits] <- tryy
y[hits] <- 1 - tryx
}
}
cbind(x, y)
}
plot(randomText(1000, "Hello"))
This produces the following plot:
Upvotes: 2