### (2)numpy整理图片数据
def get_train_Dataset(file_name):
weight = 160
height = 60
files =os.listdir(file_name)
fileList = [file_name+"/"+f for f in files]
labels = []
x = np.zeros([len(fileList),height*weight])
dict_labels = {}
for index,label in enumerate(list_labels):
dict_labels[label] = index
threshold = 195 #阈值
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
for index,f_img in enumerate(fileList):
#处理label
label = f_img.split("_")[-1].split(".")[0]
label_split = [dict_labels[la] for la in label]
labels.append(label_split)
#处理图片转换为为数组
img = cv2.imread(f_img,cv2.IMREAD_GRAYSCALE)
median = cv2.medianBlur(img, 5)
image = Image.fromarray(cv2.cvtColor(median,cv2.COLOR_BGR2RGB))
img= image.convert("L") #灰度
img = img.point(table, '1') #二值化
# 2.构造模型训练及保存模型参数
### (1)模块导入
from keras.models import load_model
import numpy as np
from PIL import Image
from keras.models import Model
from keras.layers import Input,Dense,Convolution2D,MaxPooling2D,Flatten,Dropout
from keras.optimizers import Adam
from keras.utils import np_utils
from keras.utils import plot_model
#数据准备
CLASS_NUM = 62
weight = 160
height = 60
data = np.load("./image_train_and_test06.npz")
X_train, X_test,y_train, y_test =data["train_x"],data["test_x"],data["train_y"],data["test_y"]
threshold = 215 #阈值
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
median = cv2.medianBlur(result, 5)
image = Image.fromarray(cv2.cvtColor(median,cv2.COLOR_BGR2RGB))
img= image.convert("L") #灰度
img = img.point(table, '1') #二值化
img = img.resize((weight,height))
X_test = np.array(img).reshape(-1,height*weight)
X_test = X_test.reshape(-1,height,weight,1)/255
prep1,prep2,prep3,prep4 = model.predict(X_test)
prep = np.hstack((np.argmax(prep1,axis=1).reshape(-1,1),np.argmax(prep2,axis=1).reshape(-1,1),\
np.argmax(prep3,axis=1).reshape(-1,1),np.argmax(prep4,axis=1).reshape(-1,1))).reshape(-1,4)
import string
letters = string.digits+string.ascii_letters
list_labels = [s for s in letters]
num_dicts = {}
for index,label in enumerate(list_labels):
num_dicts[index] = label
new_labels = []
for i in range(prep.shape[0]):
labels = []
for j in range(prep.shape[1]):
labels.append(num_dicts[prep[i,j]])
new_labels.append("".join(labels))
return new_labels[0]
#result = prep_image("./vaild/0_t76j.png")
print(result)