【发布时间】:2016-08-16 21:11:08
【问题描述】:
我正在从我的 C# 代码动态加载 C++ 库。我想在大图像中找到小图像,将大图像转换为byte[] 并从物理路径读取小图像。
当我调用 imdecode 时,large_img 总是返回 0 cols 和 rows。
C#
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate ImageParams GetImageParams(IntPtr dataPtr, int size, string path);
// ...
byte[] largeImgByteArr = this.BitmapToByteArray(bmp);
IntPtr dataPtr = Marshal.AllocHGlobal(largeImgByteArr.Length);
Marshal.Copy(dataPtr, largeImgByteArr, 0, largeImgByteArr.Length);
C++
ImageParams GetImageParams(BYTE* largeImgBuf, int bufLength, const char* smallImgPath)
{
Mat large_img_data(bufLength, 1, CV_32FC1, largeImgBuf);
Mat large_img = imdecode(large_img_data, IMREAD_COLOR);
Mat small_img = imread(smallImgPath, IMREAD_COLOR);
int result_cols = large_img.cols - small_img.cols + 1;
int result_rows = large_img.rows - small_img.rows + 1;
Mat result;
result.create(result_cols, result_rows, CV_32FC1);
matchTemplate(large_img, small_img, result, CV_TM_SQDIFF_NORMED);
normalize(result, result, 0, 1, NORM_MINMAX, -1, Mat());
}
我在这里做错了什么?
注意:我检查了图像路径是否正确且字节数组不为空。
编辑 1
我通过提供大图像width 和height 稍微更改了我的代码,也摆脱了imdecode 并更改了this post 中的类似内容。
ImageParams GetImageParams(BYTE* largeImgBuf, int height, int width, int bufLength, const char* smallImgPath)
{
// Mat large_img = imdecode(large_img_data, IMREAD_COLOR);
Mat large_img = Mat(height, width, CV_8UC3, largeImgBuf);
Mat small_img = imread(templPath, 1);
/// ...
}
现在它返回行和列,但是当调用 matchTemplate 方法时会抛出异常:
【问题讨论】:
-
这里为什么需要
imdecode?largeImgBuf似乎已经包含正确的数据。CV_32FC1似乎也不对。请尝试类似Mat large_img(bufLength, 1, CV_8UC3, largeImgBuf); -
@Miki 感谢您的回复,尽管
CV_8UC3也是如此。我很快就会用更多信息更新我的问题。
标签: c# c++ bytearray opencv3.1