2016-03-09 78 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 ~~~~~~特性。 –