OpenCV+Java 调用:Imgproc.findContours方法时报错:
Java FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL oth
代码:
//读取图片
Mat dst = src.clone();
Mat dstx = src.clone();
Mat dsty = src.clone();
//对图像进行高斯模糊去噪,梯度计算对噪声很敏感;
Imgproc.GaussianBlur(src, dst, new Size(5, 5), 1.0);
//调用Sobel函数计算图像在x,y方向梯度
Imgproc.Sobel(dst, dstx, -1, 1, 0, 3, 1, 0, Core.BORDER_DEFAULT);
Imgproc.Sobel(dst, dsty, -1, 0, 1, 3, 1, 0, Core.BORDER_DEFAULT);
Core.addWeighted(dstx, 0.5, dsty, 0.5, 0, dst);
// 调用convertScaleAbs函数将x,y梯度图像像素值限制在0-255;src – 原图 dst – 目标图 alpha – 乘数因子/beta – 偏移量
Core.convertScaleAbs(dstx,dstx, 1, 0);
Core.convertScaleAbs(dsty,dsty, 1, 0);
// 调用addWeight函数将x,y梯度图像融合
Mat mEdge=new Mat();
Core.addWeighted(dstx, 1, dsty, 1, 0, mEdge);
// 调用threshold函数对融合图像进行二值化;
Mat mThresh=new Mat();
Imgproc.threshold(mEdge, mThresh, 0, 255, Imgproc.THRESH_BINARY );
// 调用findContours方法查找脏污区域轮廓。
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
//Test.showImg(mThresh,"erzhi",3);
Imgproc.findContours(mThresh, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE, new Point(-1, -1));
解决方法:加载读取图片以后,加一句代码
Imgproc.cvtColor(src, src, Imgproc.COLOR_BGR2GRAY);
在图片的第一步将Mat转换为灰图即可
代码如下`
//读取图片
Mat dst = src.clone();
Mat dstx = src.clone();
Mat dsty = src.clone();
//1.彩色转灰色
Imgproc.cvtColor(src, src, Imgproc.COLOR_BGR2GRAY);
//对图像进行高斯模糊去噪,梯度计算对噪声很敏感;
Imgproc.GaussianBlur(src, dst, new Size(5, 5), 1.0);
到此,完美解决!!