Java analisa código QR por meio de opencv (ferramenta de decodificação de código aberto WeChat)

        No passado, google.zxing era usado para analisar códigos QR em Java, mas a taxa de sucesso do zxing na análise de códigos QR era relativamente baixa e muitos códigos QR embelezados ou personalizados não podiam ser analisados.

        O WeChat abriu o código-fonte de sua função de decodificação de código QR e a contribuiu para a comunidade OpenCV. Seu projeto wechat_qrcode de código aberto está incluído no projeto OpenCV contrib. A partir do OpenCV versão 4.5.2, ele pode ser usado diretamente.

Importe os pacotes dependentes primeiro

<dependency>
   <groupId>org.bytedeco</groupId>
   <artifactId>javacpp</artifactId>
   <version>1.5.7</version>
   <classifier>windows-x86_64</classifier>
</dependency>
<dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>openblas</artifactId>
    <version>0.3.19-1.5.7</version>
    <classifier>windows-x86_64</classifier>
</dependency>
<dependency>
    <groupId>org.bytedeco</groupId>
    <artifactId>opencv</artifactId>
    <version>4.5.5-1.5.7</version>
</dependency>
<dependency>
     <groupId>org.bytedeco</groupId>
     <artifactId>opencv</artifactId>
      <version>4.5.5-1.5.7</version>
      <classifier>windows-x86_64</classifier>
</dependency>

As dependências acima são para sistemas Windows. Se você deseja publicar em sistemas liunx, altere windows-x86_64 para liunx-x86_64.

A seguir está o código de análise

package com.dyserver.bean;

import org.bytedeco.opencv.opencv_core.Mat;
import org.bytedeco.opencv.opencv_core.StringVector;
import org.bytedeco.opencv.opencv_wechat_qrcode.WeChatQRCode;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.imageio.ImageIO;

import static org.bytedeco.opencv.global.opencv_imgcodecs.imread;

/**
 * @author ChenYi
 */
public class WeChatDeCode {

	public static void main(String... args) {
		Mat img = imread("d:\\img" + "\\" + "1.png");
		System.out.println(deCode(img));
		
		//下载二维码到本地识别
		String url="";
		System.out.println(openPic(url));
	}

	public static String openPic(String url) {

		String savePath = "d:\\img";
		String filename = UUID.randomUUID().toString() + ".jpg";
		String re="0";
		try {
			dxz(url, savePath, filename);		
			Mat img = imread(savePath + "\\" + filename);
			re=deCode(img);
			//如果识别失败那么尝试放大缩小图片尝试识别,提高准确率
			if(re.equals("0")) {
				ys(savePath, filename);
				Mat img1 = imread(savePath + "\\1_" + filename);
				re=deCode(img1);
			}
			if(re.equals("0")) {
				fd(savePath, filename);
				Mat img2 = imread(savePath + "\\2_" + filename);
				re=deCode(img2);
			}
			return re;
			
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "0";
		}
	}

	private static void ys(String savePath, String filename) throws Exception {
		try {
			// 读取原始图片
			BufferedImage image = ImageIO.read(new FileInputStream(savePath + "\\" + filename));
			System.out.println("Width: " + image.getWidth());
			System.out.println("Height: " + image.getHeight());
			// 调整图片大小
			BufferedImage newImage = ImageUtils.resizeImage(image, image.getWidth()*2, image.getHeight()*2);
			// 图像缓冲区图片保存为图片文件(文件不存在会自动创建文件保存,文件存在会覆盖原文件保存)
			ImageIO.write(newImage, "jpg", new File(savePath + "\\1_" + filename));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void fd(String savePath, String filename) throws Exception {
		try {
			// 读取原始图片
			BufferedImage image = ImageIO.read(new FileInputStream(savePath + "\\" + filename));
			System.out.println("Width: " + image.getWidth());
			System.out.println("Height: " + image.getHeight());
			// 调整图片大小
			BufferedImage newImage = ImageUtils.resizeImage(image, 200, 200);
			// 图像缓冲区图片保存为图片文件(文件不存在会自动创建文件保存,文件存在会覆盖原文件保存)
			ImageIO.write(newImage, "jpg", new File(savePath + "\\2_" + filename));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void dxz(String urlString, String savePath, String filename) throws Exception {
		// 构造URL
		URL url = new URL(urlString);
		// 打开连接
		URLConnection con = url.openConnection();
		// 设置请求超时为20s
		con.setConnectTimeout(20 * 1000);
		// 文件路径不存在 则创建
		File sf = new File(savePath);
		if (!sf.exists()) {
			sf.mkdirs();
		}
		// jdk 1.7 新特性自动关闭
		try (InputStream in = con.getInputStream();
				OutputStream out = new FileOutputStream(sf.getPath() + "\\" + filename)) {
			// 创建缓冲区
			byte[] buff = new byte[1024];
			int n;
			// 开始读取
			while ((n = in.read(buff)) >= 0) {
				out.write(buff, 0, n);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String deCode(Mat img) {
		// 微信二维码对象,要返回二维码坐标前2个参数必传;后2个在二维码小或不清晰时必传。
		WeChatQRCode we = new WeChatQRCode();
		List<Mat> points = new ArrayList<Mat>();
		// 微信二维码引擎解码,返回的valList中存放的是解码后的数据,points中Mat存放的是二维码4个角的坐标
		StringVector stringVector = we.detectAndDecode(img);

		if (stringVector.empty()) {
			return "0";
		}

		System.out.println(stringVector.get(0).getString(StandardCharsets.UTF_8));
		return stringVector.get(0).getString(StandardCharsets.UTF_8);
	}

}

Acho que você gosta

Origin blog.csdn.net/terry711/article/details/133632188
Recomendado
Clasificación