【问题标题】:Yolo object detection with java and yolov3 --> Parsing error) Unknown layer type: detection in function 'cv::dnn::darknet::ReadDarknetFromCfgStreamYolo object detection with java and yolov3 --> Parsing error) Unknown layer type: detection in function 'cv::dnn::darknet::ReadDarknetFromCfgStream
【发布时间】:2020-11-06 22:51:51
【问题描述】:

我想用yolov3基于openCV做物体检测。目前我正在使用windows,在JAVA中使用eclipse。

我的代码基于: https://github.com/suddh123/YOLO-object-detection-in-java/blob/code/yolo.java

当我执行程序时出现错误:

Exception in thread "main" CvException [org.opencv.core.CvException: cv::Exception: OpenCV(4.5.0) C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\dnn\src\darknet\darknet_importer.cpp:207: error: (-212:Parsing error) Failed to parse NetParameter file: C:\Projects\detection\opencv\yolov3.cfg in function 'cv::dnn::dnn4_v20200908::readNetFromDarknet'
]
    at org.opencv.dnn.Dnn.readNetFromDarknet_0(Native Method)
    at org.opencv.dnn.Dnn.readNetFromDarknet(Dnn.java:543)
    at clement.yolo.main(yolo.java:67)

我的程序代码如下所示:

package clement;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfInt;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.dnn.Dnn;
import org.opencv.dnn.Net;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.utils.Converters;
import org.opencv.videoio.VideoCapture;




public class yolo {

    private static List<String> getOutputNames(Net net) {
        List<String> names = new ArrayList<>();

        List<Integer> outLayers = net.getUnconnectedOutLayers().toList();
        List<String> layersNames = net.getLayerNames();

        outLayers.forEach((item) -> names.add(layersNames.get(item - 1)));//unfold and create R-CNN layers from the loaded YOLO model//
        return names;
    }
    public static void main(String[] args) throws InterruptedException {
        System.load("C:\\Projects\\detection\\opencv_new\\opencv\\build\\java\\x64\\opencv_java450.dll"); // Load the openCV 4.0 dll //
//      System.load("C:\\Projects\\detection\\opencv\\build\\java\\x64\\opencv_java3412.dll"); // Load the openCV 4.0 dll //




            String modelWeights = "C:\\Projects\\detection\\opencv\\yolov3.weights"; //Download and load only wights for YOLO , this is obtained from official YOLO site//
            String modelConfiguration = "C:\\Projects\\detection\\opencv\\yolov3.cfg";//Download and load cfg file for YOLO , can be obtained from official site//

            String filePath = "c:\\clement\\uwe.mp4"; //My video  file to be analysed//
            VideoCapture cap = new VideoCapture(filePath);// Load video using the videocapture method//
             Mat frame = new Mat(); // define a matrix to extract and store pixel info from video//
            Mat dst = new Mat ();
             //cap.read(frame);
             JFrame jframe = new JFrame("Video"); // the lines below create a frame to display the resultant video with object detection and localization//
             JLabel vidpanel = new JLabel();
             jframe.setContentPane(vidpanel);
             jframe.setSize(600, 600);
             jframe.setVisible(true);// we instantiate the frame here//

            Net net = Dnn.readNetFromDarknet(modelConfiguration, modelWeights); //OpenCV DNN supports models trained from various frameworks like Caffe and TensorFlow. It also supports various networks architectures based on YOLO//
            //Thread.sleep(5000);

            //Mat image = Imgcodecs.imread("D:\\yolo-object-detection\\yolo-object-detection\\images\\soccer.jpg");
            Size sz = new Size(288,288);

            List<Mat> result = new ArrayList<>();
            List<String> outBlobNames = getOutputNames(net);

            while (true) {

                if (cap.read(frame)) {





            Mat blob = Dnn.blobFromImage(frame, 0.00392, sz, new Scalar(0), true, false); // We feed one frame of video into the network at a time, we have to convert the image to a blob. A blob is a pre-processed image that serves as the input.//
            net.setInput(blob);



            net.forward(result, outBlobNames); //Feed forward the model to get output //




           // outBlobNames.forEach(System.out::println);
           // result.forEach(System.out::println);

            float confThreshold = 0.6f; //Insert thresholding beyond which the model will detect objects//
            List<Integer> clsIds = new ArrayList<>();
            List<Float> confs = new ArrayList<>();
            List<Rect> rects = new ArrayList<>();
            for (int i = 0; i < result.size(); ++i)
            {
                // each row is a candidate detection, the 1st 4 numbers are
                // [center_x, center_y, width, height], followed by (N-4) class probabilities
                Mat level = result.get(i);
                for (int j = 0; j < level.rows(); ++j)
                {
                    Mat row = level.row(j);
                    Mat scores = row.colRange(5, level.cols());
                    Core.MinMaxLocResult mm = Core.minMaxLoc(scores);
                    float confidence = (float)mm.maxVal;
                    Point classIdPoint = mm.maxLoc;
                    if (confidence > confThreshold)
                    {
                        int centerX = (int)(row.get(0,0)[0] * frame.cols()); //scaling for drawing the bounding boxes//
                        int centerY = (int)(row.get(0,1)[0] * frame.rows());
                        int width   = (int)(row.get(0,2)[0] * frame.cols());
                        int height  = (int)(row.get(0,3)[0] * frame.rows());
                        int left    = centerX - width  / 2;
                        int top     = centerY - height / 2;

                        clsIds.add((int)classIdPoint.x);
                        confs.add((float)confidence);
                       rects.add(new Rect(left, top, width, height));
                    }
                }
            }
            float nmsThresh = 0.5f;
            MatOfFloat confidences = new MatOfFloat(Converters.vector_float_to_Mat(confs));
            Rect[] boxesArray = rects.toArray(new Rect[0]);
            MatOfRect boxes = new MatOfRect(boxesArray);
            MatOfInt indices = new MatOfInt();
//          Dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThresh, indices); //We draw the bounding boxes for objects here//

            int [] ind = indices.toArray();
            int j=0;
            for (int i = 0; i < ind.length; ++i)
            {
                int idx = ind[i];
                Rect box = boxesArray[idx];
                Imgproc.rectangle(frame, box.tl(), box.br(), new Scalar(0,0,255), 2);
                //i=j;

                System.out.println(idx);
            }
           // Imgcodecs.imwrite("D://out.png", image);
            //System.out.println("Image Loaded");
            ImageIcon image = new ImageIcon(Mat2bufferedImage(frame)); //setting the results into a frame and initializing it //
         vidpanel.setIcon(image);
             vidpanel.repaint();
            // System.out.println(j);
            // System.out.println("Done");

            }
                }
    }


//  }
    private static BufferedImage Mat2bufferedImage(Mat image) {   // The class described here  takes in matrix and renders the video to the frame  //
        MatOfByte bytemat = new MatOfByte();
        Imgcodecs.imencode(".jpg", image, bytemat);
        byte[] bytes = bytemat.toArray();
        InputStream in = new ByteArrayInputStream(bytes);
        BufferedImage img = null;
        try {
            img = ImageIO.read(in);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return img;
    }
}

谁能帮帮我?

【问题讨论】:

    标签: java opencv yolo


    【解决方案1】:

    您从中复制的 GitHub 存储库具有此路径 "D:\\yolov3.cfg.txt",而您使用 "C:\\Projects\\detection\\opencv\\yolov3.cfg" 此外,您收到的错误消息是 Failed to parse NetParameter file: C:\Projects\detection\opencv\yolov3.cfg

    这让我相信文件名实际上是yolov3.cfg.txt,而你代码中的路径应该是"C:\\Projects\\detection\\opencv\\yolov3.cfg.txt"

    您也可以查看C:\Projects\detection\opencv目录,看看文件名是yolov3.cfg.txt还是yolov3.cfg

    【讨论】:

    • 你完全正确。我的错。更改路径后,我收到以下错误:线程“main”中的异常 CvException [org.opencv.core.CvException: cv::Exception: OpenCV(4.5.0) C:\build\master_winpack-bindings-win64-vc14- static\opencv\modules\dnn\src\darknet\darknet_io.cpp:865: error: (-212:Parsing error) Unknown layer type: detection in function 'cv::dnn::darknet::ReadDarknetFromCfgStream'] at org. opencv.dnn.Dnn.readNetFromDarknet_0(Native Method) at org.opencv.dnn.Dnn.readNetFromDarknet(Dnn.java:543) at clement.yolo.main(yolo.java:67)
    【解决方案2】:

    你完全正确。我的错。更改路径后,我收到以下错误:

    Exception in thread "main" CvException [org.opencv.core.CvException: cv::Exception: OpenCV(4.5.0) C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\dnn\src\darknet\darknet_io.cpp:865: error: (-212:Parsing error) Unknown layer type: detection in function 'cv::dnn::darknet::ReadDarknetFromCfgStream'
    ]
        at org.opencv.dnn.Dnn.readNetFromDarknet_0(Native Method)
        at org.opencv.dnn.Dnn.readNetFromDarknet(Dnn.java:543)
        at clement.yolo.main(yolo.java:67)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-22
      • 2018-06-22
      • 2021-04-13
      • 2017-10-26
      • 1970-01-01
      • 2022-12-28
      • 1970-01-01
      • 2019-05-24
      相关资源
      最近更新 更多