将 bin 值从 float 数组加载到 densehistogram

Load bin values to densehistogram from float array

我发现了一个类似的问题 emgu Calculate histogram with matrices ...但我缺少一些步骤!

Emgu 3/c#/Sql服务器 2014

我正在尝试将一张图片与存储在 SQL 服务器的 varbinary(max) 中的多张图片进行比较。

我的第一步是比较直方图,因为一些图像(对象)可能相似但颜色不同,所以在我的比较算法中我也想考虑要比较的对象的颜色。

我已经根据这里的其他帖子将一些代码放在一起,如果我根据图像计算直方图,我就能成功地做到这一点:

histBlueSource.Calculate(new Image<Gray, byte>[] { imgBlueSource }, true, null);
histBlueTarget.Calculate(new Image<Gray, byte>[] { imgBlueTarget }, true, null);

double cBlue = CvInvoke.CompareHist(histBlueSource, histBlueTarget, HistogramCompMethod.Correl);

由于从数据库加载图像的性能问题,我考虑从直方图中提取 BinValues 并将它们保存在 SQL SERVER 数据库中,稍后将它们上传回 DenseHistogram。

我成功提取了二进制值:

//** problem may be here - dont know if i should SAVE/LOAD bin value to a 1d FLOAT[256]
float[] BlueHist = new float[256];
BlueHist = histBlue.GetBinValues(); 

我序列化,保存到sql服务器。我可以从 sql 服务器读取,反序列化并使用我的 bin 值返回到 float[256],与提取的值完全相同。

要将数据加载回 Densehistogram,我正在这样做:

DenseHistogram histBlue = new DenseHistogram(256, new RangeF(0.0f, 255.0f));
BlueHist = (float[])bformatterBlue.Deserialize(memStreamBlue);
//**Other problem may be here
Matrix<float> mtx = new Matrix<float>(BlueHist);

我觉得矩阵数据是 {float[256,1]} 很奇怪。然后将 binvalues 中的值从 [0,0] 加载到 [255,0]。

当我做最后一步时

histBlue.Calculate(new Matrix<float>[] { mtx }, false, null);

问题是直方图二进制值加载不正确,只有 [0] 的值为 135,其他 [255] 为 0。

有人可以帮我提出这个或其他建议吗?

这对我有用....您不能序列化 DenseHistogram,但可以序列化 Mat。然后,您可以将后者的表示存储在 SQL Server Varbinary 字段中。

这是一些示例序列化代码。在此示例中,我使用的是灰度图像。

Image<Gray, Byte> croppedImage = sourceImage.Copy();

DenseHistogram hist1 = new DenseHistogram(256, new RangeF(0.0f, 255.0f));
hist1.Calculate<Byte>(new Image<Gray, byte>[] { croppedImage }, true, null);

Mat matFromHistogram = new Mat(hist1.Size, hist1.Depth, hist1.NumberOfChannels, hist1.DataPointer, hist1.Step);

byte[] histogramBytes;

using (MemoryStream stream = new MemoryStream())
{
    BinaryFormatter bformatter = new BinaryFormatter();
    bformatter.Serialize(stream, matFromHistogram);
    histogramBytes = stream.GetBuffer();
}

然后您可以从数据库反序列化并与 DenseHistogram 进行比较:

Mat matToCompare;

using (var memStream = new MemoryStream())
{
    byte[] bytes = face.Histogram;
    BinaryFormatter bformatter = new BinaryFormatter();
    memStream.Write(bytes, 0, bytes.Length);
    memStream.Seek(0, SeekOrigin.Begin);
    matToCompare = bformatter.Deserialize(memStream) as Mat;                                    
}

distance = CvInvoke.CompareHist(histSource, matToCompare, HistogramCompMethod.Bhattacharyya);