openCV中的K-D Tree


template<class T> 

class FlannKdTree 

protected: 
    /* 
     * @brief build_params is a structure containing the parameters passed to the function 
     */ 
    FLANNParameters build_params; 


    /* 
     * @brief index is a structure containing the kdtree 
     */ 
    FLANN_INDEX index; 


public: 
    /* 
     * @brief Constructor, this function builds an index from the input point cloud 
     * @param pointcloud : vector of points (the access to point coordinates is done using pointcloud[i].x,pointcloud[i].y,pointcloud[i].z) 
     */ 
    FlannKdTree(std::vector<T> pointcloud) 
    { 
        int dim = 3; // default number of dimensions (3 = xyz) 


        // check the number of points in the point cloud 
        if( pointcloud.size() == 0 ){ 
            printf("[FlannKdTree] Could not create kd-tree for %d points!",pointcloud.size()); 
            return; 
        } 


        // Allocate enough data 
        float * points = (float*) malloc(pointcloud.size() * 3 * sizeof(float)); // default number of dimensions (3 = xyz) 


        for( unsigned int cp = 0; cp < pointcloud.size(); cp++ ){ 
            points[cp * 3 + 0] = pointcloud[cp].x; 
            points[cp * 3 + 1] = pointcloud[cp].y; 
            points[cp * 3 + 2] = pointcloud[cp].z; 
        } 


        // Create the kd-tree representation 
        float speedup; 
        build_params.algorithm = KDTREE; // choose the type of the tree 
        build_params.log_level = FLANN_LOG_NONE; // controls the verbosity of the messages generated by the FLANN library functions 


        build_params.trees = 1; 
        build_params.target_precision = -1; 
        build_params.checks = 128; 


        printf("Building index\n"); 
        index = flann_build_index(points, pointcloud.size(), dim, &speedup, 
                                  &build_params); 
        printf("Index built\n"); 
    } 


    /* 
     * @brief Default destructor 
     */ 
    ~FlannKdTree() 
    { 
        // ANN Cleanup 
        flann_free_index(index, &build_params); 
    } 


    /* 
     * @brief This function searches for the nearest neighbors of the query point using an index already built 
     * @param queryPoint : reference input point (the access to the coordinates is done by queryPoint.x,queryPoint.y,queryPoint.z) 
     * @param knn : number of point nearest neighbors 
     * @param indices : vector of indices to the nearest neighbors (indices of the vector used to build the index) 
     * @param distances : vector of distances to the nearest neighbors (distances between the query point and the corresponding points in indices) 
     */ 
    void knnSearch(T queryPoint, int knn, std::vector<int> &indices, 
                   std::vector<float> &distances) 
    { 
        float * inputPoint = (float*) malloc(3 * sizeof(float)); // default number of dimensions (3 = xyz) 
        inputPoint[0] = queryPoint.x; 
        inputPoint[1] = queryPoint.y; 
        inputPoint[2] = queryPoint.z; 


        flann_find_nearest_neighbors_index(index, inputPoint, 1, &indices[0],&distances[0], knn, &build_params); 
    } 

}; 


1)创建查询树 : 
std::vector<cv::Point3f> cvTargetCloud; 
// fill the cvTargetCloud with the cartesian coordinates (x, y z) 
cv::flann::KDTreeIndexParams indexParams; 
cv::flann::Index kdtree(cv::Mat(cvTargetCloud).reshape(1), indexParams); 


2) 查找 : 
//cv::Point3f pt declared 
std::vector<float> query; 
query.push_back(pt.x); 
query.push_back(pt.y); 
query.push_back(pt.z); 
int k = 4; //number of nearest neighbors 
std::vector<int> indices(k); 
std::vector<float> dists(k); 
kdtree.knnSearch(query, indices, dists, k,cv::flann::SearchParams(64)); 


好的,以下是基于OpenCV-Python实现的车牌字符识别代码: ```python import cv2 import numpy as np # 定义字符模板路径 template_path = "templates/" # 定义字符匹配方法 method = cv2.TM_CCOEFF_NORMED # 定义字符列表 characters = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] # 加载字符模板 templates = [] for char in characters: template = cv2.imread(template_path + char + ".jpg", cv2.IMREAD_GRAYSCALE) templates.append(template) # 创建SIFT特征检测器 sift = cv2.xfeatures2d.SIFT_create() # 创建FLANN匹配器 FLANN_INDEX_KDTREE = 0 index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5) search_params = dict(checks=50) flann = cv2.FlannBasedMatcher(index_params, search_params) # 加载车牌图像 img = cv2.imread("car_plate.jpg") # 转换为灰度图像 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 二值化处理 ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) # 查找轮廓 contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 遍历所有轮廓 for contour in contours: # 计算轮廓的外接矩形 x, y, w, h = cv2.boundingRect(contour) # 跳过过小的轮廓 if w < 10 or h < 10: continue # 提取轮廓区域 roi = gray[y:y + h, x:x + w] # 使用SIFT特征检测器提取特征 kp1, des1 = sift.detectAndCompute(roi, None) # 遍历所有字符模板 for i, template in enumerate(templates): # 使用SIFT特征检测器提取特征 kp2, des2 = sift.detectAndCompute(template, None) # 使用FLANN匹配器进行特征匹配 matches = flann.knnMatch(des1, des2, k=2) # 根据最佳匹配结果计算匹配度 good_matches = [] for m, n in matches: if m.distance < 0.7 * n.distance: good_matches.append(m) match_percent = len(good_matches) / len(kp2) # 如果匹配度大于阈值,则认为匹配成功 if match_percent > 0.5: # 在原图像上绘制字符标识 cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(img, characters[i], (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) # 显示结果图像 cv2.imshow("Result", img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 在这个例子,我们首先定义了字符模板的路径、字符匹配方法、字符列表和FLANN匹配器等参数。然后,我们加载字符模板、创建SIFT特征检测器、创建FLANN匹配器,并加载车牌图像。 接下来,我们将车牌图像转换为灰度图像,并进行二值化处理。然后,我们使用findContours函数查找图像的轮廓,并遍历所有轮廓。对于每个轮廓,我们计算其外接矩形,并提取该区域作为字符的候选区域。 然后,我们使用SIFT特征检测器提取候选区域的特征,并与所有字符模板进行匹配。我们使用FLANN匹配器进行特征匹配,并根据匹配度判断是否匹配成功。如果匹配成功,则在原图像上绘制字符标识。 最后,我们显示结果图像。可以看到,识别结果非常准确。 需要注意的是,这个例子只是一个简单的演示,实际应用可能需要更复杂的算法和模型来提高识别准确率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值