Python转字符图

春节没事干,想做一个程序员的福字,就写了一个。(通过OpenCV进行的图像处理)

源码

主程序

# coding=utf-8
# 用的python2.7
from __future__ import print_function
import cv2
from utls import reimg, toString

imgOriginal = cv2.imread("../img/hu.jpeg")
h, w, un = imgOriginal.shape
size = (100, 100 * h / w)
imgOriginal = cv2.resize(imgOriginal, size)
img = cv2.cvtColor(imgOriginal, cv2.COLOR_BGR2GRAY)
# 变成二值图像
img = reimg(img)
# 生成01的字符串数组
lists = toString(img)
# 将字符串画到图像上面
h, w = img.shape
for i in range(h):
    for j in range(w):
        img[i][j] = 255
newSize = (800, 800 * h / w)
img = cv2.resize(img, newSize)
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
for i in range(h):
    cv2.putText(img, lists[i], (0, i * 8), cv2.FONT_ITALIC, 0.3, (0, 0, 0))
newSize = (800, int(800 / 3 * 2.5))
img = cv2.resize(img, newSize)
cv2.imshow("Happy", img)
cv2.waitKey()

工具类 utls.py

def reimg(img):
    h, w = img.shape
    min_value = 255
    max_value = 0
    for i in range(h):
        for j in range(w):
            if img[i][j] < min_value:
                min_value = img[i][j]
            if img[i][j] > max_value:
                max_value = img[i][j]
    x = (max_value - min_value) / 4
    for i in range(h):
        for j in range(w):
            img[i][j] = (img[i][j] - min_value) / x
    return img

# 自行修改字符数组,调节图片效果
def toString(img):
    chars = ['8', '6', '3', '2', '1']
    lists = []
    h, w = img.shape
    for i in range(h):
        string = ""
        for j in range(w):
            string = string + chars[img[i][j]]
        lists.append(string)
    return lists

处理结果

福字
Python转字符图
卡通人物
Python转字符图