0

I want write simple code to extract HOG features and then train SVM. but this exception occur, i try different OpenCV versions like 3.4.5 and 4.0 but not differ.

cv::HOGDescriptor hogDetector = cv::HOGDescriptor();
    hogDetector.winSize = cv::Size(256, 256);
    hogDetector.blockSize = cv::Size(64, 64);
    hogDetector.blockStride = cv::Size(192, 192);
    hogDetector.cellSize = cv::Size(32, 32);

and function return HOG features :

cv::Mat computeHOG(cv::Mat img)
{
    std::vector<float> descriptors;
    std::vector<cv::Point> locations;
    hogDetector.compute(img, descriptors, cv::Size(8, 8), cv::Size(0, 0), locations);
    cv::Mat row = cv::Mat(descriptors);
    return row;
}

and main code for extract features :

cv::Mat trainFeatures;
cv::Mat trainLables;
while (!PFile.eof())
    {
        std::string name; std::getline(PFile, name);
        std::vector<std::string> parts = splitString(name, ' ');
        cv::Mat img = cv::imread(basePath + parts[0]);
        cv::cvtColor(img, img, cv::COLOR_BGR2GRAY);
        cv::resize(img, img,cv::Size(1250, 320));
        cv::Mat f = computeHOG(img);
        trainFeatures.push_back(f);
        trainLables.push_back(std::stoi(parts[1]));
    }

exception occur in line : trainFeatures.push_back(f);, and f shape is 1 * 1 * 162000

full exception :

Exception thrown at 0x00007FFF5A9C17E5 (opencv_world345d.dll) in vehicleRecognition.exe: 0xC0000005: Access violation reading location 0x000002A830658140.
ali kiani
  • 807
  • 1
  • 13
  • 28
  • Are you sure the exception is thrown from trainFeatures.push_back? sometimes the IDE will point you to the next instruction instead of the one that cause the exception. Also, I'm not sure how cv::Mat allocates memory but you could try to allocate it on heap. – TwoOfDiamonds Mar 10 '19 at 06:05
  • @TwoOfDiamonds how can i allocate it on heap? – ali kiani Mar 10 '19 at 06:08
  • Unrelated: [`while (!PFile.eof())` is a common error.](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – user4581301 Mar 10 '19 at 06:10
  • @ali kiani look into unique_ptr or shared_ptr (smart pointers) – TwoOfDiamonds Mar 11 '19 at 07:03

1 Answers1

1

in debugging i found f Mat (HOG features) is FLOAT32 but trainFeatures is UINT8, first i change cv::Mat trainFeatures; to cv::Mat trainFeatures = cv::Mat1f(); but not differ and again change it to cv::Mat trainFeatures = cv::Mat(1, 162000,CV_32FC1); and work, fixed issue. and also change row with : row = row.reshape(1, 1);

I don't know why fixed issue and it's weird why OpenCV automatically can't detect its. if you have better solution please write it.

ali kiani
  • 807
  • 1
  • 13
  • 28