import cv2
import random
import numpy as np
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
compactness, labels, centroids = cv2.kmeans(frame_array, k, None, criteria, 10, flags)
centroids = sorted(centroids, key=lambda x: x[0])
ascii_char = [chr(int(i)) for i in range(0, 256)]
char_len = len(ascii_char)
stringimg = ""
for i in range(height):
for j in range(width):
index = int(labels[i * width + j])
try:
stringimg += ascii_char[int(centroids[index][0] * (char_len - 1) / 255)]
except Exception as e:
stringimg += " "
stringimg += "\n"
return stringimg
暂无评论