Python 그림 문자 변환 예제 구현(정적 그림,gif 모두 가능)

문자 화 는 알파벳,구두점 또는 다른 문자 로 구 성 된 그림 으로 인터넷 시대 에 생 겨 나 채 팅 소프트웨어 에서 많이 사용 되 었 다.본 고 는 자신 이 좋아 하 는 그림 을 어떻게 문자 화 로 바 꾸 는 지 살 펴 보 자.
정적 그림
우선 정적 그림 을 문자 그림 으로 바 꾸 는 것 을 보 여 줍 니 다.주로 사용 되 는 Python 라 이브 러 리 는 OpenCV 이 고 pip install opencv-python 명령 을 설치 하면 됩 니 다.
기능 실현 의 기본 적 인 사 고 는 집합 을 이용 하여 픽 셀 정 보 를 3 또는 5 가지 로 모 으 고 색채 가 가장 짙 은 유형 은 디지털 밀집 도 로 표시 하 며 그림자 의 유형 은 가로 줄(-)로 표시 하고 밝 은 부분 은 공백 으로 표시 하 는 것 이다.
주요 코드 는 다음 과 같 습 니 다.

def img2strimg(frame, K=5):  
  if type(frame) != np.ndarray:
    frame = np.array(frame)
  height, width, *_ = frame.shape 
  frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  frame_array = np.float32(frame_gray.reshape(-1))
  criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
  flags = cv2.KMEANS_RANDOM_CENTERS
  #    labels(  )、centroids(  )
  compactness, labels, centroids = cv2.kmeans(frame_array, K, None, criteria, 10, flags)
  centroids = np.uint8(centroids)
  # labels             ,          
  centroids = centroids.flatten()
  centroids_sorted = sorted(centroids)
  #      centroids      ,0    
  centroids_index = np.array([centroids_sorted.index(value) for value in centroids])
  bright = [abs((3 * i - 2 * K) / (3 * K)) for i in range(1, 1 + K)]
  bright_bound = bright.index(np.min(bright))
  shadow = [abs((3 * i - K) / (3 * K)) for i in range(1, 1 + K)]
  shadow_bound = shadow.index(np.min(shadow))
  labels = labels.flatten()
  #   labels             
  labels = centroids_index[labels]
  #     
  labels_picked = [labels[rows * width:(rows + 1) * width:2] for rows in range(0, height, 2)]
  canvas = np.zeros((3 * height, 3 * width, 3), np.uint8)
	#               
  canvas.fill(255)
  y = 8
  for rows in labels_picked:
    x = 0
    for cols in rows:
      if cols <= shadow_bound:
        cv2.putText(canvas, str(random.randint(2, 9)),
              (x, y), cv2.FONT_HERSHEY_PLAIN, 0.45, 1)
      elif cols <= bright_bound:
        cv2.putText(canvas, "-", (x, y),
              cv2.FONT_HERSHEY_PLAIN, 0.4, 0, 1)
      x += 6
    y += 6
  return canvas
원 도 는 다음 과 같다.

효과 도 는 다음 과 같다.

GIF 움 직 이 는 그림
다음은 GIF 를 문자 그림 으로 바 꾸 는 것 을 보 여 드 리 겠 습 니 다.주로 사용 되 는 Python 라 이브 러 리 는 imageio,Pillow 이 고 pip install imageio/Fillow 명령 을 설치 하면 됩 니 다.
기능 실현 의 기본 적 인 사고방식 은 다음 과 같다.
gif 그림 의 각 프레임 을 정적 그림 으로 나 눕 니 다.
모든 정적 그림 을 문자 그림 으로 변환 합 니 다.
모든 문 자 를 gif 로 다시 합성
주요 코드 는 다음 과 같 습 니 다.

#    gif           
def gif2pic(file, ascii_chars, isgray, font, scale):
  '''
  file: gif   
  ascii_chars:          
  isgray:     
  font: ImageFont   
  scale:     
  '''
  im = Image.open(file)
  path = os.getcwd()
  if(not os.path.exists(path+"/tmp")):
    os.mkdir(path+"/tmp")
  os.chdir(path+"/tmp")
  #    tmp      
  for f in os.listdir(path+"/tmp"):
    os.remove(f)
  try:
    while 1:
      current = im.tell()
      name = file.split('.')[0]+'_tmp_'+str(current)+'.png'
      #        
      im.save(name)
      #           
      img2ascii(name, ascii_chars, isgray, font, scale)
      #        
      im.seek(current+1)
  except:
    os.chdir(path)

#            ASCII   
def get_char(ascii_chars, r, g, b):
  length = len(ascii_chars)
  gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
  return ascii_chars[int(gray/(256/length))]


#          
def img2ascii(img, ascii_chars, isgray, font, scale):
  scale = scale
  #        RGB   
  im = Image.open(img).convert('RGB')
  #            
  raw_width = int(im.width * scale)
  raw_height = int(im.height * scale)
  #           
  font_x, font_y = font.getsize(' ')
  #        
  block_x = int(font_x * scale)
  block_y = int(font_y * scale)
  #           
  w = int(raw_width/block_x)
  h = int(raw_height/block_y)
  #             
  im = im.resize((w, h), Image.NEAREST)
  # txts   colors          ASCII     RGB  
  txts = []
  colors = []
  for i in range(h):
    line = ''
    lineColor = []
    for j in range(w):
      pixel = im.getpixel((j, i))
      lineColor.append((pixel[0], pixel[1], pixel[2]))
      line += get_char(ascii_chars, pixel[0], pixel[1], pixel[2])
    txts.append(line)
    colors.append(lineColor)
  #      
  img_txt = Image.new('RGB', (raw_width, raw_height), (255, 255, 255))
  #    ImageDraw       ASCII
  draw = ImageDraw.Draw(img_txt)
  for j in range(len(txts)):
    for i in range(len(txts[0])):
      if isgray:
        draw.text((i * block_x, j * block_y), txts[j][i], (119,136,153))
      else:
        draw.text((i * block_x, j * block_y), txts[j][i], colors[j][i])
  img_txt.save(img)

#    tmp         gif
def pic2gif(dir_name, out_name, duration):
  path = os.getcwd()
  os.chdir(dir_name)
  dirs = os.listdir()
  images = []
  num = 0
  for d in dirs:
    images.append(imageio.imread(d))
    num += 1
  os.chdir(path)
  imageio.mimsave(out_name + '_ascii.gif',images,duration = duration)
원 도 는 다음 과 같다.

흑백 효과 도 는 다음 과 같다.

컬러 효과 그림 은 다음 과 같 습 니 다.

총결산
본 고 는 Python 을 이용 하여 정적 그림 과 GIF 를 문자 그림 으로 바 꾸 는 방법 을 보 여 주 었 습 니 다.관심 이 있 으 면 자신 이 좋아 하 는 그림 을 돌려 보 세 요.전환 효과 에 만족 하지 않 으 면 코드 를 수정 하여 만 족 스 러 운 효과 로 바 꿀 수도 있 습 니 다.
예시 코드:py-ascii
이상 은 Python 이 그림 문자 화 를 실현 하 는 예제(정적 그림,gif 모두 가능)의 상세 한 내용 입 니 다.python 그림 문자 화 에 관 한 자 료 는 다른 관련 글 을 주목 하 십시오!

좋은 웹페이지 즐겨찾기