TensorFlow Object Detection API验证码识别:按Bounding Box坐标排序预测结果
解决验证码识别结果从左到右排序的问题
嘿,这个验证码识别结果排序的问题我熟!我来给你一步步讲清楚怎么搞定它~
首先你得知道,TensorFlow Object Detection API的检测输出里其实包含了每个目标的Bounding Box坐标,只是你之前的代码没用到而已。要实现从左到右排序,核心就是把每个识别到的字符和它的Bounding Box左边界坐标绑定,再按左边界的位置排序。
具体步骤和代码示例
假设你已经通过API得到了检测结果(通常是一个包含detection_boxes、detection_classes、detection_scores的字典),我们可以这样修改代码:
# 先定义你的置信度阈值 threshold = 0.5 objects = [] # 遍历所有检测结果,筛选符合阈值的条目,同时收集坐标信息 for i in range(len(detection_scores[0])): current_score = detection_scores[0][i] if current_score > threshold: # 获取类别名称 class_id = int(detection_classes[0][i]) class_name = category_index[class_id]['name'] # 获取Bounding Box的左边界x坐标(注意TF的坐标格式是 [ymin, xmin, ymax, xmax]) box_coords = detection_boxes[0][i] x_min = box_coords[1] # xmin是左边界,值越小越靠左 # 把类别、分数、坐标存到列表里 objects.append({ 'char': class_name, 'score': current_score, 'left_x': x_min }) # 按左边界x坐标升序排序,这样就得到从左到右的顺序了 sorted_objects = sorted(objects, key=lambda item: item['left_x']) # 输出排序后的结果 for item in sorted_objects: print(f"字符: {item['char']}, 置信度: {item['score']:.2f}")
关键细节说明
- 坐标格式注意:TensorFlow返回的
detection_boxes是归一化的坐标(范围0-1),顺序是[ymin, xmin, ymax, xmax],所以左边界是索引1的元素,别搞混顺序哦。 - 排序逻辑:因为验证码的字符是横向排列的,左边界的
x_min值越小,字符越靠左,所以用key=lambda item: item['left_x']升序排序就刚好符合需求。如果你的验证码有上下排列的情况,还可以先按ymin排序,再按x_min排序。 - 数据关联:通过同一个循环索引
i,我们把detection_classes、detection_scores、detection_boxes里对应位置的数据绑定到一起,这样就不会出现类别和坐标不匹配的问题了。
这样修改后,你每次运行代码得到的识别结果都会是从左到右的正确顺序啦~
内容的提问来源于stack exchange,提问作者Vladimir Kolesnikov
相关产品推荐
相关产品推荐

