實現python 調用 C++ 接口的 easypr

實現python 調用 C++ 接口的 easypr

本文實現了用python 調用 C++ 的easypr ,實現車牌的識別. CMakelist.txt 以及調用方法將會附上

CMakelist.txt, 需要 注意 add_definitions(-fPIC)  ,因爲沒有這句導致動態鏈接庫編譯失敗,而且在easypr的編譯中也要加上這句.

cmake_minimum_required(VERSION 3.0.0)
project(py_plate_locate)

#動態鏈接庫因爲沒有加這個而失敗
add_definitions(-fPIC)

# c++11 required
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "/home/k/SoftWare/opencv-3.1.0/build")
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "/home/k/SoftWare/opencv-3.2.0/build")
# OpenVC3 required
find_package(OpenCV3.2 REQUIRED)

# where to find header files
set(EASYPR_INCLUDE_DIRS "../include" )

#find include file
include_directories(.)
include_directories(${EASYPR_INCLUDE_DIRS})
include_directories(${OpenCV_INCLUDE_DIRS})

#find lib file path
link_directories(easypr "../build")
link_directories(thirdparty "../build/thirdparty")

# sub directories
#add_subdirectory(thirdparty easypr)

if (CMAKE_SYSTEM_NAME MATCHES "Darwin")
    set(EXECUTABLE_NAME "py_plate_locate")
elseif (CMAKE_SYSTEM_NAME MATCHES "Linux")
    set(EXECUTABLE_NAME "py_plate_locate")
endif ()

#"main.cpp"
set(SOURCE_FILES  "py_plate_detector.cpp")

# set to be releas mode
#  set(CMAKE_BUILD_TYPE Release)

# test cases  生成可執行文件
# add_executable(${EXECUTABLE_NAME} ${SOURCE_FILES})
#生成靜態庫
# add_library(${EXECUTABLE_NAME} STATIC ${SOURCE_FILES})
#生成動態庫
add_library(${EXECUTABLE_NAME} SHARED ${SOURCE_FILES})


# link opencv& easypr libs
target_link_libraries(${EXECUTABLE_NAME} easypr thirdparty ${OpenCV_LIBS})

# MESSAGE(${CMAKE_BINARY_DIR}/../)
SET_TARGET_PROPERTIES(${EXECUTABLE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY  "${CMAKE_BINARY_DIR}/../")

#SET_TARGET_PROPERTIES(${EXECUTABLE_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY  "${CMAKE_BINARY_DIR}/../")

 

C++ 部分 頭文件:py_plate_detector.h


#ifndef PLATE_DETER_H
#define PLATE_DETER_H

#include <iostream>
#include <cstring>
#include "opencv2/opencv.hpp"
#include <easypr.h>
#include <algorithm>
#include<ctime>

extern "C"{

    using namespace std;
    using namespace cv;
    using namespace easypr;

    struct OutRec{
        int locate[200];
    };


    unsigned int plate_recog(int height,int width, uchar* frame_data, OutRec &out);
}
#endif

c++ 實現部分 py_plate_detector.cpp

#include "py_plate_detector.h"

unsigned int plate_recog(int height,int width, uchar* frame_data,OutRec &out){
    
    //convert  image for python type
    cv::Mat image(height,width,CV_8UC3);
    uchar* pxvec = image.ptr<uchar>(0);
    int count = 0;
    for(int row = 0; row < height; row++){
        pxvec = image.ptr<uchar>(row);

        for(int col = 0; col < width; col++){
            for(int c = 0; c < 3; c++){
                pxvec[col*3+c] = frame_data[count];
                count++;
            }
        }
    }
    
    // using easypr to locate the plate
    easypr::CPlateRecognize pr;
    pr.setResultShow(false);
    pr.setDetectType(easypr::PR_DETECT_CMSER);

    vector<easypr::CPlate> plateVec;
    int result = pr.plateRecognize(image, plateVec);
    

    if (result != 0) return  -1;        
    size_t num = plateVec.size();

    // unsigned char * data = new  unsigned char[4*num];
    
    // vector<unsigned int> out_;
    // memset(data,0, 4*num*sizeof(char));       
    // printf("num %d\n", num);
    for (size_t j = 0; j < num; j++)
    {
        CPlate temp_plate = plateVec[j];
        // imshow("plate_locate", temp_plate.getPlateMat());

        RotatedRect rect = temp_plate.getPlatePos();
        if (rect.size.height > rect.size.width)
        {
            std::swap(rect.size.height, rect.size.width);
        }

        int y_off_set = rect.size.height / 2;
        int x_off_set = rect.size.width / 2;
        Point2i left_P;
        Point2i right_P;
        left_P.x = rect.center.x - x_off_set;
        left_P.y = rect.center.y - y_off_set;

        right_P.x = rect.center.x + x_off_set;
        right_P.y = rect.center.y + y_off_set;

        
        Point2i corp_left_P = left_P;
        Point2i corp_right_P = right_P;

        corp_left_P.y = std::max(int(0), int(left_P.y - 4 * rect.size.height));
        corp_right_P.y = left_P.y;

        // cout << "corp_left_P" << corp_left_P << endl;
        // cout << "corp_right_P" << corp_right_P << endl;

        if(corp_left_P.y <0 ) continue;
        if(corp_left_P.x <0) continue;
        if(corp_right_P.y <0) continue; 
        if(corp_right_P.x <0) continue;

        if(std::abs(corp_left_P.y - corp_right_P.y) < 50) continue;
        if(std::abs(corp_left_P.x - corp_right_P.x) < 50) continue;


        //yyxx
        out.locate[4*j+0] = max(0,corp_left_P.y);
        out.locate[4*j+1] = min(height,corp_right_P.y);
        out.locate[4*j+2] = max(0,corp_left_P.x);
        out.locate[4*j+3] = min(width,corp_right_P.x);

    }
    //out_.begin()  是隻想第一個元素的迭代器,確切的說,不是指針
    //傳的話就以 &*out_.begin() 來進行傳遞,實際上一下方式顯得更簡單,不那麼晦澀
    return  0;
} 

 

python 部分代碼:


if __name__ == '__main__':

    #read the so
    ll = cdll.LoadLibrary
    lib_plate_locate = ll("./libpy_plate_locate.so")

    #read image
    frame = cv2.imread("/home/k/Longlongaaago/EasyPR-master/crop_vehicle/testImg/12166814_川BZT515.jpg")
    frame_data = np.asarray(frame, dtype=np.int8)
    #change the data form
    frame_data = frame_data.ctypes.data_as(c_char_p)

    #create the struct
    rec = OutRec()

    #reference the struct
    state = lib_plate_locate.plate_recog(frame.shape[0], frame.shape[1], frame_data,byref(rec))

    locate_list = []
    if state !=0:
        print("plate locate false! or none!")


    for i in range(0,len(rec.locate),4):
        if rec.locate[i+0] == rec.locate[i+1] == rec.locate[i+2] == rec.locate[i+3] ==0:
            break;
        targrt = {}
        targrt["min_y"] = rec.locate[i+0]
        targrt["max_y"] = rec.locate[i + 1]
        targrt["min_x"] = rec.locate[i + 2]
        targrt["max_x"] = rec.locate[i + 3]
        print(rec.locate[i+0])
        print(rec.locate[i + 1])
        print(rec.locate[i + 2])
        print(rec.locate[i + 3])
        locate_list.append(targrt)

    for i in range(len(locate_list)):
        new_frame = frame[locate_list[i]["min_y"]:locate_list[i]["max_y"],locate_list[i]["min_x"]:locate_list[i]["max_x"],:]
        cv2.imshow('image', new_frame)
        cv2.waitKey()

 

至於如何進行編譯,還是要自己學習一些編譯知識

調用成功後,還要注意數值解析

參考博客,實現方式:

https://blog.csdn.net/Willen_/article/details/102744794

中間碰到編譯問題的博客:

https://blog.csdn.net/chengde6896383/article/details/93737256

https://blog.csdn.net/qq_41784559/article/details/89358958

https://blog.csdn.net/u010312436/article/details/52486811

https://blog.csdn.net/chengde6896383/article/details/93737256

https://www.cnblogs.com/luoyinjie/p/7219344.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章