背景:
为了提升用户欣赏书法图片的体验,需要从高清TIF图片中把每个字都切割出来,手动切割太麻烦,所以利用opencv自动识别图片中的文字,并将每个文字切割保存。
实现代码:
import cv2
import os
import sys
import numpy as np
#自动切割单字
def split_image_by_auto(filePath, saveTo, threshold, margin):
# img = cv2.imread(filePath)
filename = filePath.split('\\')[-1].split(".")[0]
print(filename)
if os.path.exists(saveTo + filename) == False :
os.mkdir(saveTo + filename)
img = cv2.imdecode(np.fromfile(filePath, dtype=np.uint8), -1)
sp = img.shape
print("图像信息:", sp)
h = sp[0]
w = sp[1]
c = sp[2]
#save 一份完整的
resize = cv2.resize(img, (int(w * 1000 / h), 1000))
# cv2.imwrite(saveTo + filename+"_0.jpg", resize)
cv2.imencode('.jpg', resize)[1].tofile(saveTo + filename+"/0.jpg") #支持中文
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
retval, threshold_img = cv2.threshold(gray_img, 120,255,cv2.THRESH_BINARY_INV) #阈值的作用是根据设定的值处理图像的灰度值,比如灰度大于某个数值像素点保留。通过阈值以及有关算法可以实现从图像中抓取特定的图形,比如去除背景等
cv2.imshow("threshold", threshold_img)
#垂直投影分割图像
gray_value_x = []
for i in range(w):
white_value = 0
# 显示进度条
sys.stdout.write('\r>>[%s] 第一步进度:%.1f%% %s' % (filename, float(i) / float(w) * 100.0, "▓" * int(i*100 / w)))
sys.stdout.flush()
for j in range(h):
if threshold_img[j, i] == 255: #表示白色,这里已经是转换为灰度的,用一个字节表示(8位),正常彩色的是RGB(3个字节