У меня возникли проблемы с моделью классификатора изображений, разработанной на Python, которую я хочу использовать в промышленном приложении C#.
Вот структура модели:
Tensorflow.InvalidArgumentError
HResult=0x80131500
Message=Incompatible shapes: [1,1,1,32] vs. [1,200,150,3]
[[{{node sequential_1/conv2d_1/add}}]]
Source=Tensorflow.Binding
StackTrace:
at Tensorflow.Status.Check(Boolean throwException)
at Tensorflow.BaseSession._call_tf_sessionrun(KeyValuePair`2[] feed_dict, TF_Output[] fetch_list, List`1 target_list)
at Tensorflow.BaseSession._do_run(List`1 target_list, List`1 fetch_list, Dictionary`2 feed_dict)
at Tensorflow.BaseSession._run(Object fetches, FeedItem[] feed_dict)
at Tensorflow.BaseSession.run(Tensor fetche, FeedItem[] feed_dict)
at Test2.Form1.EvaluarImagen(String RutaImagen) in D:\Soft\Soft\C#\LastVersion\Test2\Form1.cs:line 103
at Test2.Form1.button1_Click(Object sender, EventArgs e) in D:\Soft\Soft\C#\LastVersion\Test2\Form1.cs:line 26
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(HWND hWnd, MessageId msg, WPARAM wparam, LPARAM lparam)
Может кто-нибудь мне помочь? Я в отчаянии
Спасибо всем
У меня возникли проблемы с моделью классификатора изображений, разработанной на Python, которую я хочу использовать в промышленном приложении C#. Вот структура модели: [code]model = Sequential([ Conv2D(32, (3, 3), activation='relu', input_shape=(img_height, img_width, 3)), MaxPooling2D((2, 2)), Conv2D(64, (3, 3), activation='relu'), MaxPooling2D((2, 2)), Conv2D(128, (3, 3), activation='relu'), MaxPooling2D((2, 2)), Flatten(), Dense(512, activation='relu'), Dropout(0.5), Dense(len(class_names), activation='softmax') ]) [/code] Вот код, который я использую на C#: [code]var modelfile = "D:\\Soft\\Soft\\C#\\LastVersion\\frozen_model.pb"; var labels = new[] { "ORANGE", "BANANA", "APPLE", "MIX" };
var graph = new Graph().as_default(); graph.Import(File.ReadAllBytes(modelfile));
using (var session = tf.Session(graph)) { var tensor = ImageToTensor(RutaImagen);
var input_op = graph.OperationByName("sequential_1/conv2d_1/convolution"); var output_op = graph.OperationByName("sequential_1/dense_1_2/Softmax");
// this next line gives me a Runtime Error var result = session.run(output_op.outputs[0], (input_op.outputs[0], tensor));
var results = result.ToArray(); float totalConfidence = results.Sum();
int[] quantized = Quantized(results);
label1.Text = "Resultados cuantizados:\n"; for (int i = 0; i < results.Length; i++) { label1.Text += $"{labels[i]}:\n" + $" Valor original: {results[i]:0.000}\n" + $" Probabilidad: {results[i] * 100:0.00}%\n" + $" Normalizado: {(results[i] / totalConfidence) * 100:0.00}%\n" + $" Cuantizado: {(results[i] >= 0.5 ? "Probable" : "No probable")}\n"; } [/code] Код функции ImageToTensor, которую я вызываю для предварительной обработки изображения: [code] private static NDArray ImageToTensor(string file) { Bitmap bitmap = new Bitmap(file); Bitmap resizedBitmap = new Bitmap(bitmap, new Size(imgWidth, imgHeight));
// Convertir la imagen a un tensor float[,,,] input = new float[1, imgHeight, imgWidth, 3]; for (int y = 0; y < imgHeight; y++) { for (int x = 0; x < imgWidth; x++) { Color pixel = resizedBitmap.GetPixel(x, y); input[0, y, x, 0] = pixel.R / 255.0f; input[0, y, x, 1] = pixel.G / 255.0f; input[0, y, x, 2] = pixel.B / 255.0f; } } //return new DenseTensor(input); return np.array(input); } [/code] И, наконец, ошибка выполнения: При выполнении var result = session.run(output_op.outputs[0], (input_op.outputs[0], tensor )); [code]Tensorflow.InvalidArgumentError HResult=0x80131500 Message=Incompatible shapes: [1,1,1,32] vs. [1,200,150,3] [[{{node sequential_1/conv2d_1/add}}]] Source=Tensorflow.Binding StackTrace: at Tensorflow.Status.Check(Boolean throwException) at Tensorflow.BaseSession._call_tf_sessionrun(KeyValuePair`2[] feed_dict, TF_Output[] fetch_list, List`1 target_list) at Tensorflow.BaseSession._do_run(List`1 target_list, List`1 fetch_list, Dictionary`2 feed_dict) at Tensorflow.BaseSession._run(Object fetches, FeedItem[] feed_dict) at Tensorflow.BaseSession.run(Tensor fetche, FeedItem[] feed_dict) at Test2.Form1.EvaluarImagen(String RutaImagen) in D:\Soft\Soft\C#\LastVersion\Test2\Form1.cs:line 103 at Test2.Form1.button1_Click(Object sender, EventArgs e) in D:\Soft\Soft\C#\LastVersion\Test2\Form1.cs:line 26 at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(HWND hWnd, MessageId msg, WPARAM wparam, LPARAM lparam)
[/code] Может кто-нибудь мне помочь? Я в отчаянии Спасибо всем