Character picture is a picture composed of letters, punctuation marks or other characters. It came into being in the Internet era and is widely used in chat software. In this article, we will look at how to turn your favorite picture into character picture.

Static image

First, we will demonstrate the static image into character painting, function implementation mainly use Python library for OpenCV, install using PIP install opencv-python command can be.

The basic idea of function realization is as follows: the pixel information is grouped into 3 or 5 categories by clustering. The category of darkest color is represented by digital intensity, the category of shadow is represented by horizontal bars (-), and the bright part is represented by blank.

The main code is as follows:

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 # get labels, centroids compactness, labels, centroids = cv2.kmeans(frame_array, K, None, criteria, 10, Uint8 (Centroids) # labels are arranged in random order. Flatten () centroids_sorted = sorted(centroids) 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 = allels.flatten () # Turn all labels to the actual list of allels.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), Uint8) # Create 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: PutText (canvas, "-", (x, y), FONT_HERSHEY_PLAIN, 0.4, 0, 1) x += 6 y += 6 return canvasCopy the code

The original picture is as follows:

The renderings are as follows:

GIF dynamic figure

The main Python libraries used for this function are Imageio and Pillow. PIP install imageio/Pillow command is used to install this function.

The basic idea of function realization is as follows:

  • Split each frame of the GIF image into a still image
  • Turn all static images into character paintings
  • Recompose all character drawings into GIFs

The main code is as follows:

Def GIF2pic (file, ascii_chars, isgray, font, scale): Font: ImageFont Object scale: Im = image.open (file) path = os.getcwd() if(not os.path.exists(path+"/ TMP ")): Os. mkdir(path+"/ TMP ") os.chdir(path+"/ TMP ") # delete the contents of the TMP directory for f in os.listdir(path+"/ TMP "): os.remove(f) try: while 1: Split ('.')[0]+'_tmp_'+ STR (current)+'.png' # Save each frame im.save(name) # process each frame as a character drawing Img2ascii (name, ascii_chars, isgray, font, scale) # continue processing next frame im.seek(current+1) except: 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 # convert Image to RGB mode im = image.open (img).convert('RGB') Raw_height = int(im.height * scale) Block_y = int(font_x * scale) block_y = int(font_y * scale) # Int (raw_width/block_x) h = int(raw_height/block_y) # resize((w, h), 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) # create a new canvas img_txt = image.new ('RGB', (raw_width,) 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) 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)Copy the code

The original picture is as follows:

Black and white renderings are as follows:

The color renderings are as follows:

conclusion

This article uses Python to demonstrate how to convert static images and GIFs into character drawings. If you are interested, you can convert your favorite image. If you are not satisfied with the conversion, you can also modify the code to change the effect to your own satisfaction.

PS: If you can’t solve the problem, you can click the link below to get it by yourself

Free Python learning materials and group communication solutions click to join