분석시각화 대회 코드 공유 게시물은
내용 확인 후
좋아요(투표) 가능합니다.
opencv 이미지 처리 질문
이미지에 텍스트를 넣어서 텍스트 이미지를 생성하는 실습을 해보고 있습니다.
텍스트는 255픽셀로, 텍스트의 테두리는 128로 배경은 0픽셀로 고정된 값을 넣어서
이미지를 생성하고 싶은데 아무리 해도 완성된 이미지를 살펴보면 제가 255, 128, 0 말고도
다른 픽셀들도 같이 이미지에 포함되어 있습니다. 혹시 뭐가 문제인가요?
np.unique(txt_img) 하면 0, 128, 255만 나와야 하는 거아닌가요?
제발 도와주세요... 며칠 째 이것만 붙잡고 있어서 너무 답답헙니다...ㅠ
import numpy as np import cv2 import random as rnd import matplotlib.pyplot as plt from PIL import Image, ImageFont, ImageDraw text = 'John I have many homework' font = '폰트 경로' font_size = 10 space_width = 1.0 fit = False image_font = ImageFont.truetype(font=font, size=font_size) space_width = image_font.getsize(' ')[0] * space_width # 단어별로 쪼개진 텍스트의 각 글자에 대해 크기를 계산 char_sizes = [image_font.getsize(char) for char in text] # 텍스트 너비와 높이 계산 text_width = sum(size[0] for size in char_sizes) + int(space_width) * (len(char_sizes) - 1) text_height = max(size[1] for size in char_sizes) txt_img = Image.new('RGBA', (text_width, text_height), (0, 0, 0, 255)) txt_draw = ImageDraw.Draw(txt_img) text_color = (255, 255, 255, 255) border_color = (128, 128, 128, 255) border_width = 1 # 테두리 두께 x_offset = 0 for char, size in zip(text, char_sizes): txt_draw.text((x_offset, 0), char, fill=text_color, font=image_font) x_offset += size[0] + int(space_width) if fit: txt_img = txt_img.crop(txt_img.getbbox()) else: txt_img = np.array(txt_img) txt_img_gray = cv2.cvtColor(txt_img, cv2.COLOR_RGBA2GRAY) txt_img_gray_not = cv2.bitwise_not(txt_img_gray) contours, _ = cv2.findContours(txt_img_gray_not, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(txt_img, contours, -1, border_color, 1, cv2.LINE_AA)
DACON Co.,Ltd | CEO Kookjin Kim | 699-81-01021
Mail-order-sales Registration Number: 2021-서울영등포-1704
Business Providing Employment Information Number: J1204020250004
#901, Eunhaeng-ro 3, Yeongdeungpo-gu, Seoul 07237
E-mail dacon@dacon.io |
Tel. 070-4102-0545
Copyright ⓒ DACON Inc. All rights reserved