如何解决 OpenCv 绘制轮廓错误
Posted
技术标签:
【中文标题】如何解决 OpenCv 绘制轮廓错误【英文标题】:How to solve the OpenCv's drawing contour error 【发布时间】:2013-09-15 15:26:02 【问题描述】:基本上,我正在尝试用颜色绘制第一个轮廓。但是这个程序崩溃并出现以下错误:
9-11 09:56:38.230: D/dalvikvm(1920): GC_FOR_ALLOC 释放 71K,10% 释放 2824K/3124K,暂停 0ms,总共 3ms
09-11 09:56:38.340: D/dalvikvm(1920): GC_FOR_ALLOC 释放 379K,17% 释放 2958K/3564K,暂停 3ms,总共 4ms
09-11 09:56:38.360: D/dalvikvm(1920): GC_FOR_ALLOC 释放 107K,10% 释放 3361K/3696K,暂停 2ms,总共 3ms
09-11 09:56:38.390: D/dalvikvm(1920): GC_FOR_ALLOC 释放 170K,10% 释放 3702K/4100K,暂停 4ms,总共 4ms
09-11 09:56:38.420: E/cv::error()(1920): OpenCV 错误: cv::Mat cv::cvarrToMat(const CvArr *, bool, bool, int),文件 /home/reports/ci/slave_desktop/50-SDK/opencv/modules/core/src/matrix.cpp,第 698 行
09-11 09:56:38.430:A/libc(1920):致命信号 11 (SIGSEGV) 位于 0x00000000 (code=1),线程 1920 (pencvratstudy01)
程序是
@Override
protected void onCreate(Bundle savedInstanceState)
Log.i(TAG, "called onCreate");
super.onCreate( savedInstanceState );
if (!OpenCVLoader.initDebug())
// Handle initialization error
setContentView(R.layout.activity_main);
// load an image from Resource directory
Mat mMat = new Mat();
try
mMat = Utils.loadResource(this, R.drawable.baby,
Highgui.CV_LOAD_IMAGE_COLOR);
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
// Create result object with correct color
Mat result = new Mat();
Imgproc.cvtColor(mMat, result, Imgproc.COLOR_RGB2BGRA);
// create tmpMat object for gray image and blur it
Mat tmpMat = new Mat();
Imgproc.cvtColor(result,tmpMat , Imgproc.COLOR_BGR2GRAY);
Imgproc.blur(tmpMat, tmpMat, new Size(3,3));
/* find cany of tmpMat */
Mat canny = new Mat();
Imgproc.Canny( tmpMat, canny , 2 , 4);
// find contours
Mat hierarchy = new Mat();
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Imgproc.findContours(canny, contours, hierarchy, Imgproc.RETR_EXTERNAL,
Imgproc.CHAIN_APPROX_SIMPLE);
// draw contour on mask object
Mat mask = new Mat();
Imgproc.drawContours(mask, contours, 0 , new Scalar(255));
// create bitmap and draw on imageView
Bitmap bmp;
bmp = Bitmap.createBitmap(mask.cols(), mask.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mask, bmp);
ImageView imgView = (ImageView) findViewById(R.id.sampleImageView);
imgView.setImageBitmap(bmp);
这里有什么问题?
【问题讨论】:
【参考方案1】:问题是你给drawContours方法提供了错误类型的垫子,你可以使用
Mat mask = Mat.zeros(result.rows(),result.cols(),result.type());
另一个建议是在 onCreate 之前使用静态块加载 opencv:
static
if (!OpenCVLoader.initDebug())
// Handle initialization error
【讨论】:
以上是关于如何解决 OpenCv 绘制轮廓错误的主要内容,如果未能解决你的问题,请参考以下文章