Djangoで画像CNNに読み込ませ、予測結果を返すコードを書きましたが、次のようなエラーが発生します。
python
1Exception Value: 2src is not a numpy array, neither a scalar 3 4 5self.params['pred'] = pred(image) ... 6▶ Local vars 7/Users//Downloads/image_pred/myapp/main.py in pred 8 9x = cv2.cvtColor(input_img, cv2.COLOR_BGR2GRAY) ... 10▶ Local vars
main.pyにformから取得した画像を読み込ませ、あらかじめ用意した変数(params)をレンダリングしています。
formからclean_dataで読み込んだ変数の形式がスカラーなので、画像でないということでしょうか?
ご教授お願いします。
python
1# views.py 2from django.shortcuts import render, redirect 3from django.http import HttpResponse 4from django.views.generic import TemplateView 5from .forms import PhotoForm 6from myapp.main import pred 7 8class MyappView(TemplateView): 9 def __init__(self): 10 self.params={'pred': 'idx', 11 'form': PhotoForm()} 12 def get(self, req): 13 return render(req, 'myapp/index.html', self.params) 14 15 def post(self, req): 16 form = PhotoForm(req.POST, req.FILES) 17 if not form.is_valid(): 18 raise ValueError('invalid fiorm') 19 20 image = form.cleaned_data['image'] 21 self.params['pred'] = pred(image) 22 return render(req, 'myapp.index.html', self.params)
python
1# forms.py 2from django import forms 3 4class PhotoForm(forms.Form): 5 6 image = forms.ImageField()
python
1# main.py 2from __future__ import print_function 3from __future__ import absolute_import 4import warnings 5import os 6import math 7import cv2 8import numpy as np 9import tensorflow as tf 10import pandas as pd 11import matplotlib.pyplot as plt 12from keras.models import load_model, Model 13from keras.optimizers import SGD 14from PIL import Image 15from keras import layers 16from keras.layers import Activation, Concatenate, AveragePooling2D, BatchNormalization 17from keras.layers import Conv2D, Dense, Input, Lambda, Flatten 18from keras.layers import GlobalMaxPooling2D, MaxPooling2D, GlobalAveragePooling2D 19from keras import backend as K 20from keras.applications.inception_resnet_v2 import preprocess_input 21 22 23 24def conv2d_bn(x, 25 filters, 26 kernel_size, 27 strides=1, 28 padding='same', 29 activation='relu', 30 use_bias=False, 31 name=None): 32 x = Conv2D(filters, 33 kernel_size, 34 strides=strides, 35 padding=padding, 36 use_bias=use_bias, 37 name=name)(x) 38 if not use_bias: 39 bn_axis = 1 if K.image_data_format() == 'channels_first' else 3 40 bn_name = None if name is None else name + '_bn' 41 x = BatchNormalization(axis=bn_axis, scale=False, name=bn_name)(x) 42 if activation is not None: 43 ac_name = None if name is None else name + '_ac' 44 x = Activation(activation, name=ac_name)(x) 45 return x 46 47 48def inception_resnet_block(x, scale, block_type, block_idx, activation='relu'): 49 50 if block_type == 'block35': 51 branch_0 = conv2d_bn(x, 32, 1) 52 branch_1 = conv2d_bn(x, 32, 1) 53 branch_1 = conv2d_bn(branch_1, 32, 3) 54 branch_2 = conv2d_bn(x, 32, 1) 55 branch_2 = conv2d_bn(branch_2, 48, 3) 56 branch_2 = conv2d_bn(branch_2, 64, 3) 57 branches = [branch_0, branch_1, branch_2] 58 elif block_type == 'block17': 59 branch_0 = conv2d_bn(x, 192, 1) 60 branch_1 = conv2d_bn(x, 128, 1) 61 branch_1 = conv2d_bn(branch_1, 160, [1, 7]) 62 branch_1 = conv2d_bn(branch_1, 192, [7, 1]) 63 branches = [branch_0, branch_1] 64 elif block_type == 'block8': 65 branch_0 = conv2d_bn(x, 192, 1) 66 branch_1 = conv2d_bn(x, 192, 1) 67 branch_1 = conv2d_bn(branch_1, 224, [1, 3]) 68 branch_1 = conv2d_bn(branch_1, 256, [3, 1]) 69 branches = [branch_0, branch_1] 70 else: 71 raise ValueError('Unknown Inception-ResNet block type. ' 72 'Expects "block35", "block17" or "block8", ' 73 'but got: ' + str(block_type)) 74 75 block_name = block_type + '_' + str(block_idx) 76 channel_axis = 1 if K.image_data_format() == 'channels_first' else 3 77 mixed = Concatenate(axis=channel_axis, name=block_name + '_mixed')(branches) 78 up = conv2d_bn(mixed, 79 K.int_shape(x)[channel_axis], 80 1, 81 activation=None, 82 use_bias=True, 83 name=block_name + '_conv') 84 85 x = Lambda(lambda inputs, scale: inputs[0] + inputs[1] * scale, 86 output_shape=K.int_shape(x)[1:], 87 arguments={'scale': scale}, 88 name=block_name)([x, up]) 89 if activation is not None: 90 x = Activation(activation, name=block_name + '_ac')(x) 91 return x 92 93 94def InceptionResNetV2(include_top=True, pooling=None, classes=13): 95 # Stem block: 35 x 35 x 192 96 img_input = Input(batch_shape=(None,100,100,3)) 97 x = conv2d_bn(img_input, 32, 3, strides=2, padding='valid') 98 x = conv2d_bn(x, 32, 3, padding='valid') 99 x = conv2d_bn(x, 64, 3) 100 x = MaxPooling2D(3, strides=2)(x) 101 x = conv2d_bn(x, 80, 1, padding='valid') 102 x = conv2d_bn(x, 192, 3, padding='valid') 103 x = MaxPooling2D(3, strides=2)(x) 104 105 # Mixed 5b (Inception-A block): 35 x 35 x 320 106 branch_0 = conv2d_bn(x, 96, 1) 107 branch_1 = conv2d_bn(x, 48, 1) 108 branch_1 = conv2d_bn(branch_1, 64, 5) 109 branch_2 = conv2d_bn(x, 64, 1) 110 branch_2 = conv2d_bn(branch_2, 96, 3) 111 branch_2 = conv2d_bn(branch_2, 96, 3) 112 branch_pool = AveragePooling2D(3, strides=1, padding='same')(x) 113 branch_pool = conv2d_bn(branch_pool, 64, 1) 114 branches = [branch_0, branch_1, branch_2, branch_pool] 115 channel_axis = 1 if K.image_data_format() == 'channels_first' else 3 116 x = Concatenate(axis=channel_axis, name='mixed_5b')(branches) 117 118 # 10x block35 (Inception-ResNet-A block): 35 x 35 x 320 119 for block_idx in range(1, 11): 120 x = inception_resnet_block(x, 121 scale=0.17, 122 block_type='block35', 123 block_idx=block_idx) 124 125 # Mixed 6a (Reduction-A block): 17 x 17 x 1088 126 branch_0 = conv2d_bn(x, 384, 3, strides=2, padding='valid') 127 branch_1 = conv2d_bn(x, 256, 1) 128 branch_1 = conv2d_bn(branch_1, 256, 3) 129 branch_1 = conv2d_bn(branch_1, 384, 3, strides=2, padding='valid') 130 branch_pool = MaxPooling2D(3, strides=2, padding='valid')(x) 131 branches = [branch_0, branch_1, branch_pool] 132 x = Concatenate(axis=channel_axis, name='mixed_6a')(branches) 133 134 # 20x block17 (Inception-ResNet-B block): 17 x 17 x 1088 135 for block_idx in range(1, 21): 136 x = inception_resnet_block(x, 137 scale=0.1, 138 block_type='block17', 139 block_idx=block_idx) 140 141 # Mixed 7a (Reduction-B block): 8 x 8 x 2080 142 branch_0 = conv2d_bn(x, 256, 1) 143 branch_0 = conv2d_bn(branch_0, 384, 3, strides=2, padding='valid') 144 branch_1 = conv2d_bn(x, 256, 1) 145 branch_1 = conv2d_bn(branch_1, 288, 3, strides=2, padding='valid') 146 branch_2 = conv2d_bn(x, 256, 1) 147 branch_2 = conv2d_bn(branch_2, 288, 3) 148 branch_2 = conv2d_bn(branch_2, 320, 3, strides=2, padding='valid') 149 branch_pool = MaxPooling2D(3, strides=2, padding='valid')(x) 150 branches = [branch_0, branch_1, branch_2, branch_pool] 151 x = Concatenate(axis=channel_axis, name='mixed_7a')(branches) 152 153 # 10x block8 (Inception-ResNet-C block): 8 x 8 x 2080 154 for block_idx in range(1, 10): 155 x = inception_resnet_block(x, 156 scale=0.2, 157 block_type='block8', 158 block_idx=block_idx) 159 x = inception_resnet_block(x, 160 scale=1., 161 activation=None, 162 block_type='block8', 163 block_idx=10) 164 165 # Final convolution block: 8 x 8 x 1536 166 x = conv2d_bn(x, 1536, 1, name='conv_7b') 167 168 # Classification block 169 x = GlobalAveragePooling2D(name='avg_pool')(x) 170 output = Dense(classes, activation='softmax', name='predictions')(x) 171 172 return Model(img_input, output) 173 174 175def pred(input_img): 176 sess = tf.Session() 177 K.set_session(sess) 178 cnt=pd.read_csv('/Users/d/image_pred/myapp/weight_dir/cnt.csv') 179 cnt=cnt.drop('Unnamed: 0', axis=1) 180 cnt=cnt.drop('cnt', axis=1) 181 182 183 dic = {} 184 for i, v in cnt.iterrows(): 185 dic.setdefault(v['index'], []).append([v['brand_id'], v['model_id'], v['cate_id']]) 186 187 x = cv2.cvtColor(input_img, cv2.COLOR_BGR2GRAY) 188 x = cv2.resize(x, (100, 100)) 189 x = np.expand_dims(x, axis=0) 190 image = preprocess_input(x) 191 192 test_model = InceptionResNetV2(include_top=True) 193 test_model.load_weights('/Users/d/image_pred/myapp/weight_dir/incep_model.h5') 194 test_model.compile(optimizer=SGD(lr=0.01, momentum=0.9, decay=0.001, nesterov=True), 195 loss='categorical_crossentropy', 196 metrics=['accuracy']) 197 198 y_pred = test_model.predict(image) 199 top_k=sess.run(tf.nn.top_k(y_pred,k=3,sorted=True)) 200 idxs=list(np.reshape(top_k[1],(3,))) 201 for idx, v in dic.items(): 202 if idx in idxs: 203 print('brand_id:{} model_id:{}, cate_id:{}'.format(v[0][0], v[0][1], v[0][2])) 204
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。