Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我需要一个带未处理异常的遍历问题_C#_Tensorflow - Fatal编程技术网

C# 我需要一个带未处理异常的遍历问题

C# 我需要一个带未处理异常的遍历问题,c#,tensorflow,C#,Tensorflow,我目前正试图在C#中使用我的预训练的tensorflow模型(这是一个.pb文件格式的冻结初始模型) 这是一个图像识别项目,这是我的代码 using NumSharp; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using Tensorflow; using Tensorflow.Ker

我目前正试图在C#中使用我的预训练的tensorflow模型(这是一个.pb文件格式的冻结初始模型)

这是一个图像识别项目,这是我的代码

    using NumSharp;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Drawing;
    using System.IO;
    using Tensorflow;
    using Tensorflow.Keras.Utils;
    using static Tensorflow.Binding;
    using Console = Colorful.Console;
    
    
    namespace TensorFlowNET.Examples
    {
        /// <summary>
        /// Inception v3 is a widely-used image recognition model 
        /// that has been shown to attain greater than 78.1% accuracy on the ImageNet dataset. 
        /// The model is the culmination of many ideas developed by multiple researchers over the years.
        /// </summary>
        public class ImageRecognitionInception : SciSharpExample, IExample
        {
            string dir = "ImageRecognitionInception";
            string pbFile = "tensorflow_inception_graph.pb";
            string labelFile = "imagenet_comp_graph_label_strings.txt";
            List<NDArray> file_ndarrays = new List<NDArray>();
    
            public ExampleConfig InitConfig()
                => Config = new ExampleConfig
                {
                    Name = "Image Recognition Inception",
                    Enabled = true,
                    IsImportingGraph = false
                };
            
            public bool Run()
            
            {
                tf.compat.v1.disable_eager_execution();
    
                PrepareData();
    
                var graph = new Graph();
                //import GraphDef from pb file
                graph.Import(Path.Join(dir, pbFile));
    
                var input_name = "input";
                var output_name = "output";
    
                var input_operation = graph.OperationByName(input_name);
                var output_operation = graph.OperationByName(output_name);
    
                var labels = File.ReadAllLines(Path.Join(dir, labelFile));
                var result_labels = new List<string>();
                var sw = new Stopwatch();
    
                using (var sess = tf.Session(graph))
                {
                    foreach (var nd in file_ndarrays)
                    {
                        sw.Restart();
    
                        var results = sess.run(output_operation.outputs[0], (input_operation.outputs[0], nd));
                        results = np.squeeze(results);
                        int idx = np.argmax(results);
    
                         
                        Console.WriteLine($"{labels[idx]} {results[idx]} in {sw.ElapsedMilliseconds}ms", Color.Tan);
                        result_labels.Add(labels[idx]);
                        
                    }
                }
                return result_labels.Contains("Blues");
                
            }
    
            private NDArray ReadTensorFromImageFile(string file_name,
                                    int input_height = 288,
                                    int input_width = 432,
                                    int input_mean = 0,
                                    int input_std = 255)
            {
                var graph = tf.Graph().as_default();
    
                var file_reader = tf.io.read_file(file_name, "file_reader");
                var decodeJpeg = tf.image.decode_jpeg(file_reader, channels: 3, name: "DecodeJpeg");
                var cast = tf.cast(decodeJpeg, tf.float32);
                var dims_expander = tf.expand_dims(cast, 0);
                var resize = tf.constant(new int[] { input_height, input_width });
                var bilinear = tf.image.resize_bilinear(dims_expander, resize);
                var sub = tf.subtract(bilinear, new float[] { input_mean });
                var normalized = tf.divide(sub, new float[] { input_std });
    
                using (var sess = tf.Session(graph))
                    return sess.run(normalized);
            }
    
            public void PrepareData()
            {
                Directory.CreateDirectory(dir);
    
                // get model file
                string url = "https://drive.google.com/file/d/1FaUst3rrZ9JfdEGlsySwkE1d2KpEo9cm/view?usp=sharing";
    
                Web.Download(url, dir, "inception5h.zip");
    
                Compress.UnZip(Path.Join(dir, "inception5h.zip"), dir);
    
                // download sample picture
                Directory.CreateDirectory(Path.Join(dir, "img"));
                url = $"https://drive.google.com/file/d/1T-jNhZqVninEpMtco_sgpgHz10Mn1Qig/view?usp=sharing";
                Web.Download(url, Path.Join(dir, "img"), "jazz00090.png");
                
    
                url = $"https://drive.google.com/file/d/1iDKZR7orT0e103wxgaGarV_EDcjKHkb1/view?usp=sharing";
                Web.Download(url, Path.Join(dir, "img"), "blues00081.png");
    
                // load image file
                var files = Directory.GetFiles(Path.Join(dir, "img"));
                for (int i = 0; i < files.Length; i++)
                {
                    var nd = ReadTensorFromImageFile(files[i]);
                    file_ndarrays.Add(nd);
                }
            }
        }
    }
    
    
使用NumSharp;
使用System.Collections.Generic;
使用系统诊断;
使用系统图;
使用System.IO;
使用张量流;
使用Tensorflow.Keras.Utils;
使用静态张量流。绑定;
使用Console=colored.Console;
名称空间TensorFlowNET.Examples
{
/// 
///Inception v3是一种广泛使用的图像识别模型
///这已经证明在ImageNet数据集上达到了78.1%以上的准确率。
///该模型是多年来由多名研究人员提出的许多想法的结晶。
/// 
公共类ImageRecognitionOption:示例,IExample
{
string dir=“imagerecognitionoption”;
字符串pbFile=“tensorflow\u inception\u graph.pb”;
string labelFile=“imagenet\u comp\u graph\u label\u strings.txt”;
列表文件\u ndarrays=新列表();
public ExampleConfig InitConfig()
=>Config=newexampleconfig
{
Name=“图像识别开始”,
启用=真,
IsImportingGraph=false
};
公营学校
{
tf.compat.v1.disable_eager_execution();
PrepareData();
var-graph=新图();
//从pb文件导入GraphDef
导入(Path.Join(dir,pbFile));
变量输入\ u name=“输入”;
var output_name=“output”;
var input_operation=graph.OperationByName(输入_名称);
var output\u operation=graph.OperationByName(output\u name);
var labels=File.ReadAllLines(Path.Join(dir,labelFile));
var result_labels=新列表();
var sw=新秒表();
使用(var sess=tf.Session(图))
{
foreach(文件数组中的变量nd)
{
sw.Restart();
var results=sess.run(output_operation.outputs[0],(input_operation.outputs[0],nd));
结果=np.挤压(结果);
int idx=np.argmax(结果);
Console.WriteLine($“{labels[idx]}{results[idx]}在{sw.elapsedmillesons}ms中,{Color.Tan”);
结果_labels.Add(labels[idx]);
}
}
返回结果标签。包含(“蓝色”);
}
private NDArray ReadTensorFromImageFile(字符串文件名,
int input_height=288,
int input_WITH=432,
int输入_平均值=0,
int输入(标准=255)
{
var graph=tf.graph().as_default();
var file_reader=tf.io.read_file(文件名,“文件读取器”);
var decode jpeg=tf.image.decode_jpeg(文件读取器,通道:3,名称:“decode jpeg”);
var cast=tf.cast(decodeJpeg,tf.float32);
var dims_expander=tf.expand_dims(强制转换,0);
var resize=tf.constant(新int[]{input\u height,input\u width});
var bilinear=tf.image.resize\u双线性(dims\u扩展器,resize);
var sub=tf.subtract(双线性,新浮点[]{input_mean});
var normalized=tf.divide(sub,新浮点[]{input_std});
使用(var sess=tf.Session(图))
返回sess.run(标准化);
}
公共无效准备数据()
{
CreateDirectory(dir);
//获取模型文件
字符串url=”https://drive.google.com/file/d/1FaUst3rrZ9JfdEGlsySwkE1d2KpEo9cm/view?usp=sharing";
下载(url,dir,“inception5h.zip”);
Compress.UnZip(Path.Join(dir,“inception5h.zip”)、dir;
//下载示例图片
CreateDirectory(Path.Join(dir,“img”);
url=$”https://drive.google.com/file/d/1T-jNhZqVninEpMtco_sgpgHz10Mn1Qig/view?usp=sharing";
下载(url,Path.Join(dir,“img”),“jazz00090.png”);
url=$”https://drive.google.com/file/d/1iDKZR7orT0e103wxgaGarV_EDcjKHkb1/view?usp=sharing";
下载(url,Path.Join(dir,“img”),“blues00081.png”);
//加载图像文件
var files=Directory.GetFiles(Path.Join(dir,“img”);
for(int i=0;i
我正在使用Tensorflow.NET在C#中使用Tensorflow。这些是他们提供的示例代码。 所以我使用了我自己的模型和样本图像。(使用上述URL)

但问题来了

未处理的异常。Tensorflow.InvalidArgumentError:未知的图像文件格式。需要JPEG、PNG、GIF和BMP格式之一。 [{{node DecodeJpeg}}]

即使我使用了正确的示例图像文件格式,这种情况也会发生。我试过JPEG,PNG,JPG

(当我使用提供的示例图像和经过训练的模型时,它工作得很好)

它说我可以更改我的异常设置,所以我猜这可能是一个解决方案