Draw text on an angle (rotated) in Python

前端 未结 2 744
日久生厌
日久生厌 2021-01-13 12:27

I am drawing text onto a numpy array image in Python (using a custom font). Currently I am converting the image to PIL, drawing the text and then converting back to a numpy

2条回答
  •  逝去的感伤
    2021-01-13 13:02

    Using matplotlib, first visualize array and draw on it, get the raw data from the figure back. Pro: both tools are quite high level and let you deal with many details of the process. ax.annotate() offers flexibility for where and how to draw and set font properties, and plt.matshow() offers flexibility that lets you deal with aspects of array visualization.

    import matplotlib.pyplot as plt
    import scipy as sp
    
    # make Data array to draw in
    M = sp.zeros((500,500))
    
    dpi = 300.0
    
    # create a frameless mpl figure
    fig, axes = plt.subplots(figsize=(M.shape[0]/dpi,M.shape[1]/dpi),dpi=dpi)
    axes.axis('off')
    fig.subplots_adjust(bottom=0,top=1.0,left=0,right=1)
    axes.matshow(M,cmap='gray')
    
    # set custom font
    import matplotlib.font_manager as fm
    ttf_fname = '/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-B.ttf'
    prop = fm.FontProperties(fname=ttf_fname)
    
    # annotate something
    axes.annotate('ABC',xy=(250,250),rotation=45,fontproperties=prop,color='white')
    
    # get fig image data and read it back to numpy array
    fig.canvas.draw()
    w,h = fig.canvas.get_width_height()
    Imvals = sp.fromstring(fig.canvas.tostring_rgb(),dtype='uint8')
    ImArray = Imvals.reshape((w,h,3))
    

提交回复
热议问题