IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

OpenCV Discussion :

Assertion dans cvtColor


Sujet :

OpenCV

  1. #1
    Membre habitué Avatar de CLeBeR
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2011
    Messages
    412
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Septembre 2011
    Messages : 412
    Points : 188
    Points
    188
    Par défaut Assertion dans cvtColor
    Bonjour,

    je suis un tutoriel OpenCV de reconnaissance faciale disponible sur la documentation officielle. La compilation se déroule sans problème mais lorsque je lance le programme j'ai l'erreur suivante :

    OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/modules/imgproc/src/color.cpp, line 3737
    New image readError opening file "data.csv". Reason: /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/modules/imgproc/src/color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cvtColor
    J'ai mise quelques cout pour voir d'où vient le problème et comme décrit dans l'erreur, le programme plante sur cette ligne :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    cvtColor(m,m2,CV_BGR2GRAY);
    Voici le code complet :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    /*
     * Copyright (c) 2011. Philipp Wagner <bytefish[at]gmx[dot]de>.
     * Released to public domain under terms of the BSD Simplified license.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions are met:
     *   * Redistributions of source code must retain the above copyright
     *     notice, this list of conditions and the following disclaimer.
     *   * Redistributions in binary form must reproduce the above copyright
     *     notice, this list of conditions and the following disclaimer in the
     *     documentation and/or other materials provided with the distribution.
     *   * Neither the name of the organization nor the names of its contributors
     *     may be used to endorse or promote products derived from this software
     *     without specific prior written permission.
     *
     *   See <http://www.opensource.org/licenses/bsd-license>
     */
     
    #include "opencv2/core/core.hpp"
    #include "opencv2/contrib/contrib.hpp"
    #include "opencv2/highgui/highgui.hpp"
    #include "opencv2/imgproc/imgproc.hpp"
    #include "opencv2/objdetect/objdetect.hpp"
     
    #include <iostream>
    #include <fstream>
    #include <sstream>
     
    using namespace cv;
    using namespace std;
     
    static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
        std::ifstream file(filename.c_str(), ifstream::in);
        if (!file) {
            string error_message = "No valid input file was given, please check the given filename.";
            CV_Error(CV_StsBadArg, error_message);
        }
        string line, path, classlabel;
        int numberImageReaded = 0;
        while (getline(file, line)) {
            stringstream liness(line);
            getline(liness, path, separator);
            getline(liness, classlabel);
            if(!path.empty() && !classlabel.empty()) {
                Mat m = imread(path, 1);
                Mat m2;
                cout << endl << "New image read";
                cvtColor(m,m2,CV_BGR2GRAY);
                numberImageReaded++;
                cout << endl << "Number of image read = " << numberImageReaded;
                images.push_back(m2);
                labels.push_back(atoi(classlabel.c_str()));
            }
        }
        cout << endl << "Read finish";
    }
     
    int main(int argc, const char *argv[]) {
        // Check for valid command line arguments, print usage
        // if no arguments were given.
        if (argc != 4) {
            cout << "usage: " << argv[0] << " </path/to/haar_cascade> </path/to/csv.ext> </path/to/device id>" << endl;
            cout << "\t </path/to/haar_cascade> -- Path to the Haar Cascade for face detection." << endl;
            cout << "\t </path/to/csv.ext> -- Path to the CSV file with the face database." << endl;
            cout << "\t <device id> -- The webcam device id to grab frames from." << endl;
            exit(1);
        }
        // Get the path to your CSV:
        string fn_haar = string(argv[1]);
        string fn_csv = string(argv[2]);
        int deviceId = atoi(argv[3]);
        // These vectors hold the images and corresponding labels:
        vector<Mat> images;
        vector<int> labels;
        // Read in the data (fails if no valid input filename is given, but you'll get an error message):
        try {
            read_csv(fn_csv, images, labels);
        } catch (cv::Exception& e) {
            cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
            // nothing more we can do
            exit(1);
        }
        // Get the height from the first image. We'll need this
        // later in code to reshape the images to their original
        // size AND we need to reshape incoming faces to this size:
        int im_width = images[0].cols;
        int im_height = images[0].rows;
        // Create a FaceRecognizer and train it on the given images:
        Ptr<FaceRecognizer> model = createFisherFaceRecognizer();
        model->train(images, labels);
        // That's it for learning the Face Recognition model. You now
        // need to create the classifier for the task of Face Detection.
        // We are going to use the haar cascade you have specified in the
        // command line arguments:
        //
        CascadeClassifier haar_cascade;
        haar_cascade.load(fn_haar);
        // Get a handle to the Video device:
        VideoCapture cap(deviceId);
        // Check if we can use this device at all:
        if(!cap.isOpened()) {
            cerr << "Capture Device ID " << deviceId << "cannot be opened." << endl;
            return -1;
        }
        // Holds the current frame from the Video device:
        Mat frame;
        for(;;) {
            cap >> frame;
            // Clone the current frame:
            Mat original = frame.clone();
            // Convert the current frame to grayscale:
            Mat gray;
            if(original.empty())
                break;
            else if(original.channels()>1)
                cvtColor(original, gray, CV_BGR2GRAY);
            else gray = original;
            // Find the faces in the frame:
            vector< Rect_<int> > faces;
            haar_cascade.detectMultiScale(gray, faces);
            // At this point you have the position of the faces in
            // faces. Now we'll get the faces, make a prediction and
            // annotate it in the video. Cool or what?
            for(int i = 0; i < faces.size(); i++) {
                // Process face by face:
                Rect face_i = faces[i];
                // Crop the face from the image. So simple with OpenCV C++:
                Mat face = gray(face_i);
                // Resizing the face is necessary for Eigenfaces and Fisherfaces. You can easily
                // verify this, by reading through the face recognition tutorial coming with OpenCV.
                // Resizing IS NOT NEEDED for Local Binary Patterns Histograms, so preparing the
                // input data really depends on the algorithm used.
                //
                // I strongly encourage you to play around with the algorithms. See which work best
                // in your scenario, LBPH should always be a contender for robust face recognition.
                //
                // Since I am showing the Fisherfaces algorithm here, I also show how to resize the
                // face you have just found:
                Mat face_resized;
                cv::resize(face, face_resized, Size(im_width, im_height), 1.0, 1.0, INTER_CUBIC);
                // Now perform the prediction, see how easy that is:
                int prediction = model->predict(face_resized);
                // And finally write all we've found out to the original image!
                // First of all draw a green rectangle around the detected face:
                rectangle(original, face_i, CV_RGB(0, 255,0), 1);
                // Create the text we will annotate the box with:
                string box_text = format("Prediction = %d", prediction);
                // Calculate the position for annotated text (make sure we don't
                // put illegal values in there):
                int pos_x = std::max(face_i.tl().x - 10, 0);
                int pos_y = std::max(face_i.tl().y - 10, 0);
                // And now put it into the image:
                putText(original, box_text, Point(pos_x, pos_y), FONT_HERSHEY_PLAIN, 1.0, CV_RGB(0,255,0), 2.0);
            }
            // Show the result:
            imshow("face_recognizer", original);
            // And display it:
            char key = (char) waitKey(20);
            // Exit this loop on escape:
            if(key == 27)
                break;
        }
        return 0;
    }
    Je précise que j'ai du remplacer cette ligne :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    images.push_back(imread(path, 0));
    par :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    Mat m = imread(path, 1);
    Mat m2;
    cout << endl << "New image read";
    cvtColor(m,m2,CV_BGR2GRAY);
    numberImageReaded++;
    cout << endl << "Number of image read = " << numberImageReaded;
    images.push_back(m2);
    Car j'obtenais une autre erreur :

    OpenCV Error: Image step is wrong (The matrix is not continuous, thus its number of rows can not be changed) in reshape, file /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/modules/core/src/matrix.cpp, line 802
    terminate called after throwing an instance of 'cv::Exception'
    what(): /build/opencv-SviWsf/opencv-2.4.9.1+dfsg/modules/core/src/matrix.cpp:802: error: (-13) The matrix is not continuous, thus its number of rows can not be changed in function reshape

    Abandon (core dumped)
    J'ai également essayé de mettre dans mon fichier data.csv les chemins complets des photos de référence mais ça ne résout pas le problème (Je suis sous Ubuntu 16.04).

    Les réponses apportées pour ce problème disaient de changer de matrice lors de l'insertion (c'est ce que je fais) mais le problème persiste.

    Merci de votre aide.
    Pensez à voter pour une réponse qui vous aide ou pour une personne insolente !
    Si votre sujet est résolu, cliquez sur le bouton !

  2. #2
    Membre habitué Avatar de CLeBeR
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2011
    Messages
    412
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Septembre 2011
    Messages : 412
    Points : 188
    Points
    188
    Par défaut
    Bonjour,
    je viens de changer le code de la lecture du CSV pour ajouter un test de validité sur l'image lue :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
        std::ifstream file(filename.c_str(), ifstream::in);
        if (!file) {
            string error_message = "No valid input file was given, please check the given filename.";
            CV_Error(CV_StsBadArg, error_message);
        }
        string line, path, classlabel;
        int numberImageReaded = 0;
        while (getline(file, line)) {
            stringstream liness(line);
            getline(liness, path, separator);
            getline(liness, classlabel);
            if(!path.empty() && !classlabel.empty()) {
                Mat m = imread(path, 1);
                Mat m2;
                cout << endl << "New image read";
                if (m.empty()) {
                    cout << endl << "Image empty";
                    break;
                }
                cvtColor(m,m2,CV_BGR2GRAY);
                numberImageReaded++;
                cout << endl << "Number of image read = " << numberImageReaded;
                images.push_back(m2);
                labels.push_back(atoi(classlabel.c_str()));
            }
        }
        cout << endl << "Read finish";
    }
    J'obtiens l'erreur suivante à l'exécution :

    New image read
    Image empty
    Erreur de segmentation (core dumped)
    Pensez à voter pour une réponse qui vous aide ou pour une personne insolente !
    Si votre sujet est résolu, cliquez sur le bouton !

  3. #3
    Rédacteur/Modérateur


    Homme Profil pro
    Network game programmer
    Inscrit en
    Juin 2010
    Messages
    7 115
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : Canada

    Informations professionnelles :
    Activité : Network game programmer

    Informations forums :
    Inscription : Juin 2010
    Messages : 7 115
    Points : 32 967
    Points
    32 967
    Billets dans le blog
    4
    Par défaut
    Es-tu sûr de ta lecture d'image ?
    Utiliser std::getline pour du binaire me parait un peu bizarre.
    Pensez à consulter la FAQ ou les cours et tutoriels de la section C++.
    Un peu de programmation réseau ?
    Aucune aide via MP ne sera dispensée. Merci d'utiliser les forums prévus à cet effet.

  4. #4
    Membre habitué Avatar de CLeBeR
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2011
    Messages
    412
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Septembre 2011
    Messages : 412
    Points : 188
    Points
    188
    Par défaut
    Citation Envoyé par Bousk Voir le message
    Es-tu sûr de ta lecture d'image ?
    Utiliser std::getline pour du binaire me parait un peu bizarre.
    Bonjour,
    j'ai suivi le code du tutoriel indiqué plus haut donc normalement le code est bon. Par contre, j'ai du nouveau; j'ai ajouté une vérification des images lues :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    Mat m = imread(path, 1);
    if (m.empty())
    {
        cerr << path << " could not be read." << endl;
        continue;
    }
    Pour chaque image lue, j'obtiens le message d'erreur : could not be read. C'est donc bel et bien la lecture de mon image qui ne fonctionne pas.
    Pensez à voter pour une réponse qui vous aide ou pour une personne insolente !
    Si votre sujet est résolu, cliquez sur le bouton !

  5. #5
    Rédacteur/Modérateur


    Homme Profil pro
    Network game programmer
    Inscrit en
    Juin 2010
    Messages
    7 115
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : Canada

    Informations professionnelles :
    Activité : Network game programmer

    Informations forums :
    Inscription : Juin 2010
    Messages : 7 115
    Points : 32 967
    Points
    32 967
    Billets dans le blog
    4
    Par défaut
    Repassons les classiques en revue
    - chemins utilisés
    - execution path
    - permissions sur les répertoires
    - permissions sur les fichiers
    Pensez à consulter la FAQ ou les cours et tutoriels de la section C++.
    Un peu de programmation réseau ?
    Aucune aide via MP ne sera dispensée. Merci d'utiliser les forums prévus à cet effet.

  6. #6
    Membre habitué Avatar de CLeBeR
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2011
    Messages
    412
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Septembre 2011
    Messages : 412
    Points : 188
    Points
    188
    Par défaut
    Les chemins que me montre la console sont les bons, j'ai bien les permissions lorsque je modifie en console. Comment vérifier que mon programme les ai ? En regardant la documentation je me suis rendu compte qu'il y a un paragraphe dédié à Linux. Il faut apparemment installer une bibliothèque (libjpeg-dev), ce que j'ai fait. Il est dit également qu'il faut ajouter un flag au CMake : OPENCV_BUILD_3RDPARTY_LIBS. Le problème c'est que je compile directement avec la commande suivante : clang++ -std=c++11 main.cpp -o w `pkg-config --cflags --libs opencv`. Comment ajouter ce fameux flag ?
    Merci.
    Pensez à voter pour une réponse qui vous aide ou pour une personne insolente !
    Si votre sujet est résolu, cliquez sur le bouton !

Discussions similaires

  1. L'usage d'assert dans tests unitaires pour les jeux vidéos
    Par Neckara dans le forum Création de jeux vidéo
    Réponses: 28
    Dernier message: 01/04/2015, 12h52
  2. [JMeter] Assertion dans un fichier
    Par pmartin8 dans le forum Tests et Performance
    Réponses: 0
    Dernier message: 10/03/2010, 20h43
  3. crée(simulé) une assertion dans mysql 5.0
    Par mohouch05 dans le forum SQL Procédural
    Réponses: 1
    Dernier message: 14/05/2006, 18h23
  4. [RegEx] Assertion négative dans une classe
    Par xuoy dans le forum Langage
    Réponses: 8
    Dernier message: 20/02/2006, 11h59
  5. Réponses: 5
    Dernier message: 11/01/2006, 07h58

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo