1.多二維碼識別 (同一張圖片中多二維碼識別)
直接上代碼舒服:
pom文件:
1 <!-- QR Code --> 2 <dependency> 3 <groupId>com.google.zxing</groupId> 4 <artifactId>core</artifactId> 5 <version>3.3.3</version> 6 </dependency>、
1 /** 2 * Parse multiple qr codes(解析多個二維碼) 3 * 使用java實現 4 * 5 * @param bufferedImage image 6 * @return QRCode analysis results 7 */ 8 @Override 9 public Result[] analysisQRCodeOfMore(BufferedImage bufferedImage) { 10 QRCodeMultiReader qrCodeMultiReader = new QRCodeMultiReader(); 11 Result[] results = null; 12 try { 13 BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage))); 14 Map hints = new Hashtable(); 15 hints.put(EncodeHintType.CHARACTER_SET, SystemConstants.SYS_ENC); 16 hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); //優化精度 17 hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE); //復雜模式,開啟PURE_BARCODE模式; 帶圖片LOGO的解碼方案 18 hints.put(DecodeHintType.POSSIBLE_FORMATS,BarcodeFormat.QR_CODE);//指定識別的二維碼格式 19 results = qrCodeMultiReader.decodeMultiple(binaryBitmap, hints); 20 } catch (NotFoundException e) { 21 //e.printStackTrace(); 22 System.err.println("二維碼識別中..."); 23 } 24 return results; 25 }
注意:開啟精度優化與復雜模式會消耗識別時間!
在多二維碼識別中,應該說是zxing的一個小bug,在識別過程中對於模糊一點的圖片,會一直拋異常 (二維碼識別中...) 直至二維碼識別不出來,或者二維碼識別出來;此問題沒來得及細細研究,等日后補充;
2.單二維碼識別:
1 private String decodeQRCode(Mat src) { 2 if (src == null) { 3 return null; 4 } 5 BufferedImage image; 6 try { 7 image = ImageUtils.mat2BufferedImage(src, ".jpg"); 8 LuminanceSource source = new BufferedImageLuminanceSource(image); 9 Binarizer binarizer = new HybridBinarizer(source); 10 BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); 11 Map<DecodeHintType, Object> hints = new HashMap<>(); 12 hints.put(DecodeHintType.CHARACTER_SET, SystemConstants.SYS_ENC); 13 hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); 14 Result resultText = new MultiFormatReader().decode(binaryBitmap, hints); 15 return resultText.getText(); 16 } catch (NotFoundException e) { 17 LogUtils.info("[QRCodeServiceImpl] decodeQRCode image transform failed."); 18 } 19 return null; 20 }
以上代碼使用opencv格式的圖片來轉換為BufferedImage為需要的入參;
3. (擴展) 多二維碼識別與多二維碼識別不同點:
1 public Result[] decodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints)
單二維碼識別函數:
1 public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints)
完畢!