从代码上看Image.size只是读取数据是buffer区的大小。你将读取的数据存储到pbuf中,这里应该是存储整个图像的数据,而你给pbuf分配的大小仅为一个buffer的大小,而非height x width x chanel的大小。height x width x chanel应该是远大于你目前分配的pbuf的空间大小,当你进行遍历赋值时根据 height x width计算pbuf的下标,当下标大于Image.size时则报错了,建议规范编码的命名。
jpg是经过压缩编码的图像格式,读出来的数据需要经过解码才能恢复图像原始数据,而后才能把原始数据转换为mat格式
/** @brief Reads an image from a buffer in memory.
The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or
contains invalid data, the function returns an empty matrix ( Mat::data==NULL ).
See cv::imread for the list of supported formats and flags description.
@note In the case of color images, the decoded images will have the channels stored in **B G R** order.
@param buf Input array or vector of bytes.
@param flags The same flags as in cv::imread, see cv::ImreadModes.
*/
CV_EXPORTS_W Mat imdecode( InputArray buf, int flags );
/** @overload
@param buf
@param flags
@param dst The optional output placeholder for the decoded matrix. It can save the image
reallocations when the function is called repeatedly for images of the same size.
*/
CV_EXPORTS Mat imdecode( InputArray buf, int flags, Mat* dst);
你这是啥?读取中文路径图片?不然直接使用imread()读取啊。你这个报错的意思就是长X宽和你的imag.size()的大小不一致,1280X1072>>99051,相当于你的图片指针长度不勾,图片丢失了当然不行了。如果你的图片指针够的话,可以直接使用 Mat img=Mat(Size(w,h),CV_8UC3,image.pbuf),前提是你的image.pbuf得长度要比w*h大才行,这样可以丢掉后面的数据(只能保证不报错,不能保证你的数据丢掉之后图片是否正常)
你可以试试这个。之前测试读中文路径和特殊字符图片的时候写的,可以根据图片本身的大小调整,而不像你这么直接写死图片的大小。另外,都使用opencv了,我的建议是直接用cpp的读取方式。
string img_path_name="中文路径图片.jpg";
ifstream pFile(img_path_name, ios::binary);
pFile.seekg(0, pFile.end); //文件指针移到文件尾
long long LSize = pFile.tellg(); //获取文件长度
pFile.seekg(0, pFile.beg); //移动回到文件头
vector<uchar> pData(LSize);
char * buffer = (char*)malloc(sizeof(char)*LSize);
pFile.read(buffer, LSize); //将文件读取到buffer
pFile.close(); //关闭
memcpy(&pData[0], buffer, sizeof(char)*LSize); //复制
free(buffer);
buffer = nullptr;
Mat img = imdecode(pData, IMREAD_COLOR); //解码
可以参考一下代码修改
uchar c[100][100];
for(int i=0; i<100; i++)
for(int j=0; j<100; j++)
c[i][j] = (i<j)?0:255;
imshow("x", Mat(100, 100, CV_8UC1, (void *)c));
waitKey();
其实opencv提供了相关的库可以直接实现将uchar类型转换为opencv的Mat类型。
cv::Mat TempImage = cv::Mat(imageHeight,imageWidth, CV_8UC4, uchar变量);
cv::cvtColor(TempImage, GrapImg, cv::COLOR_BGRA2BGR);(如果是4通道的还需要转换为三通道)
其中CV_8UC4这个不同相机可能通道数不一样,需要根据相机返回数据的具体类型更改(我用的索尼的工业相机目前以上是OK的)。 建议去opencv官网查看一下该API参数的说明。