Java OpenCV文件存储和Mat.push_

Java OpenCV文件存储和Mat.push_,java,c++,opencv,Java,C++,Opencv,我正试图用Java for KNN分类器实现这个项目,即GenData.cpp(用C++编写) 我已到达以下代码行并卡住: matClassificationInts.push_back(intChar); cv::FileStorage fsClassifications("classifications.xml", cv::FileStorage::WRITE); fsClassifications << "classifications" << matClassif

我正试图用Java for KNN分类器实现这个项目,即GenData.cpp(用C++编写)
我已到达以下代码行并卡住:

matClassificationInts.push_back(intChar);
cv::FileStorage fsClassifications("classifications.xml", cv::FileStorage::WRITE);
fsClassifications << "classifications" << matClassificationInts;
fsClassifications.release();
matclassificationts.push_-back(intChar);
cv::FileStorage fsclassification(“classification.xml”,cv::FileStorage::WRITE);
FSU分类(最小轮廓面积){
Rect boundingRect=Imgproc.boundingRect(ptcours.get(i));
Imgproc.rectangle(imgTrainingNumbers,boundingRect.tl(),boundingRect.br(),新标量(0,0255),2);
Mat matROI=imgThresh.submat(boundingRect.y,boundingRect.y+boundingRect.height,boundingRect.x,boundingRect.x+boundingRect.width);
MatroResized=新Mat();
调整大小(调整大小、调整大小、新大小(调整大小的图像宽度、调整大小的图像高度));
/*
im.showImage(matROI);
im.showImage(拟阵化);
im.showImage(imgTrainingNumber);
*/
字符串输入=键盘.nextLine();
int intChar=(int)input.charAt(0);
if(Arrays.binarySearch(intValidChars,intChar)>=0){
/*
MatClassifications.push_back(intChar);
//这里我得到一个错误。
*/
Mat matImageFloat=新Mat();
拟阵化。转换为(matImageFloat,CV_32FC1);
Mat MatimageFlattedFloat=matImageFloat.重塑(1,1);
MattrainingImagesAsFlattedFloat。向后推(MatimageFlattedFloat);
}
}
}
//这里应该有文件存储的东西。
}   
}
提前谢谢

另外,使用OpenCV_310+Java(不是JavaCV)

我自己做了解决方案我猜相当脏,但事实就是这样。如果你知道如何改进我的代码,我很乐意阅读你的评论
1) 我的第一个问题是关于在Mat中添加int(用于进一步生成*.xml)。我避免了这种方法,并决定将int(实际上是整数)放入列表中

 Scanner keyboard = new Scanner(System.in);
 String input = keyboard.nextLine();
 int intChar = (int)input.charAt(0);
 List<Integer> matClassificationInts = new ArrayList<Integer>();
 if (Arrays.binarySearch(intValidChars, intChar) >=0) {
    matClassificationInts.add(new Integer(intChar));
    ......
 }
 String dataImages = "";
 for (Integer i : matClassificationInts) {
     dataImages += i + " ";
 }
并使用这些函数创建*.xml:
Classifications.xml:

    DocumentBuilderFactory icFactory_images = DocumentBuilderFactory.newInstance();
    DocumentBuilder icBuilder_images;
    try {
        icBuilder_images = icFactory_images.newDocumentBuilder();
        Document doc = icBuilder_images.newDocument();
        Element mainRootElement = doc.createElement("opencv_storage");
        doc.appendChild(mainRootElement);
        mainRootElement.appendChild(getMatXML(doc, "classifications", "opencv-matrix", rowsImages, colsImages, "i", dataImages));
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
        DOMSource source = new DOMSource(doc);
        String filename = "classifications.xml";
        File file = new File(filename);
        StreamResult console = new StreamResult(file); //(System.out)
        transformer.transform(source, console);
    } catch (Exception e) {
        e.printStackTrace();
    }
Images.xml:

    DocumentBuilderFactory icFactory_classifications = DocumentBuilderFactory.newInstance();
    DocumentBuilder icBuilder_classifications;
    try {
        icBuilder_classifications = icFactory_classifications.newDocumentBuilder();
        Document doc = icBuilder_classifications.newDocument();
        Element mainRootElement = doc.createElement("opencv_storage");
        doc.appendChild(mainRootElement);
        mainRootElement.appendChild(getMatXML(doc, "images", "opencv-matrix", rowsClassifications, colsClassifications, "f", dataClassifications));
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
        DOMSource source = new DOMSource(doc);
        String filename = "images.xml";
        File file = new File(filename);
        StreamResult console = new StreamResult(file); //(System.out)
        transformer.transform(source, console);
    } catch (Exception e) {
        e.printStackTrace();
    }
例如,生成的分类文件是:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<opencv_storage>
<classifications type_id="opencv-matrix">
<rows>2</rows>
<cols>1</cols>
<dt>i</dt>
<data>49 48 </data>
</classifications>
</opencv_storage>

2.
1.
我
49 48 
我为这张照片做了测试:

通过GenData.cpp(见问题中的链接-第1行)和我的Java代码(完整代码见下文)。两个程序都给了我相同的结果:
对于Java OpenCV Imshow实现,您可以看一看(不是我的)。

导入java.io.File;
导入java.io.FileNotFoundException;
导入java.io.FileOutputStream;
导入java.io.FileReader;
导入java.io.IOException;
导入java.util.ArrayList;
导入java.util.array;
导入java.util.List;
导入java.util.Map;
导入java.util.Scanner;
导入org.opencv.core.core;
导入静态org.opencv.core.CvType.CV_32FC1;
导入org.opencv.core.Mat;
导入org.opencv.core.MatOfInt4;
导入org.opencv.core.MatOfPoint;
导入org.opencv.core.Rect;
导入org.opencv.core.Scalar;
导入org.opencv.core.Size;
导入org.opencv.imgcodecs.imgcodecs;
导入org.opencv.imgproc.imgproc;
导入静态org.opencv.imgproc.imgproc.ADAPTIVE_THRESH_GAUSSIAN_C;
导入静态org.opencv.imgproc.imgproc.CHAIN\u近似\u简单;
导入静态org.opencv.imgproc.imgproc.RETR\u外部;
导入静态org.opencv.imgproc.imgproc.THRESH\u BINARY\u INV;
//XML-write。
导入javax.xml.parsers.DocumentBuilder;
导入javax.xml.parsers.DocumentBuilderFactory;
导入javax.xml.transform.OutputKeys;
导入javax.xml.transform.Transformer;
导入javax.xml.transform.TransformerFactory;
导入javax.xml.transform.dom.DOMSource;
导入javax.xml.transform.stream.StreamResult;
导入org.w3c.dom.Document;
导入org.w3c.dom.Element;
导入org.w3c.dom.Node;
公共类genData{
私有静态最终整数
最小轮廓面积=100,
调整大小的图像宽度=20,
调整大小的图像高度=30;
公共静态void main(字符串[]args)引发IOException{
System.loadLibrary(Core.NATIVE\u LIBRARY\u NAME);
扫描仪键盘=新扫描仪(System.in);
Mat imgtrainingnumber;
Mat imgGrayscale=新Mat();
Mat imgBlurred=新Mat();
Mat imgThresh=新Mat();
Mat imgThreshCopy=新Mat();
ArrayList=新的ArrayList();
MatOfInt4 v4iHierarchy=新的MatOfInt4();
List MatClassificationts=new ArrayList();
Matt MattrainingImagesAsFlattedFloats=新Mat();
int[]intValidChars={'0','1','2','3','4','5','6','7','8','9',',
‘A’、‘B’、‘C’、‘E’、‘H’,
‘K’、‘M’、‘O’、‘P’、‘T’,
'X','Y'};
Arrays.sort(intValidChars);
imgTrainingNumbers=Imgcodecs.imread(“01.png”);
if(imgTrainingNumbers.empty()){
System.out.println(“错误:找不到文件”);
返回;
}
Imgproc.cvt颜色(imgTrainingNumber、imgRayScale、Imgproc.COLOR\u bgr2灰色);
Imgproc.GaussianBlur(imgGrayscale,imgBlurred,新尺寸(5,5),0);
Imgproc.adaptiveThreshold(imgBlurred,imgThresh,255,自适应阈值高斯C,阈值二进制INV,11,2);
Imshow im=新Imshow(“imgThresh”);
im.showImage(imgThresh);
imgThreshCopy=imgThresh.clone();
Imgproc.findContours(imgThreshCopy、ptContours、v4iHierarchy、RETR_EXTERNAL、CHAIN_Abrox_SIMPLE);
对于(int i=0;iMIN_Contours_AREA){
Rect boundingRect=Imgproc.boundingRect(ptcours.get(i));
Imgproc.rectangle(imgTrainingNumbers,boundingRect.tl(),boundingRect.br(),新标量(0,0255),2);
Mat matROI=imgThresh.submat(boundingRect.y,boundingRect.y+boundingRect.height,boundingRect.x,boundingRect.x+b
private static Node getMatXML(Document doc, String option_id, String type_id, String rows, String cols, String dt, String data) {
    Element elem = doc.createElement(option_id);
    elem.setAttribute("type_id", type_id);
    elem.appendChild(getMatXMLElement(doc,"rows", rows));
    elem.appendChild(getMatXMLElement(doc, "cols", cols));
    elem.appendChild(getMatXMLElement(doc, "dt", dt));
    elem.appendChild(getMatXMLElement(doc, "data", data));
    return elem;
}

private static Node getMatXMLElement(Document doc, String name, String value) {
    Element node = doc.createElement(name);
    node.appendChild(doc.createTextNode(value));
    return node;
}
    DocumentBuilderFactory icFactory_images = DocumentBuilderFactory.newInstance();
    DocumentBuilder icBuilder_images;
    try {
        icBuilder_images = icFactory_images.newDocumentBuilder();
        Document doc = icBuilder_images.newDocument();
        Element mainRootElement = doc.createElement("opencv_storage");
        doc.appendChild(mainRootElement);
        mainRootElement.appendChild(getMatXML(doc, "classifications", "opencv-matrix", rowsImages, colsImages, "i", dataImages));
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
        DOMSource source = new DOMSource(doc);
        String filename = "classifications.xml";
        File file = new File(filename);
        StreamResult console = new StreamResult(file); //(System.out)
        transformer.transform(source, console);
    } catch (Exception e) {
        e.printStackTrace();
    }
    DocumentBuilderFactory icFactory_classifications = DocumentBuilderFactory.newInstance();
    DocumentBuilder icBuilder_classifications;
    try {
        icBuilder_classifications = icFactory_classifications.newDocumentBuilder();
        Document doc = icBuilder_classifications.newDocument();
        Element mainRootElement = doc.createElement("opencv_storage");
        doc.appendChild(mainRootElement);
        mainRootElement.appendChild(getMatXML(doc, "images", "opencv-matrix", rowsClassifications, colsClassifications, "f", dataClassifications));
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
        DOMSource source = new DOMSource(doc);
        String filename = "images.xml";
        File file = new File(filename);
        StreamResult console = new StreamResult(file); //(System.out)
        transformer.transform(source, console);
    } catch (Exception e) {
        e.printStackTrace();
    }
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<opencv_storage>
<classifications type_id="opencv-matrix">
<rows>2</rows>
<cols>1</cols>
<dt>i</dt>
<data>49 48 </data>
</classifications>
</opencv_storage>
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import org.opencv.core.Core;
import static org.opencv.core.CvType.CV_32FC1;
import org.opencv.core.Mat;
import org.opencv.core.MatOfInt4;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import static org.opencv.imgproc.Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C;
import static org.opencv.imgproc.Imgproc.CHAIN_APPROX_SIMPLE;
import static org.opencv.imgproc.Imgproc.RETR_EXTERNAL;
import static org.opencv.imgproc.Imgproc.THRESH_BINARY_INV;

//XML - write.
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class genData {


    private static final int 
            MIN_CONTOUR_AREA = 100,
            RESIZED_IMAGE_WIDTH = 20,
            RESIZED_IMAGE_HEIGHT = 30;

    public static void main(String[] args) throws IOException {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME); 
        Scanner keyboard = new Scanner(System.in);

        Mat imgTrainingNumbers;
        Mat imgGrayscale = new Mat();
        Mat imgBlurred = new Mat();
        Mat imgThresh = new Mat();
        Mat imgThreshCopy = new Mat();

        ArrayList<MatOfPoint> ptContours = new ArrayList<MatOfPoint>();
        MatOfInt4 v4iHierarchy = new MatOfInt4();

        List<Integer> matClassificationInts = new ArrayList<Integer>();

        Mat matTrainingImagesAsFlattenedFloats = new Mat();

        int[] intValidChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'E', 'H',
        'K', 'M', 'O', 'P', 'T',
        'X', 'Y'};
        Arrays.sort(intValidChars);

        imgTrainingNumbers = Imgcodecs.imread("01.png");

        if (imgTrainingNumbers.empty()) {
            System.out.println("Error: file is not found");
            return;
        }

        Imgproc.cvtColor(imgTrainingNumbers, imgGrayscale, Imgproc.COLOR_BGR2GRAY);
        Imgproc.GaussianBlur(imgGrayscale, imgBlurred, new Size(5, 5), 0);
        Imgproc.adaptiveThreshold(imgBlurred, imgThresh, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY_INV, 11, 2);

        Imshow im = new Imshow("imgThresh");
        im.showImage(imgThresh);
        imgThreshCopy = imgThresh.clone();

        Imgproc.findContours(imgThreshCopy, ptContours, v4iHierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);


        for (int i = 0; i < ptContours.size(); i++) {
            if (Imgproc.contourArea(ptContours.get(i)) > MIN_CONTOUR_AREA) {
                Rect boundingRect = Imgproc.boundingRect(ptContours.get(i));
                Imgproc.rectangle(imgTrainingNumbers, boundingRect.tl(), boundingRect.br(), new Scalar(0, 0, 255), 2);
                Mat matROI = imgThresh.submat(boundingRect.y, boundingRect.y + boundingRect.height, boundingRect.x, boundingRect.x + boundingRect.width);
                Mat matROIResized = new Mat();
                Imgproc.resize(matROI, matROIResized, new Size(RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT));
                im.showImage(matROI);
                im.showImage(matROIResized);
                im.showImage(imgTrainingNumbers);
                String input = keyboard.nextLine();
                int intChar = (int)input.charAt(0);
                if (Arrays.binarySearch(intValidChars, intChar) >=0) {
                    matClassificationInts.add(new Integer(intChar));
                    Mat matImageFloat = new Mat();
                    matROIResized.convertTo(matImageFloat, CV_32FC1);
                    Mat matImageFlattenedFloat = matImageFloat.reshape(1, 1);
                    matTrainingImagesAsFlattenedFloats.push_back(matImageFlattenedFloat);
                }
            }
        }

        String dataImages = "";
        for (Integer i : matClassificationInts) {
            dataImages += i + " ";
        }

        String dataClassifications = "";
        for (int i = 0; i < matTrainingImagesAsFlattenedFloats.rows(); i++) {
            for (int j = 0; j < matTrainingImagesAsFlattenedFloats.cols(); j++) {
                double[] temp = matTrainingImagesAsFlattenedFloats.get(i, j);
                dataClassifications += temp[0] + " ";
            }
            dataClassifications += "\n";
        }

        String rowsImages = String.valueOf(matClassificationInts.size());
        String colsImages = "1";
        String rowsClassifications = String.valueOf(matTrainingImagesAsFlattenedFloats.rows());
        String colsClassifications = String.valueOf(matTrainingImagesAsFlattenedFloats.cols());

        DocumentBuilderFactory icFactory_images = DocumentBuilderFactory.newInstance();
        DocumentBuilder icBuilder_images;
        try {
            icBuilder_images = icFactory_images.newDocumentBuilder();
            Document doc = icBuilder_images.newDocument();
            Element mainRootElement = doc.createElement("opencv_storage");
            doc.appendChild(mainRootElement);
            mainRootElement.appendChild(getMatXML(doc, "classifications", "opencv-matrix", rowsImages, colsImages, "i", dataImages));
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
            DOMSource source = new DOMSource(doc);
            String filename = "classifications.xml";
            File file = new File(filename);
            StreamResult console = new StreamResult(file); //(System.out)
            transformer.transform(source, console);
        } catch (Exception e) {
            e.printStackTrace();
        }

        DocumentBuilderFactory icFactory_classifications = DocumentBuilderFactory.newInstance();
        DocumentBuilder icBuilder_classifications;
        try {
            icBuilder_classifications = icFactory_classifications.newDocumentBuilder();
            Document doc = icBuilder_classifications.newDocument();
            Element mainRootElement = doc.createElement("opencv_storage");
            doc.appendChild(mainRootElement);
            mainRootElement.appendChild(getMatXML(doc, "images", "opencv-matrix", rowsClassifications, colsClassifications, "f", dataClassifications));
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
            DOMSource source = new DOMSource(doc);
            String filename = "images.xml";
            File file = new File(filename);
            StreamResult console = new StreamResult(file); //(System.out)
            transformer.transform(source, console);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Finished.");
        System.exit(0);
    }   

    private static Node getMatXML(Document doc, String option_id, String type_id, String rows, String cols, String dt, String data) {
        Element elem = doc.createElement(option_id);
        elem.setAttribute("type_id", type_id);
        elem.appendChild(getMatXMLElement(doc,"rows", rows));
        elem.appendChild(getMatXMLElement(doc, "cols", cols));
        elem.appendChild(getMatXMLElement(doc, "dt", dt));
        elem.appendChild(getMatXMLElement(doc, "data", data));
        return elem;
    }

    private static Node getMatXMLElement(Document doc, String name, String value) {
        Element node = doc.createElement(name);
        node.appendChild(doc.createTextNode(value));
        return node;
    }
}