[英]OpenCV Draw Contours in JAVA (Android)
我试图在 JAVA (Android) 中绘制图像的轮廓,但它似乎没有做任何事情(该功能没有绘制任何东西)这是代码:
public Mat contours(Mat mat)
{
ArrayList<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();
Mat balele = new Mat();
mat.convertTo(balele, CvType.CV_32SC1);
// find contours:
Imgproc.findContours(balele, contours, hierarchy, Imgproc.RETR_FLOODFILL, Imgproc.CHAIN_APPROX_SIMPLE);
Mat source = new Mat(balele.size(), balele.type());
for (int contourIdx = 0; contourIdx < contours.size(); contourIdx++)
{
Imgproc.drawContours(source, contours, contourIdx, new Scalar(0,0,255), -1);
}
return source;
}
当我们将 mat 图像传递给方法时,它已经是二进制格式。
你检测到任何错误吗?
更新:我更新了代码,它看起来像这样:
公共垫轮廓(垫垫){
ArrayList<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();
// find contours:
Imgproc.findContours(mat, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);
System.out.println(contours.size() + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
Mat source = new Mat();
for (int contourIdx = 0; contourIdx < contours.size(); contourIdx++)
{
Imgproc.drawContours(source, contours, contourIdx, new Scalar(0,0,255), -1);
}
return source;
}
我仍然没有得到所有的轮廓,我得到了一个浅白色。 有任何更正的想法吗?
Imgproc.findContours
内部更改输入Mat
,这会创建一个工件,如上所示,您可以将Mat
作为克隆对象传递,以便更改不会反映在输入Mat
。 我不确定是否有更好的解决方案,因为克隆Mat
肯定有一些时间和空间(不是太多)。 所以你可以使用:
Imgproc.findContours(mat.clone(), contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE);
我发现了问题。 这确实是 OpenCV 库中的一个错误。 下面的代码正是 OpenCV 在 java 中实现 drawContours() 的方式。 它始终使用包含 R、G、B 和 Alpha 的四个值标度。
public static void drawContours(Mat image, List<MatOfPoint> contours, int contourIdx, Scalar color, int thickness, int lineType, Mat hierarchy, int maxLevel, Point offset) {
List<Mat> contours_tmplm = new ArrayList<Mat>((contours != null) ? contours.size() : 0);
Mat contours_mat = Converters.vector_vector_Point_to_Mat(contours, contours_tmplm);
drawContours_0(image.nativeObj, contours_mat.nativeObj, contourIdx, color.val[0], color.val[1], color.val[2], color.val[3], thickness, lineType, hierarchy.nativeObj, maxLevel, offset.x, offset.y);
}
现在,让我们考虑一下 alpha 的默认值是多少。 零,对吧? 这就是为什么你总是用黑色画画。 解决方案是使用四个值标量,例如 new Scalar(0, 0, 255, 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.