![](/img/trans.png)
[英]How to implement Canny Edge Detector in Java and android studio
[英]How to apply Canny edge detector effectively on image using Opencv in Android?
我正在制作一个Android应用程序以从图像中检测多个对象,然后处理这些对象并将它们与参考对象进行比较以检测异常。 我在python中测试了不同的图像边缘检测器,Prewitt运算符为我提供了最佳结果,如下所示:https://i.imgur.com/4iwOx9s.png对于android,我使用了Canny边缘检测器,但结果不如Prewitt如下所示https://i.imgur.com/Bax1Wxw.png应用Canny边缘检测器的目的是先检测最大轮廓,然后提取该轮廓并检测在该轮廓中找到的每个对象(在我的情况下为3个对象) 。
这是我尝试过的Java代码
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.coffret);
//compress bitmap
bmp = getResizedBitmap(bmp, 500);
Mat rgbMat = new Mat();
Utils.bitmapToMat(bmp, rgbMat);
Mat grayMat = new Mat();
Mat bwMat = new Mat();
Imgproc.cvtColor(rgbMat, grayMat, Imgproc.COLOR_RGB2GRAY);
Imgproc.equalizeHist(grayMat, grayMat);
//Imgproc.adaptiveThreshold(grayMat, grayMat, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 15, 40);
Imgproc.Canny(grayMat, bwMat, 50, 200, 3, false);
//find largest contour
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Imgproc.findContours(bwMat, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_NONE);
double maxArea = -1;
int maxAreaIdx = -1;
if (contours.size() > 0) {
MatOfPoint temp_contour = contours.get(0); //the largest is at the index 0 for starting point
MatOfPoint2f approxCurve = new MatOfPoint2f();
Mat largest_contour = contours.get(0);
List<MatOfPoint> largest_contours = new ArrayList<MatOfPoint>();
for (int idx = 0; idx < contours.size(); idx++) {
temp_contour = contours.get(idx);
double contourarea = Imgproc.contourArea(temp_contour);
//compare this contour to the previous largest contour found
if (contourarea > maxArea) {
//check if this contour is a square
MatOfPoint2f new_mat = new MatOfPoint2f( temp_contour.toArray() );
int contourSize = (int)temp_contour.total();
Imgproc.approxPolyDP(new_mat, approxCurve, contourSize*0.05, true);
if (approxCurve.total() == 4) {
maxArea = contourarea;
maxAreaIdx = idx;
largest_contours.add(temp_contour);
largest_contour = temp_contour;
}
}
}
if (largest_contours.size() >= 1) {
MatOfPoint temp_largest = largest_contours.get(largest_contours.size()-1);
largest_contours = new ArrayList<MatOfPoint>();
largest_contours.add(temp_largest);
Imgproc.cvtColor(bwMat, bwMat, Imgproc.COLOR_BayerBG2RGB);
Imgproc.drawContours(bwMat, largest_contours, -1, new Scalar(0, 255, 0), 1);
}
}
Utils.matToBitmap(bwMat, bmp);
Matrix matrix = new Matrix();
matrix.postRotate(180);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
imgView.setImageBitmap(bmp);
如您所见,使用Prewitt运算符可以使文本清晰,轮廓更清晰。 我认为我没有正确应用Canny,这就是为什么未检测到最大轮廓的原因。 我究竟做错了什么?
编辑:这是原始图像https://i.imgur.com/BtyZOvj.jpg
看来您正确应用了Canny边缘检测器。 但是,有时可能很难定义适当的最小值和最大值以限制边缘。
也许您使用的间隔(即50到200)对于您的目的而言很大。 您可以尝试以较小的时间间隔(例如175至200)来设置较高的最小值和最大值。
随着图像变得复杂,您需要特别注意这些参数。 有时,图像的不同部分将需要不同的最小和最大阈值。 看一下此参考,它包含有关Canny边缘检测改进的正当解释。 在此页的最后,对如何确定双阈值进行了说明 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.