前面的文章提到,要实现两个功能
前面的文章已经已经实现了数字的识别,但是发现识别率比较低,并且识别的错误率也比较高。考虑是因为背景比较复杂影响了识别效果,本文主要解决复杂背景的简化,以及图片的对比
我使用了最新的4.6.0 的版本
2. 解压下载的zip得到demo和需要集成的module
3. 接入自己的项目 3.1、将2中得到的sdk作为一个独立module放到项目中
3.2、在项目的setting.gradle中引入sdk module
3.3、 在使用opencv的module中引入sdk module
至此集成算是完成了,但是因为这个使用了ndk相关的功能,如果本地没有ndk环境的话,可能需要处理下环境问题,这里不再赘述
public static Bitmap createBitmap(Bitmap bitmap) { Mat src = new Mat(); Utils.bitmapToMat(bitmap, src); //将bitmap转换为Mat Mat thresholdImage = new Mat(src.size(), src.type()); //这个二值图像用于找出关键信息的图像 //将图像转换为灰度图像 Imgproc.cvtColor(src, thresholdImage, Imgproc.COLOR_RGBA2GRAY); //将图像转换为边缘二值图像 Imgproc.threshold(thresholdImage,thresholdImage,10.0,255.0, Imgproc.THRESH_BINARY_INV|Imgproc.THRESH_OTSU); Bitmap binaryBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig()); Utils.matToBitmap(thresholdImage, binaryBitmap); return binaryBitmap; }
` 将图像转为二值图像。 这个方法非常的重要,在这里专门说一下
3. 效果展示
public static Double similarity(Bitmap bitmap1, Bitmap bitmap2){ // 计算每张图片的特征点 MatOfKeyPoint descriptors1 = computeDescriptors(bitmap1); MatOfKeyPoint descriptors2 = computeDescriptors(bitmap2); // 比较两张图片的特征点 DescriptorMatcher descriptorMatcher = DescriptorMatcher.create(DescriptorMatcher.FLANNBASED); List matches =new ArrayList(); // 计算大图中包含多少小图的特征点。 // 如果计算小图中包含多少大图的特征点,结果会不准确。 // 比如:若小图中的 50 个点都包含在大图中的 100 个特征点中,则计算出的相似度为 100%,显然不符合我们的预期 if (bitmap1.getByteCount() > bitmap2.getByteCount() ) { descriptorMatcher.knnMatch(descriptors1, descriptors2, matches, 2); } else { descriptorMatcher.knnMatch(descriptors2, descriptors1, matches, 2); } Log.i("~~~", "matches.size: ${matches.size}"); if (matches.isEmpty()) return 0.00; // 获取匹配的特征点数量 int matchCount = 0; // 邻近距离阀值,这里设置为 0.7,该值可自行调整 float nndrRatio = 0.7f; for (MatOfDMatch match:matches) { DMatch[] array = match.toArray(); // 用邻近距离比值法(NNDR)计算匹配点数 if (array[0].distance <= array[1].distance * nndrRatio) { matchCount++; } } Log.i("~~~", "matchCount: $matchCount"); return Double.valueOf(matchCount/ matches.size()); }
private static MatOfKeyPoint computeDescriptors(Bitmap bitmap){ Mat mat = new Mat(); Utils.bitmapToMat(bitmap, mat); MatOfKeyPoint keyPoints = new MatOfKeyPoint(); siftDetector.detect(mat, keyPoints); MatOfKeyPoint descriptors = new MatOfKeyPoint(); // 计算图片的特征点 siftDetector.compute(mat, keyPoints, descriptors); return descriptors; }
opencv提供了一整套非常完善的api,可以解决我们遇到的绝大部分场景,大家可以多看文档,学习起来。
留言与评论(共有 0 条评论) “” |