Get pixel array of a Char

I am doing image processing work where I need to be able to manipulate images as arrays. I would like to make an array with values 0 or 1 such that the 1’s make the shape of a given letter. It is proving surprisingly difficult to find an elegant way to do this.

An example of what I would like:

function makeLetter(c::Char,nPixels::Int)
    # code....
end

makeLetter('o',10) 

 0  0  0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0  0  0
 0  0  0  1  1  1  1  0  0  0
 0  0  1  1  0  0  1  1  0  0
 0  0  1  1  0  0  1  1  0  0
 0  0  1  1  0  0  1  1  0  0
 0  0  1  1  0  0  1  1  0  0
 0  0  0  1  1  1  1  0  0  0
 0  0  0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0  0  0

I can imagine some clunky ways to do this, like saving .pngs of all the letters and then importing them and converting to arrays. Is there a better way using some handy Julia package? Preferably it would not involve saving auxiliary files.

(Remark: Having the array values be 0 or 1 is just for simplicity. If they are e.g. Floats or UInts in some other range, that’s fine.)

You could use GitHub - JuliaGraphics/FreeTypeAbstraction.jl: A Julian abstraction layer over FreeType.jl for that

2 Likes

The suggestion of ericphanson worked with some modifications, which I’m recording here for posterity (the package linked has no documentation, but works wonderfully once you figure it out). I followed the description in the package readme, but got an error when I ran the line face = FTFont("hack_regular.ttf"). There was no such file. I downloaded the required file from this link. Then I replaced the above call with face = FTFont("path\\to\\file").

The next line of the readme, img, metric = renderface(face, 'C'), also errored. It turns out it requires a third argument which is an integer. This has something to do with the image size, though it’s not exactly the size in pixels. Anyhow, with something like img, metric = renderface(face, 'C',100), I got a result.

1 Like

I have suggested this improvement to the readme based on your feedback, hopefully that will help clarify it for the next person!

Thanks! However, FYI part of your suggested change also does not work for me. findfont("juliamono") returns nothing, and it is unclear to me how to remedy this.

ah ok, in that case you need to choose the name of a font installed on your system. I’ll update my PR to add a comment. juliamono is just an example