2
我有一個256字節的二進制Mat(1x256)(CV_8UC1)。我需要創建另一個具有1x64尺寸浮標的Mat(CV_32F)。這意味着每個4個字節在結果矩陣中構造一個浮點值。OpenCV創建從二進制浮點數墊
有沒有辦法在OpenCV中做到這一點?或者任何其他的C++方式?
我有一個256字節的二進制Mat(1x256)(CV_8UC1)。我需要創建另一個具有1x64尺寸浮標的Mat(CV_32F)。這意味着每個4個字節在結果矩陣中構造一個浮點值。OpenCV創建從二進制浮點數墊
有沒有辦法在OpenCV中做到這一點?或者任何其他的C++方式?
#include "opencv2/opencv.hpp"
using namespace cv;
#include <assert.h>
int main()
{
Mat floatOrig = Mat::zeros(1,64,CV_32FC1);
Mat ucharConverted = Mat::zeros(1,256,CV_8UC1);
Mat floatConverted = Mat::zeros(1,64,CV_32FC1);
//construct some data
RNG rng = theRNG();
for(int i=0;i<floatOrig.cols;++i)
{
floatOrig.at<float>(0,i)=rng.gaussian(1.);
}
//save them into uchar first
for(int i=0;i<ucharConverted.cols;++i)
{
ucharConverted.at<uchar>(0,i)= floatOrig.at<uchar>(0,i);
}
//now convert them back into float
//uchar b[4] = {0}; uncomment for big endian data
for(int i=0;i<floatConverted.cols;++i)
{
/* uncomment for big endian ordering
b[0]=ucharConverted.at<uchar>(0,i*4+3);
b[1]=ucharConverted.at<uchar>(0,i*4+2);
b[2]=ucharConverted.at<uchar>(0,i*4+1);
b[3]=ucharConverted.at<uchar>(0,i*4+0);
memcpy(&floatConverted.at<float>(0,i),&b, sizeof(float));
*/
memcpy(&floatConverted.at<float>(0,i),&ucharConverted.at<uchar>(0,i*4), sizeof(float));
}
//verify
for(int i=0;i<floatConverted.cols;++i)
{
assert(floatConverted.at<float>(0,i)-floatOrig.at<float>(0,i)==0.);
}
// now lets try saving that to file
FILE* fp = fopen("c:/data/float64.bin","wb");
for(size_t i=0;i<floatConverted.cols;++i)
{
fwrite(&floatConverted.at<float>(0,i),sizeof(float),1,fp);
}
fclose(fp);
floatConverted=0;//we gonna try to load it back
fp = fopen("c:/data/float64.bin","rb");
for(size_t i=0;i<floatConverted.cols;++i)
{
fread( &floatConverted.at<float>(0,i),sizeof(float),1,fp);
}
fclose(fp);
//verify data read from file
for(int i=0;i<floatConverted.cols;++i)
{
assert(floatConverted.at<float>(0,i)-floatOrig.at<float>(0,i)==0.);
}
getchar();
}
你能否澄清如何從字節構造浮點數?連續四個字節連接並重新解釋爲浮點數? – Aurelius
@奧勒留,是的。四個連續的字節=一個浮點數。 –
你爲什麼要這樣做?從我的研究來看,這可能會在某處觸發未定義的行爲。 – Aurelius