머신러닝/Computer Vision

[Python/PIL] 텍스트에 취소선 넣기

Js.Y 2023. 5. 4. 13:46
728x90
반응형
def strike(draw, img, font, text):
    
    # Get the image, and calculate the average of font thickness.
    twidth, theight = img.size
    lx, ly = twidth, theight/2
    thickness = 2 if twidth >200 or theight > 200 else 1
    draw.line((0, ly, lx, ly), fill="black", width=thickness) # [0, height/2] ~ [width, height/2]
    
    
# "*"처럼 위로 올려붙는 특수 문자의 경우, font의 getmask함수로 영역을 잡아줘야 함.    
def special_strike(draw, img, font, text):
    text_bbox = font.getmask(text).getbbox() #"***의 박스"(tx, ty, bx, by)
    twidth, theight = img.size
    lx, ly = twidth, (text_bbox[3] - text_bbox[1])/2
    thickness = 2 if twidth >200 or theight > 200 else 1
    draw.line((0, ly, lx, ly), fill="black", width=thickness) # [0, height/2] ~ [width, height/2]


font = ImageFont.truetype(font_nm, size=10)
draw = ImageDraw.Draw(target_img)
draw.text(
    (0, 0),
    sentence,
    fill=(0, 0, 0, 255),
    font=font
)

strike(draw, target_img, font, sentence)

결과물

728x90
반응형