春节没事干,想做一个程序员的福字,就写了一个。(通过OpenCV进行的图像处理)
更新于20190214,将0-9都用上了,并解决了图像变窄的问题。
源码
主程序
# coding=utf-8
from __future__ import print_function
from utls import *
import cv2
if __name__ == '__main__':
INPUT_PATH = "../img/xie.jpg"
OUTPUT_PATH = "../generateImg/xie.png"
img = cv2.imread(INPUT_PATH)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
h, w = img.shape
img = cv2.resize(img, (w/6, h/6))
img = reImg(img) # 变成十值图像(将将灰度图像的色彩空间转换为0-9的值)
lists = to2dList(img) # 生成01的字符串数组
img = toCharImg(img, lists) # 生成字符图片
cv2.imwrite(OUTPUT_PATH, img) # 保存生成的图片
# cv2.namedWindow("Happy", cv2.WINDOW_AUTOSIZE)
# cv2.imshow("Happy", img)
# cv2.waitKey()
工具类 utls.py
# coding=utf-8
import cv2
import numpy as np
chars = ['8', '6', '9', '5', '0', '2', '3', '4', '7', '1']
def reImg(img):
h, w = img.shape
min_value = np.min(img)
max_value = np.max(img)
x = (max_value - min_value) / (len(chars) - 1)
for i in range(h):
for j in range(w):
img[i][j] = (img[i][j] - min_value) / x
return img
def toString(img):
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
def to2dList(img):
lists = []
h, w = img.shape
for i in range(h):
string = []
for j in range(w):
string.append(chars[img[i][j]])
lists.append(string)
return lists
def toCharImg(img, lists):
# 将字符串画到图像上面
h, w = img.shape
img = np.full((8 * h, 8 * w), 255)
for i in range(h):
for j in range(len(lists[i])):
cv2.putText(img, lists[i][j], (j * 8, i * 8 + 7), cv2.FONT_HERSHEY_SCRIPT_SIMPLEX, 0.3, (0, 0, 0))
return img
处理结果
福字(1.0版本的)
火影忍者蝎(2.0版本)