2016-03-09 76 views
2

我是JavaCv的新手。我的任務是在圖像上查找符號並生成單個符號的圖片。 首先,我看到這樣的畫面:enter image description here 後來我做的閾值,並得到這個: enter image description here 我試圖使用cvFindContours的並繪製每個符號的矩形,我的代碼:JavaCV檢測二進制圖像上的驗證碼字母

String filename = "captcha.jpg"; 
    IplImage firstImage=cvLoadImage(filename); 
    Mat src = imread(filename, CV_LOAD_IMAGE_GRAYSCALE); 
    Mat dst = new Mat(); 
    threshold(src, dst, 200, 255, 0); 
    imwrite("out.jpg", dst); 

    IplImage iplImage=cvLoadImage("out.jpg",CV_8UC1); 
    CvMemStorage memStorage=CvMemStorage.create(); 
    CvSeq contours=new CvSeq(); 
    cvFindContours(iplImage,memStorage,contours,Loader.sizeof(CvContour.class),CV_RETR_CCOMP,CV_CHAIN_APPROX_SIMPLE,cvPoint(0,0)); 
    CvSeq ptr; 
    CvRect bb; 
    for (ptr=contours;ptr!=null;ptr=ptr.h_next()){ 
     bb=cvBoundingRect(ptr); 
     cvRectangle(firstImage , cvPoint(bb.x(), bb.y()), 
       cvPoint(bb.x() + bb.width(), bb.y() + bb.height()), 
       CvScalar.BLACK, 2, 0, 0); 

    } 
    cvSaveImage("result.jpg",firstImage); 
} 

我想得到這樣的輸出:enter image description here,但我真的得到這個:enter image description here

請,需要你的幫助。

+0

你爲什麼不使用的OpenCV 2.x或3.0功能?在我看來,這些cv ~~功能最近幾乎不推薦使用。 –

回答

1

您正在使用findContour()的「out.jpg」圖片。
當您將dst Mat保存到「out.jpg」中時,JPEG格式會自動量化您的原始像素數據併爲圖像創建噪音。

將dst保存爲「out.png」而不是「out.jpg」,或者將dst Mat直接保存到findContour()中。

將源代碼加入:C++版本

string filename = "captcha.jpg"; 
Mat src = imread(filename); 
Mat gray; 
cvtColor(src, gray, CV_BGR2GRAY); 
Mat thres; 
threshold(gray, thres, 200, 255, 0); 

vector<vector<Point>> contours; 
vector<Vec4i> hierarchy; 

findContours(thres.clone(), contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); 

Mat firstImage = src.clone(); 
for(int i=0; i< contours.sizes(); i++) 
{ 
    Rect r = boundingRect(contours[i]); 
    rectangle(firstImage, r, CV_RGB(255, 0, 0), 2); 
} 

imwrite("result.png", firstImage); 
+0

非常感謝!它終於有效。 –

+0

@RinatSakaev查看我添加的代碼:我用cv :: ~~特性替換了cv ~~~~~~特性。 –