当我使用tensorflowsharp将.jpeg图像解码为张量,然后将张量编码为Jpeg时,新的.jpeg图像将更改为黑色,这与原始图像不同。有什么问题吗?
我尝试了许多图片,并用不同的方式对这些图片进行解码和编码,但是问题始终存在。
将图像解码为张量的代码,如下所示:
private static void ConstructGraphToNormalizeImage(out TFGraph graph, out TFOutput input, out TFOutput output, TFDataType destinationDataType = TFDataType.Float)
{
int W = 288;
int H = 288;
float Scale = 1;
graph = new TFGraph();
input = graph.Placeholder(TFDataType.String);
output = graph.Cast(graph.Div(
x: graph.ResizeBilinear(
images: graph.ExpandDims(
input: graph.Cast(
graph.DecodeJpeg(contents: input, channels: 3), DstT: TFDataType.Float),
dim: graph.Const(0, "make_batch")),
size: graph.Const(new int[] { W, H }, "size")),
y: graph.Const(Scale, "scale")), destinationDataType);
}
public static TFTensor CreateTensor(TFTensor tensor, TFDataType destinationDataType = TFDataType.Float)
{
TFGraph graph;
TFOutput images, output;
ConstructGraphToNormalizeImage(out graph, out images, out output, destinationDataType);
using (var session = new TFSession(graph))
{
var normalized = session.Run(
inputs: new[] { images },
inputValues: new[] { tensor },
outputs: new[] { output });
return normalized[0];
}
}
将张量编码为图像的代码如下:
private byte[] TensorToJpeg(TFTensor image)
{
var graph = new TFGraph();
var input = graph.Placeholder(TFDataType.Float);
var output = graph.Squeeze(input, new long[] {0}, "Squeeze_dimens");
output = graph.Cast(output, TFDataType.UInt8);
output = graph.EncodeJpeg(output);
using (var session = new TFSession(graph))
{
var result = session.Run(
inputs: new[] { input },
inputValues: new[] { image },
outputs: new[] { output });
var tensor = result[0];
byte[] buffer = new byte[(int)tensor.TensorByteSize-10];
System.Runtime.InteropServices.Marshal.Copy(tensor.Data+10, buffer, 0, buffer.Length);
return buffer;
}
}
var contents = File.ReadAllBytes(ImagePath);
var tensor = TFTensor.CreateString(contents);
TFTensor tensorNormalized = CreateTensor(tensor);
byte[] NewImage_Bytes = TensorToJpeg(tensorNormalized);
File.WriteAllBytes(SendPathName+"Newimage.jpeg", NewImage_Bytes);
通常,如果我不对其进行标准化,则新图像应与原始图像相同。但即使图像已标准化,我认为新图像也不应该是黑色的。