import cv2
import numpy as np
from keras.models import load_model
from keras.datasets import cifar10
from PIL import Image, ImageDraw, ImageFont
img_row, img_height, img_depth = 32,32,3
classifier = load_model('/home/zzh/cifar_simple_cnn.h5')
# Loads the CIFAR dataset
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
color = True
scale = 4
def paint_chinese_opencv(im,chinese,position,fontsize,color):#opencv输出中文
img_PIL = Image.fromarray(cv2.cvtColor(im,cv2.COLOR_BGR2RGB))# 图像从OpenCV格式转换成PIL格式
font = ImageFont.truetype('SimHei.ttf',fontsize,encoding="utf-8")
#color = (255,0,0) # 字体颜色
#position = (100,100)# 文字输出位置
draw = ImageDraw.Draw(img_PIL)
draw.text(position,chinese,font=font,fill=color)# PIL图片上打印汉字 # 参数1:打印坐标,参数2:文本,参数3:字体颜色,参数4:字体
img = cv2.cvtColor(np.asarray(img_PIL),cv2.COLOR_RGB2BGR)# PIL图片转cv2 图片
return img
def draw_test(name, res, input_im, scale, img_row, img_height):
BLACK = [0,0,0]
res = int(res)
if res == 0:
pred = "灰机"
if res == 1:
pred = "汽车"
if res == 2:
pred = "鸟"
if res == 3:
pred = "猫"
if res == 4:
pred = "鹿"
if res == 5:
pred = "狗"
if res == 6:
pred = "小青蛙"
if res == 7:
pred = "马"
if res == 8:
pred = "船"
if res == 9:
pred = "卡车"
expanded_image = cv2.copyMakeBorder(input_im, 0, 0, 0, imageL.shape[0] ,cv2.BORDER_CONSTANT,value=BLACK)
if color == False:
expanded_image = cv2.cvtColor(expanded_image, cv2.COLOR_GRAY2BGR)
expanded_image = paint_chinese_opencv(expanded_image,str(pred),(150,40),32,(0,255,0))
cv2.imshow(name, expanded_image)
for i in range(1,20):
# rand = np.random.randint(0,len(x_test))
input_im = x_test[i]
imageL = cv2.resize(input_im, None, fx=scale, fy=scale, interpolation = cv2.INTER_CUBIC)
input_im = input_im.reshape(1,img_row, img_height, img_depth)
## Get Prediction
res = str(classifier.predict_classes(input_im, 1, verbose = 0)[0])
draw_test("Prediction", res, imageL, scale, img_row, img_height)
cv2.waitKey(0)
cv2.destroyAllWindows()