| Reference | Downloads | Github

Extract width of letters when using a monospaced font



Is there a way to extract the width of the letters when using a monospaced font?
When using boundingBox, it returns (logically) the same width for each letter.
However, is there a way to extract which pixels are used by a letter?
When knowing the x-coordinates of the two extremes, I could calculate the width.
Any ideas?

Thank you,


Not thoroughly tested, but something like this might give you the extent of each letter:

def letter_extent(text_stim, win):

    import string

    import numpy as np

    bg_255 = np.round(
        (win.color + 1.0) / 2.0 * 255.0

    letter_sizes = {}

    for letter in string.letters:

        text_stim.text = letter



        cap = np.array(win.getMovieFrame())

        win.movieFrames = []

        letter_pix = np.any(cap != bg_255, axis=-1)

        i_letter_pix = np.argwhere(letter_pix)

        letter_size = np.ptp(i_letter_pix, axis=0)

        # xy
        letter_sizes[letter] = letter_size.tolist()[::-1]

    return letter_sizes


thank you, extremely helpful.

could you explain a bit what you do here:

bg_255 = np.round(
        (win.color + 1.0) / 2.0 * 255.0

I think you look at the the pixels that aren’t white, but I am not exactly sure?


That section is to determine the colour of the background, so we can look at pixels that aren’t the colour of the background and assume they are due to the text. The background colour is available in win.color, but it is in the -1:+1 range, rather than the 0:255 of the screen capture - so we convert it to 0:255 here.