JavaCVOpenCV 二维码扫描功能

    科技2024-05-12  86

    JavaCV/OpenCV 二维码扫描功能 怎样配置工程就不再赘述,不清楚的读者可以网上查找资料,二维码扫描功能通过JavaCV实现起来还是挺简单的,主要OpenCV中QRCodeDetector提供强大的API,识别速度个人感觉以微信(经常扫不到)来作对比还是快许多。

    //本地安装的摄像头驱动可能有多个,选择合适的 VideoInputFrameGrabber grabber = VideoInputFrameGrabber.createDefault(1); grabber.start(); QRCodeDetector qrCodeDetector = new QRCodeDetector(); OpenCVFrameConverter.ToMat frameConverter = new OpenCVFrameConverter.ToMat(); String windowTitle = "QR SCAN"; Frame frame = null; int count = 0; while ((frame = grabber.grabFrame()) != null) { Mat img = frameConverter.convertToMat(frame);//如果需要扩展可以在图像前面添加扫描框 int imageWidth = img.size().width(); int imageHeight = img.size().height(); int hStartPosition = Float.valueOf(imageHeight * 0.2f).intValue(); int maxPostion = Float.valueOf(imageHeight * 0.8f).intValue(); int lineHeight = hStartPosition + Float.valueOf(count++ * 0.05f * imageHeight).intValue(); if (lineHeight > maxPostion) { lineHeight = hStartPosition; count = 0; } Point pt1 = new Point(Float.valueOf(imageWidth * 0.2f).intValue(), lineHeight); Point pt2 = new Point(Float.valueOf(imageWidth * 0.8f).intValue(), lineHeight); opencv_imgproc.line(img, pt1, pt2, Scalar.WHITE, 5, opencv_imgproc.LINE_8, 0); opencv_highgui.imshow(windowTitle, img); StringVector decoded_info = new StringVector(); boolean success = qrCodeDetector.detectAndDecodeMulti(img, decoded_info); if (success) { BytePointer bytePointer = decoded_info.get(0); this.output("结果:" + bytePointer.getString()); break; } int cvWaitKey = opencv_highgui.cvWaitKey(50); if (cvWaitKey == 27) { break; } } grabber.close(); qrCodeDetector.close();
    Processed: 0.013, SQL: 8