亲宝软件园·资讯

展开

与Django结合利用模型对上传图片预测的实例详解

人气:0

1 预处理

(1)对上传的图片进行预处理成100*100大小

def prepicture(picname):
  img = Image.open('./media/pic/' + picname)
  new_img = img.resize((100, 100), Image.BILINEAR)
  new_img.save(os.path.join('./media/pic/', os.path.basename(picname)))

(2)将图片转化成数组

def read_image2(filename):
  img = Image.open('./media/pic/'+filename).convert('RGB')
  return np.array(img)

2 利用模型进行预测

def testcat(picname):
  # 预处理图片 变成100 x 100
  prepicture(picname)
  x_test = []

  x_test.append(read_image2(picname))

  x_test = np.array(x_test)

  x_test = x_test.astype('float32')
  x_test /= 255

  keras.backend.clear_session() #清理session反复识别注意
  model = Sequential()
  model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3)))
  model.add(Conv2D(32, (3, 3), activation='relu'))
  model.add(MaxPooling2D(pool_size=(2, 2)))
  model.add(Dropout(0.25))

  model.add(Conv2D(64, (3, 3), activation='relu'))
  model.add(Conv2D(64, (3, 3), activation='relu'))
  model.add(MaxPooling2D(pool_size=(2, 2)))
  model.add(Dropout(0.25))

  model.add(Flatten())
  model.add(Dense(256, activation='relu'))
  model.add(Dropout(0.5))
  model.add(Dense(4, activation='softmax'))

  sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
  model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])


  model.load_weights('./cat/cat_weights.h5')
  classes = model.predict_classes(x_test)[0]
  # target = ['布偶猫', '孟买猫', '暹罗猫', '英国短毛猫']
  # print(target[classes])
  return classes

3 与Django结合

在views中调用模型进行图片分类

def catinfo(request):
  if request.method == "POST":
    f1 = request.FILES['pic1']
    # 用于识别
    fname = '%s/pic/%s' % (settings.MEDIA_ROOT, f1.name)
    with open(fname, 'wb') as pic:
      for c in f1.chunks():
        pic.write(c)
    # 用于显示
    fname1 = './static/img/%s' % f1.name
    with open(fname1, 'wb') as pic:
      for c in f1.chunks():
        pic.write(c)

    num = testcat(f1.name)
    # 有的数据库id从1开始这样就会报错
    # 因此原本数据库中的id=0被系统改为id=4
    # 遇到这样的问题就加上
    # if(num == 0):
    #  num = 4 
    # 通过id获取猫的信息
    name = models.Catinfo.objects.get(id = num)
    return render(request, 'info.html', {'nameinfo': name.nameinfo, 'feature': name.feature, 'livemethod': name.livemethod, 'feednn': name.feednn, 'feedmethod': name.feedmethod, 'picname': f1.name})
  else:
    return HttpResponse("上传失败!")

以上这篇与Django结合利用模型对上传图片预测的实例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论