Java OpenCV DNN提取置信度遇空指针异常求助
OpenCV中从detections提取置信度空指针问题排查
问题描述
- 从OpenCV的
Mat类型对象detections提取置信度时,执行代码double confidence; confidence = detections.get(i, 2)[0];抛出空指针异常:Exception in thread "main" java.lang.NullPointerException: Cannot load from double array because the return value of "org.opencv.core.Mat.get(int, int)" is null
- 改用非空判断代码后,
detection = detections.get(i, 2)始终返回null:
double[] detection; detection = detections.get(i, 2); if (detection != null) { confidence = detection[0]; System.out.println("i : " + i + " Confidence : " + confidence); }
- 打印
detections的内容如下:
dump : [1.6463306; 0.39511931; 0.59267896; 1.778037; 0.52682579; 0.46097255; 1.8438902; etc...
错误原因
从打印的detections内容可以看出,这个Mat是1列的一维矩阵,所有检测结果的数值按顺序平铺在同一列中。但你调用get(i, 2)是试图获取第i行、第2列的元素——而该矩阵根本不存在第2列,因此get方法返回null,触发空指针异常。
解决方法
目标检测输出的常规格式中,每个检测结果会包含多个数值(如坐标、宽高、置信度等),置信度通常是每个检测结果的第3个值(索引从0开始为2)。针对一维Mat的情况,有两种处理方式:
方式1:直接计算一维索引
先确定每个检测结果包含的数值个数(比如YOLO输出通常是5个:x、y、宽、高、置信度),然后计算置信度对应的一维索引,再通过get(0, 索引)获取(一维Mat的行索引固定为0):
int numPerResult = 5; // 根据你的检测输出调整此数值 double[] confidenceArr = detections.get(0, i * numPerResult + 2); if (confidenceArr != null) { double confidence = confidenceArr[0]; System.out.println("i : " + i + " Confidence : " + confidence); }
方式2:将一维Mat转为二维Mat
通过reshape方法把一维Mat转换成按检测结果分行的二维Mat,之后就可以按行、列正常访问:
int numPerResult = 5; // 每个检测结果的数值个数 Mat detections2D = detections.reshape(1, detections.rows() / numPerResult); double[] detection = detections2D.get(i, 2); if (detection != null) { double confidence = detection[0]; System.out.println("i : " + i + " Confidence : " + confidence); }
内容的提问来源于stack exchange,提问作者Tom C
相关产品推荐
相关产品推荐

