java实现二维码识别(ZBar)

要求:系统Centos7.x

第一步安装Cmake

yum install -y gcc gcc-c++ wget
wget https://cmake.org/files/v3.14/cmake-3.14.0.tar.gz
tar -zxvf cmake-3.14.0.tar.gz
cd cmake-3.14.0
./bootstrap
gmake
gmake install

rm -rf /usr/bin/cmake
ln -s /usr/local/bin/cmake /usr/bin/cmake

第二步编译libz

tar -xvf zlib-1.2.11.tar.gz
cd zlib-1.2.11
mkdir build
cd build
touch build.sh

build.sh

cmake -G "Unix Makefiles" \
-D CMAKE_BUILD_TYPE=Release \
-D CMAKE_INSTALL_PREFIX=/var/SDK/install/zlib \
-D CMAKE_C_FLAGS="-fPIC" \
-D CMAKE_CXX_FLAGS="-fPIC" ..
chmod -R 777 build.sh
./build.sh
make
make install

第三步编译libpng

tar -xvf libpng-1.5.30.tar.xz
cd libpng-1.5.30
touch build.sh

 build.sh

export CFLAGS="-I/var/SDK/install/zlib/include -fPIC"
export CPPFLAGS="-I/var/SDK/install/zlib/include -fPIC"
export LDFLAGS="-L/var/SDK/install/zlib/lib"
./configure --prefix=/var/SDK/install/libpng
chmod -R 777 build.sh
./build.sh
make
make install

第四步编译opencv

unzip opencv-4.1.0.zip
cd opencv-4.1.0
mkdir build
cd build
touch build.sh

build.sh

cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/var/SDK/install/opencv \
-D BUILD_SHARED_LIBS=OFF \
-D WITH_FFMPEG=ON \
-D ENABLE_CXX11=1 ..
chmod -R 777 build.sh
./build.sh
make
make install

第四步编译zbar

tar -xvf zbar-0.10.tar.bz2
cd zbar-0.10
touch build.sh

build.sh


export CFLAGS="-I/var/SDK/install/zlib/include -fPIC"
export CPPFLAGS="-I/var/SDK/install/zlib/include -fPIC"
export LDFLAGS="-L/var/SDK/install/zlib/lib"
./configure --without-imagemagick --disable-video --without-gtk --without-qt --with-x --prefix=/var/SDK/install/zbar --without-python --without-jpeg --disable-shared --enable-static
make 
make install

 

chmod -R 777 build.sh
./build.sh
make
make install

第五步编译c++的二维码识别程序

mkdir /var/SDK/project/zbar
cd /var/SDK/project/zbar
touch CMakeLists.txt
touch opencv_core.h
touch opencv_core.cpp
touch zbar_core.h
touch zbar_core.cpp
touch test.cpp

CMakeLists.txt

cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_CXX_STANDARD 11)
 
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
 
add_library(libittnotify STATIC IMPORTED)
set_target_properties(libittnotify PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/opencv4/3rdparty/libittnotify.a)
 
add_library(libquirc STATIC IMPORTED)
set_target_properties(libquirc PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/opencv4/3rdparty/libquirc.a)
 
add_library(liblibprotobuf STATIC IMPORTED)
set_target_properties(liblibprotobuf PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/opencv4/3rdparty/liblibprotobuf.a)
 
add_library(libIlmImf STATIC IMPORTED)
set_target_properties(libIlmImf PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/opencv4/3rdparty/libIlmImf.a)
 
add_library(liblibjasper STATIC IMPORTED)
set_target_properties(liblibjasper PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/opencv4/3rdparty/liblibjasper.a)
 
add_library(liblibwebp STATIC IMPORTED)
set_target_properties(liblibwebp PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/opencv4/3rdparty/liblibwebp.a)
 
add_library(liblibtiff STATIC IMPORTED)
set_target_properties(liblibtiff PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/opencv4/3rdparty/liblibtiff.a)
 
add_library(liblibjpeg-turbo STATIC IMPORTED)
set_target_properties(liblibjpeg-turbo PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/opencv4/3rdparty/liblibjpeg-turbo.a)
 
add_library(libopencv_video STATIC IMPORTED)
set_target_properties(libopencv_video PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/libopencv_video.a)
 
add_library(libopencv_stitching STATIC IMPORTED)
set_target_properties(libopencv_stitching PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/libopencv_stitching.a)
 
add_library(libopencv_objdetect STATIC IMPORTED)
set_target_properties(libopencv_objdetect PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/libopencv_objdetect.a)
 
add_library(libopencv_calib3d STATIC IMPORTED)
set_target_properties(libopencv_calib3d PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/libopencv_calib3d.a)
 
add_library(libopencv_features2d STATIC IMPORTED)
set_target_properties(libopencv_features2d PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/libopencv_features2d.a)
 
add_library(libopencv_dnn STATIC IMPORTED)
set_target_properties(libopencv_dnn PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/libopencv_dnn.a)
 
add_library(libopencv_photo STATIC IMPORTED)
set_target_properties(libopencv_photo PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/libopencv_photo.a)
 
add_library(libopencv_ml STATIC IMPORTED)
set_target_properties(libopencv_ml PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/libopencv_ml.a)
 
add_library(libopencv_flann STATIC IMPORTED)
set_target_properties(libopencv_flann PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/libopencv_flann.a)
 
add_library(libopencv_highgui STATIC IMPORTED)
set_target_properties(libopencv_highgui PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/libopencv_highgui.a)
 
add_library(libopencv_videoio STATIC IMPORTED)
set_target_properties(libopencv_videoio PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/libopencv_videoio.a)
 
add_library(libopencv_imgcodecs STATIC IMPORTED)
set_target_properties(libopencv_imgcodecs PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/libopencv_imgcodecs.a)
 
add_library(libopencv_imgproc STATIC IMPORTED)
set_target_properties(libopencv_imgproc PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/libopencv_imgproc.a)
 
add_library(libopencv_core STATIC IMPORTED)
set_target_properties(libopencv_core PROPERTIES IMPORTED_LOCATION /var/SDK/install/opencv/lib64/libopencv_core.a)
 
add_library(libzbar STATIC IMPORTED)
set_target_properties(libzbar PROPERTIES IMPORTED_LOCATION /var/SDK/install/zbar/lib/libzbar.a)
 
add_library(libz STATIC IMPORTED)
set_target_properties(libz PROPERTIES IMPORTED_LOCATION /var/SDK/install/zlib/lib/libz.a)
 
add_library(libpng15 STATIC IMPORTED)
set_target_properties(libpng15 PROPERTIES IMPORTED_LOCATION /var/SDK/install/libpng/lib/libpng15.a)
 
message("include 头文件目录")
include_directories(/var/SDK/install/opencv/include/opencv4)
include_directories(/var/SDK/install/zbar/include)
include_directories(/var/java/jdk1.8.0_221/include)
include_directories(/var/java/jdk1.8.0_221/include/linux)
include_directories(${SRC_ROOT_PATH}/)
 
message("设置源码根路径,即 cpp 目录")
set(SRC_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
message(${SRC_ROOT_PATH})
 
message("定义要编译的文件列表变量")
 file(GLOB CPP_FILES_IN_UTILS "${SRC_ROOT_PATH}/*.cpp")
 
message("设置要编译的源文件")
set(SOURCE_FILES ${CPP_FILES_IN_UTILS})
 
add_library(qrcode2 SHARED ${SOURCE_FILES})
 
target_link_libraries(
qrcode2
libzbar
libopencv_video
libopencv_stitching
libopencv_objdetect
libopencv_calib3d
libopencv_features2d
libopencv_dnn
libopencv_photo
libopencv_ml
libopencv_flann
libopencv_highgui
libopencv_videoio
libopencv_imgcodecs
libopencv_imgproc
libopencv_core
libittnotify
libquirc
liblibprotobuf
libIlmImf
liblibjasper
liblibwebp
liblibtiff
liblibjpeg-turbo
libpng15
libz
)

 zbar_core.h

#pragma once
char * decodeByZbar(const char* fromPath);

zbar_core.cpp

#ifndef zxing_parse_h
#define zxing_parse_h
#include "zbar.h"      
#include 
#include "zbar_core.h"
#include "opencv2/opencv.hpp"
#endif
using namespace std;
using namespace zbar;  //添加zbar名称空间    
using namespace cv;
char * decodeByZbar(const char* fromPath) {
	ImageScanner scanner;
	scanner.set_config(ZBAR_NONE, ZBAR_CFG_ENABLE, 1);
	cv::Mat image = cv::imread(fromPath, 1);
	if (!image.data) {
		return nullptr;
	}
	Mat imageGray;
	cvtColor(image, imageGray, COLOR_RGB2GRAY);
	int width = imageGray.cols;
	int height = imageGray.rows;
	uchar* raw = (uchar*)imageGray.data;
	Image imageZbar(width, height, "Y800", raw, width * height);
	scanner.scan(imageZbar); //扫描条码    
	Image::SymbolIterator symbol = imageZbar.symbol_begin();
	if (imageZbar.symbol_begin() == imageZbar.symbol_end())
	{
		cout << "查询条码失败,请检查图片!" << endl;
	}
      string result;
	for (; symbol != imageZbar.symbol_end(); ++symbol)
	{
		//cout << "类型:" << endl << symbol->get_type_name() << endl << endl;
		//cout << "条码:" << endl << symbol->get_data() << endl << endl;
		result= symbol->get_data();
	}
	imageZbar.set_data(NULL, 0);
 
      const int len = result.length();
      char* c=(char *)malloc(sizeof(char *) * len);

	strcpy(c,result.c_str());
      
     return c;
}

 opencv_core.h

#pragma once
int opencv_detail(const char* fromPath,const char* toPath);

opencv_core.cpp

#ifndef opencv_core_h
#define opencv_core_h
 
 
#include 
#include "opencv2/opencv.hpp"
#include "opencv_core.h"
 
#endif 
 
using namespace cv;
using namespace std;
 
int opencv_detail(const char* fromPath,const char* toPath)
{
	Mat src = imread(fromPath);
	if (src.empty()) {
		printf("error");
		return -1;
	}
 
	Mat gray;
	cvtColor(src, gray, COLOR_RGB2GRAY);
 
 
	Mat binary;
	threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
 
	vector> contours;
	vector hireachy;
	findContours(binary.clone(), contours, hireachy, RETR_TREE, CHAIN_APPROX_NONE, Point());
 
	vector> filter1;
 
	int ic = 0;
	int parentIdx = -1;
 
	for (int i = 0; i < contours.size(); i++)
	{
		if (hireachy[i][2] != -1 && ic == 0)
		{
			parentIdx = i;
			ic++;
		}
		else if (hireachy[i][2] != -1)
		{
			ic++;
		}
		else if (hireachy[i][2] == -1)
		{
			if (ic == 2) {
				RotatedRect rect1 = minAreaRect(contours[parentIdx]);
				RotatedRect rect2 = minAreaRect(contours[parentIdx + 1]);
				RotatedRect rect3 = minAreaRect(contours[parentIdx + 2]);
				if (rect1.size.width / rect1.size.height > 0.85) {
					if ((rect1.size.width - rect2.size.width) / 2 + (rect2.size.width - rect3.size.width) / 2 < rect3.size.width) {
						filter1.push_back(contours[parentIdx]);
					}
				}
			}
			parentIdx = -1;
			ic = 0;
		}
	}
 
	if (filter1.size() < 3) {
		//imshow("input_image", src);
		imwrite(toPath, src);
 
	//	waitKey();
		return 0;
	}
	RotatedRect minRect1 = minAreaRect(Mat(filter1[0]));
	RotatedRect minRect2 = minAreaRect(Mat(filter1[1]));
	RotatedRect minRect3 = minAreaRect(Mat(filter1[2]));
	int minLeft = min(min(minRect1.center.x, minRect2.center.x), minRect3.center.x);
	int maxLeft = max(max(minRect1.center.x, minRect2.center.x), minRect3.center.x);
	int minTop = min(min(minRect1.center.y, minRect2.center.y), minRect3.center.y);
	int maxTop = max(max(minRect1.center.y, minRect2.center.y), minRect3.center.y);
	int rectWidth = minRect1.size.width / 2;
	Rect rect(minLeft - rectWidth, minTop - rectWidth, maxLeft - minLeft + minRect1.size.width, maxLeft - minLeft + minRect1.size.width);
	Mat mat = src(rect);
	//namedWindow("input_image", WINDOW_AUTOSIZE);
	//imshow("input_image", mat);
	imwrite(toPath, mat);
 
	//waitKey();
	return 0;
}

 test.cpp


#include "jni.h"
#ifndef dllmain_h
#define dllmain_h 
#include 
#include "opencv_core.h"
#include "zbar_core.h"
#endif
 
#define FROM_PATH_NULL -1001
#define TO_PATH_NULL -1002
 
#include        
using namespace std;  //这两个支持linux cout
extern "C" {
	JNIEXPORT jstring JNICALL Java_com_java_wjs_opencv_qr_QRScan_decodeByZbar(JNIEnv* env, jobject jobj, jstring fromPath) {
            jboolean b=false;
		const char* fromPathStr = env->GetStringUTFChars(fromPath, &b);
		if (fromPathStr == NULL || strlen(fromPathStr) == 0 || fromPathStr[0] == '\0') {
			return env->NewStringUTF("-1001");
		}
          char* result=decodeByZbar(fromPathStr);
          if (result != NULL) {
			env->ReleaseStringUTFChars(fromPath, fromPathStr);
                        jstring rt=env->NewStringUTF(result);
                   free(result);
			return rt;
	 }
		return env->NewStringUTF("-1003");
	}
}

编写 QRScan.java

package com.java.wjs.opencv.qr;
 
public class QRScan {
    static {
        System.loadLibrary("qrcode2");
    }
    public native String decodeByZbar(String fromPath);
}

编写Main.java

package com.java.wjs.opencv.qr;
public class Main {
    private static final String PATH_PHOTO="/home/admin/test.png";
    long tempTime = System.currentTimeMillis();
    public static final void main(String[] args){
        QRScan qrScan = new QRScan();
        String result=qrScan.decodeByZbar(PATH_PHOTO);
        System.out.println("result:"+result);
	  Main main=new Main();
        main.printTime("寻找二维码所用时间");
 
    }
    public void printTime(String time){
        System.out.println(time+ (System.currentTimeMillis() - tempTime));
        tempTime=System.currentTimeMillis();
    }
}

配置环境变量LD_LIBRARY_PATH指向so

你可能感兴趣的:(C,opencv专栏)