使用C++和Ado从数据库获取图像数据为cv :: Mat格式
问题描述:
我正在使用ADO(C++)从MS-SQL数据库读取图像。图像以数据库中的varBinary(max)形式存储。我试图获取并将图像转换为cv::Mat
格式。使用C++和Ado从数据库获取图像数据为cv :: Mat格式
下面是代码我有,
HRESULT hr = ::CoInitialize(NULL);
ADODB::_ConnectionPtr pConnection;
hr = pConnection.CreateInstance(__uuidof(ADODB::Connection));
pConnection->CursorLocation = ADODB::adUseClient;
hr=pConnection->Open(L"Provider=sqloledb;Data Source=SAMPLE-DB;"
L"Initial Catalog=IMAGE;User Id=sr;Password=****;", L"",
L"", ADODB::adConnectUnspecified);
if (FAILED(hr))
{
//error handling...
}
ADODB::_RecordsetPtr recordset;
hr = recordset.CreateInstance(__uuidof(ADODB::Recordset));
std::string cmd = "SQL COMMAND THAT PROVIDE IMAGE BINARY";
recordset->Open(cmd.c_str(), pConnection.GetInterfacePtr(),
ADODB::adOpenForwardOnly, ADODB::adLockReadOnly, ADODB::adCmdText);
std::vector<uchar> buffer;
buffer = recordset->Fields->GetItem(L"ImgBinary")->GetValue(); //problem!!
cv::Mat testImage = cv::imdecode(buffer,cv::IMREAD_COLOR); //problem!!
cv::namedWindow("MyWindow");
cv::imshow("MyWindow",testImage);
错误我,
1) 'CV :: imdecode':没有2个重载可以转换所有的论据类型
2-)智能感知:没有从“_variant_t”到 “std :: vector>”的用户自定义转换存在
你能帮忙吗?我怎么能把图像作为cv::Mat
格式?
谢谢广告
答
问题解决了!问题是GetValue()
方法。我们需要使用GetChunk()
方法,因为我们从数据库中获取数组。 GetChunk()
必须有一个尺寸参数。我们可以得到尺寸,
long lngSize = recordset->Fields->GetItem(L"ImgBinary")->ActualSize;
代码行。
的代码的已编辑版本是在下面,
HRESULT hr = ::CoInitialize(NULL);
ADODB::_ConnectionPtr pConnection;
hr = pConnection.CreateInstance(__uuidof(ADODB::Connection));
pConnection->CursorLocation = ADODB::adUseClient;
hr=pConnection->Open(L"Provider=sqloledb;Data Source=SAMPLE-DB;"
L"Initial Catalog=IMAGE;User Id=sr;Password=****;", L"",
L"", ADODB::adConnectUnspecified);
if (FAILED(hr))
{
//error handling...
}
ADODB::_RecordsetPtr recordset;
hr = recordset.CreateInstance(__uuidof(ADODB::Recordset));
std::string cmd = "SQL COMMAND THAT PROVIDE IMAGE BINARY";
recordset->Open(cmd.c_str(), pConnection.GetInterfacePtr(),
ADODB::adOpenForwardOnly, ADODB::adLockReadOnly, ADODB::adCmdText);
/////////////// Edited Part ///////////////
long lngSize = recordset->Fields->GetItem(L"ImgBinary")->ActualSize;
_variant_t varChunk = recordset->Fields->GetItem(L"ImgBinary")->GetChunk(lngSize);
std::vector<uchar> buffer(lngSize);
SAFEARRAY* pData=NULL;
pData=V_ARRAY(&varChunk);
void *pVoid = 0;
hr = ::SafeArrayAccessData(pData, &pVoid);
uchar *pBinary = reinterpret_cast<uchar *>(pVoid);
for (int i = 0; i < pData->rgsabound[0].cElements; ++i)
{
buffer[i] = pBinary[i];
}
hr = ::SafeArrayUnaccessData(pData);
cv::Mat testImage = cv::imdecode(buffer,cv::IMREAD_COLOR);
cv::namedWindow("MyWindow");
cv::imshow("MyWindow",testImage);
cv::waitKey();