gpt4 book ai didi

java - Java中的Opencv SVM无法正确训练

转载 作者:太空宇宙 更新时间:2023-11-03 21:50:56 24 4
gpt4 key购买 nike

请帮帮我我正在尝试创建Android应用程序来检测答案表中的冒泡答案我使用的是Opencv 3.4,面临的问题是:Opencv-SVM训练不正确,因为训练时间很短(有些秒)这是我的代码:

    private static Mat trainingMat;
private static Mat trainingLabels;
private static SVM clasificador;
private static int img_area = 50 * 70;
private static int negativo_size = 520;
private static int positivo_size = 349;
private static int file_count = 0;

public static void main(String[] args) {
System.load("E:/Android/opencv/build/java/x64/opencv_java340.dll");
trainingMat = new Mat(negativo_size + positivo_size, img_area, CvType.CV_32FC1);
trainingLabels = new Mat(negativo_size + positivo_size, 1, CvType.CV_32S);
trainingLabels = new Mat();
clasificador = SVM.create();
trainPositive();
trainNegative();
train();
test();
}


private static void test() {
SVM svm = SVM.load(new File(XML).getAbsolutePath());
Mat in = getMat(FILE_TEST);
in.reshape(1);
Mat out = new Mat(1, img_area, CvType.CV_32FC1);
int ii = 0;
for (int i = 0; i < in.rows(); i++) {
for (int j = 0; j < in.cols(); j++) {
out.put(1, ii, in.get(i, j));
ii++;
}
}
System.out.println("prediction is:" + svm.predict(out));
}

private static void train() {
clasificador.setType(SVM.C_SVC);
clasificador.setKernel(SVM.POLY);
clasificador.setGamma(3);
clasificador.setDegree(3);
clasificador.train(trainingMat, Ml.ROW_SAMPLE, trainingLabels);
clasificador.save(XML);
}

private static void trainPositive() {
for (File file : new File(PATH_POSITIVE).listFiles()) {
Mat img = getMat(file.getAbsolutePath());
img.reshape(1);
int ii = 0;
for (int i = 0; i < img.rows(); i++) {
for (int j = 0; j < img.cols(); j++) {
trainingMat.put(file_count, ii, img.get(i, j));
ii++;
}
}
file_count++;
}
}

private static void trainNegative() {
for (File file : new File(PATH_NEGATIVE).listFiles()) {
Mat img = getMat(file.getAbsolutePath());
img.reshape(1);
int ii = 0;
for (int i = 0; i < img.rows(); i++) {
for (int j = 0; j < img.cols(); j++) {
trainingMat.put(file_count, ii, img.get(i, j));
ii++;
}
}
file_count++;
}
trainingLabels.rowRange(0,positivo_size-1).setTo(new Scalar(1.0));
trainingLabels.rowRange(positivo_size,positivo_size+negativo_size -1).setTo(new Scalar(-1.0));
}

private static Mat getMat(String path) {
Mat img = new Mat();
Mat con = Imgcodecs.imread(path, Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE);
con.convertTo(img, CvType.CV_32FC1, 1.0 / 255.0);
return img;
}

当我编译这段代码时,SVM预测总是返回1.0发生了什么?
更多细节:
Opencv版本3.4
输入图像大小50*70
负片图像计数=520
正像计数=349;

最佳答案

只要检查SVM是否经过训练你可以用svm.trained()来实现这一点;
如果在train()之后没有训练svm,则返回一个布尔值,它将始终预测100%的精度在不知道项目和数据集的情况下找到解决方案是不可能的我的建议是检查数据集以及如何准备插入到svm中。

关于java - Java中的Opencv SVM无法正确训练,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49083799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com