OpenCV C++ imgdecode 在 OSX 上生成异常
OpenCV C++ imgdecode generating an exception on OSX
我有一个应用程序可以从相机拍摄照片、对其进行编码、执行一些操作然后对其进行解码。它适用于 Ubuntu,但在 OSX imgdecode
上生成以下异常:
libc++abi.dylib: terminating with uncaught exception of type cv::Exception: OpenCV(4.2.0) /tmp/opencv-20200404-3398-7w1b75/opencv-4.2.0/modules/imgcodecs/src/loadsave.cpp:732: error: (-215:Assertion failed) buf.checkVector(1, CV_8U) > 0 in function 'imdecode_'
Abort trap: 6
我尝试在同一个脚本中对图像进行编码和解码,以获得最小的可验证示例。脚本如下:
#include "opencv2/opencv.hpp"
#include<unistd.h>
using namespace std;
using namespace cv;
int main(int argc, char *argv[])
{
Mat frame;
VideoCapture cam(0);
std::vector<uchar> buf_in;
u_char *buf ;
while(1)
{
cam>>frame;
imencode(".png",frame, buf_in);
//encode image and put data into the vector buf
frame = cv::imdecode(cv::Mat(3, buf_in.size(), CV_8UC3, buf_in.data()), 1);
imshow("window", frame);
waitKey(2);
}
return 0;
}
并且它仍在 OSX 上生成异常。这是为什么?为什么会产生异常?为什么只在 OSX 上?
POST 剧本
如果需要编译代码,可以使用下面的Makefile:
CXX = g++
CXXFLAGS = -std=c++11 -pg
INC_PATH = `pkg-config --cflags opencv4`
LIBS = `pkg-config --libs opencv4`
SOURCEDIR := ./
SOURCES := $(wildcard $(SOURCEDIR)/*.cpp)
OBJDIR=$(SOURCEDIR)/obj
OBJECTS := $(patsubst $(SOURCEDIR)/%.cpp,$(OBJDIR)/%.o, $(SOURCES))
DEPENDS := $(patsubst $(SOURCEDIR)/%.cpp,$(OBJDIR)/%.d,$(SOURCES))
WARNING := -Wall -Wextra
.PHONY: all clean
all: openCV
clean:
$(RM) $(OBJECTS) $(DEPENDS) openCV
openCV: $(OBJECTS)
$(CXX) $(WARNING) $(CXXFLAGS) $(INC_PATH) $^ -o $@ $(LIBS)
-include $(DEPENDS)
$(OBJDIR):
mkdir -p $(OBJDIR)
$(OBJDIR)/%.o: $(SOURCEDIR)/%.cpp Makefile | $(OBJDIR)
$(CXX) $(WARNING) $(CXXFLAGS) $(INC_PATH) -MMD -MP -c $< -o $@
我解决了将 imdecode
的参数更改为包含原始数据的 vector<u_char>
,而不是初始化新的 Mat
结构。
#include "opencv2/opencv.hpp"
#include<unistd.h>
using namespace std;
using namespace cv;
int main(int argc, char *argv[])
{
Mat frame;
VideoCapture cam(0);
std::vector<uchar> buf_in;
u_char *buf ;
while(1)
{
cam>>frame;
imencode(".png",frame, buf_in);
//encode image and put data into the vector buf
buf_out.assign(buf_in.data, buf_in.data+buf_in.size());
frame = cv::imdecode(buf_out, 1);
imshow("window", frame);
waitKey(2);
}
return 0;
}