清理验证码图像使用OpenCV

时间:2018-03-03 09:23:14

标签: ios image opencv tesseract captcha

当干涉线和相同颜色的文字时,如何清除干扰线的验证码图片

我尝试使用以下图片作为演示

demo picture

使用以下代码处理

- (UIImage *)cleanLine:(UIImage *)image {

   IplImage *src = [self convertToIplImage:image];

   IplImage *gray = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U, 1);
   IplImage *dst = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U, 1);
   IplImage *binary = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U, 1);

   cvCvtColor(src, gray, CV_RGB2GRAY);
   cvThreshold(gray, binary, 120, 255, CV_THRESH_OTSU);

   findLines(gray, dst);

for (int row = 0; row < binary->height; row++)
    for (int col = 0; col < binary->width; col++)
    {
        if (cvGet2D(dst, row, col).val[0] == 255)
        {
            int up = 0, down = 0;
            int white = 0;
            for (int i = row; i >= 0; i--)
            {
                if (cvGet2D(binary, i, col).val[0] == 0)
                {
                    up++;
                    white = 0;
                }
                else white++;
                if(white > 2)    break;
            }
            white = 0;
            for (int i = row; i < binary->height; i++)
            {
                if (cvGet2D(binary, i, col).val[0] == 0)
                {
                    down++;
                    white = 0;
                }
                else white++;
                if (white > 2)   break;
            }
            if (up + down < 8)
            {
                for (int i = -up; i <= down; i++) cvSet2D(binary, row + i, col, cvScalar(255));
            }
        }
    }

    erase(binary);

    cvErode(binary, binary, NULL, 1);

    cvDilate(binary, binary, NULL, 1);

    Mat Img = cvarrToMat(binary);

    cvReleaseImage(&src);
    cvReleaseImage(&gray);
    cvReleaseImage(&dst);
    cvReleaseImage(&binary);

    return MatToUIImage(Img); 
}

找到干扰代码行

void findLines(IplImage *raw, IplImage *dst) {

IplImage *src = cvCloneImage(raw);
IplImage *canny = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U, 1);

cvCanny(src, canny, 20, 200, 3);
CvMemStorage *stor = cvCreateMemStorage(0);
CvSeq *lines = NULL;

lines = cvHoughLines2(canny, stor, CV_HOUGH_PROBABILISTIC, 1, CV_PI / 180, 80, 200, 30);
cvZero(dst);

CvPoint maxStart, maxEnd;

int maxDistance = 0;


for (int i = 0; i < lines->total; i++) {
    CvPoint* line = (CvPoint*)cvGetSeqElem(lines, i);
    if (abs(line[0].x - line[1].x) > maxDistance) {
        maxDistance = abs(line[0].x - line[1].x);
        maxStart = line[0];
        maxEnd = line[1];
    }
}

cvLine(dst, maxStart, maxEnd, cvScalar(255), 1);

cvReleaseImage(&src);
cvReleaseMemStorage(&stor);
}

获取结果图片result picture

我在这里有一部分验证码图像 captcha image

我使用我的代码来处理验证码图像,但它不起作用

我不知道如何修改我的代码以清除干扰线

任何人都可以指导我,非常感谢

0 个答案:

没有答案