2015-03-20 3 views
0

Я кодирую в C++ в visual studioios express 2012, используя opencv 2.4.10 на Windows 7 в 32-разрядной операционной системе, я создаю программу, которая будет захватывать кадр из камеры, обнаруживать края , а затем сделайте некоторые измерения, основанные на местоположении пикселя и длинах этих краев, однако после успешного обнаружения canny edge, houghlines или findcontours, похоже, не работают. Ниже приведена часть моего кода и связанная с этим ошибка, что происходит?OpenCV C++ Преобразование HoughLines не работает

Mat src, srcEdge, ROImat, templ; 
double lowThreshold = 105, highThreshold = lowThreshold*2.2; 
int roi_xstart = 140, roi_ystart = 180, roi_width = 360, roi_height = 140, counter = 0, badpartcounter = 0; 
Rect ROIrect = cvRect(roi_xstart, roi_ystart, roi_width, roi_height); 
Rect matchrect = cvRect(roi_xstart - 10, roi_ystart - 10, roi_width + 20, roi_height + 20); 

int main (int argc, const char** argv) 
{ 
int input; 
if (goodpart == true) 
{ 
    while (looper) 
    { 
     cout<<"1. Capture Image\n"; 
     cout<<"2. Detect Edges of image/create template if first image capture/read\n"; 
     cout<<"3. Compare Template with Captured/Read Image\n"; 
     cout<<"4. Reset counter to reset template\n"; 
     cout<<"5. Read Image\n"; 
     cout<<"6. HoughLines\n"; 
     cout<<"7. Find Contours of img\n"; 
     cout<<"8. Exit program\n"; 
     cin >> input; 
     switch (input) 
     { 
     case 1: 
      src = FrameCapture(); 
      break; 
     case 2: 
      srcEdge = CannyEdge (src, templ); 
      cout << "counter = " << counter << endl; 
      break; 
     case 3: 
      MatchingMethod (srcEdge, templ, goodpart, badpartcounter); 
      break; 
     case 4: 
      counter = 0; 
      break; 
     case 5: 
      src = ReadImage(); 
      imshow (window1, src); 
      waitKey(0); 
      destroyWindow(window1); 
      break; 
     case 6: 
      HoughLineTransform (srcEdge); 
      break; 
     case 7: 
      ContourFinding (srcEdge); 
      break; 
     case 8: 
      looper = false; 
      break; 
     default: 
      cout << "incorrect input"<< endl; 
     } 
     destroyWindow(window1); 
    } 
}else 
{ 
    looper = false; 
} 
return 0; 
} 

здесь функции я создал

//blur image, detect edges, result will be binary (black/white) image of edges detected 
Mat CannyEdge (Mat& src, Mat& templ) 
{ 
//declare matrices to be used in edge detection 
Mat dst; 
Mat src_gray; 
Mat detected_edges; 
//dst is same size as src, all zeros, 8bit 1 channel 
dst.zeros(src.rows, src.cols, CV_8UC1); 
//convert src from 8 bit 3 channel to 8 bit 1 channel grayimage, output is to src_gray 
cvtColor(src, src_gray, CV_RGB2GRAY); 
//applies normal blur to image to reduce image noise using a kernel of size 3, takes 8bit 1 channel grayimage of src_gray, blurs it and outputs it to detected_edges 
blur(src_gray, detected_edges, Size(3,3)); 
//applies canny algorithm for edge detection, takes input of detected edges and outputs back to same matrix 
Canny (detected_edges, detected_edges, lowThreshold, highThreshold, 3); 
//copies image to dst with the mask output from the canny edge detection function, so every pixel that doesn't fit the mask drops to 0, leaving the edges 
src_gray.copyTo(dst, detected_edges); 
//displays image of edges 
threshold (dst, dst, 100, 255, 0); 
namedWindow(window1, CV_WINDOW_AUTOSIZE); 
imshow (window1, dst); 
waitKey(0); 
destroyWindow(window1); 
//if this is the first image taken, it creates a template from the specified region of interest to compare with the next images taken 
if (counter == 0) 
{ 
    Mat ROImat (dst, ROIrect); 
    threshold (ROImat, ROImat, 100, 255, 0); 
    imshow (window2, ROImat); 
    waitKey(0); 
    destroyWindow(window2); 
    ROImat.copyTo (templ); 
} 
counter++; 
return dst; 
} 

//find countours 
void ContourFinding (Mat srcEdge) 
{ 

vector<vector<Point> > contouroutput; 
vector<Vec4i> hierarchy; 
Point ROIstart; 
ROIstart.x = roi_xstart, ROIstart.y = roi_ystart; 
Mat contourinput (srcEdge, ROIrect); 
Mat contourimage = Mat::zeros(contourinput.size(), CV_8UC3); 
findContours(contourinput, contouroutput, hierarchy, 0, 1, ROIstart); 
int idx = 0; 
for(; idx >= 0; idx = hierarchy[idx][0]) 
{ 
    Scalar color(rand()&255, rand()&255, rand()&255); 
    drawContours(contourimage, contouroutput, idx, color, CV_FILLED, 8, hierarchy, 2, ROIstart); 
} 

namedWindow("Components", 1); 
imshow("Components", contourinput); 
waitKey(0); 

} 

//Hough Line Transformation function 
void HoughLineTransform (Mat srcEdge) 
{ 
Mat cdst; 
Mat hdst (srcEdge, matchrect); 
vector<Vec4i> lines; 
HoughLinesP(hdst, lines, 1, CV_PI/180, 150, 30, 10); 
for(size_t i = 0; i < lines.size(); i++) 
{ 
    line(cdst, Point(lines[i][0], lines[i][1]), 
     Point(lines[i][2], lines[i][3]), Scalar(0,0,255), 3, 8); 
} 
} 

здесь ошибка, которая выбрасывается для контуров

Unhandled exception at 0x54CD1600 (opencv_core2410.dll) in Template Matching.exe: 0xC0000005: Access violation reading location 0x00389738. 

, а затем, когда я иду к разборке

00BD4B8E E8 C1 3B 00 00  call  cv::findContours (0BD8754h) 
00BD4B93 83 C4 1C    add   esp,1Ch 

со второй строкой, как «следующая Команда должна быть выполнена»

, а затем для Хаф

Unhandled exception at 0x008952D3 in Template Matching.exe: 0xC0000005: Access violation reading location 0x0036E004. 

и в разборке

008952CD 89 A5 50 FE FF FF mov   dword ptr [ebp-1B0h],esp 
008952D3 8B 08    mov   ecx,dword ptr [eax] 

в нижней строке следующий оператор будет выполняться я не знаком с указателем стеков, выделение памяти или код сборки

+0

Я думаю, что это имеет какое-то отношение к распределению памяти, потому что размер векторов линий невероятно велик, но, честно говоря, я - noob при поиске и устранении неисправностей/отладки, так что любой совет/экспертиза высоко ценится – jschnitz1

+0

где MatchingMethod ?? – Micka

+0

Метод соответствия - это отдельная функция, работающая нормально, поэтому я оставил функцию. Это было для элементарной проверки, связанной с сопоставлением шаблонов, я не хотел заполнять всю страницу кодом, который не имел отношения к ошибке – jschnitz1

ответ

1

так что это очень простое исправление, в режиме отладки у меня были все дополнительные библиотеки, то есть

opencv_core2410.lib

opencv_core2410d.lib

для всех модулей, удаление библиотек релиза и просто держать opencv_core2410d.lib и т.д., сделал всю эту работу. Когда я изначально задавал свойства проекта, я настраивал режимы отладки и выпуска и, следовательно, включал каждую библиотеку.