您的位置:首页 > 运维架构

【OpenCV】【图像处理】基于轮廓的字符分割

2015-11-03 17:01 621 查看
vector<IplImage*>  mycvCharSegment(IplImage* image)
{  //此函数利用OpenCV中的cvFindContours找出字符的轮廓后进行字符分割,包括汉字的合并处理,但是要求二值化的图像轮廓清晰
vector<IplImage*> characters;  //存储分割出来的字符的图像头

IplImage* smoothImg = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
cvSmooth(image, smoothImg, CV_MEDIAN, 3, 3, 0, 0);
/*cvNamedWindow("Smooth", CV_WINDOW_AUTOSIZE);
cvShowImage("Smooth", smoothImg);*/

IplImage* contoursImg = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
cvCopy(smoothImg,contoursImg);
CvSeq* contours = NULL;
CvMemStorage* storage = cvCreateMemStorage(0);
int count = cvFindContours(smoothImg, storage, &contours, sizeof(CvContour), CV_RETR_EXTERNAL);

vector<CvRect> rcs;
vector<CvRect> comrcs;
for ( CvSeq* c = contours; c != NULL; c = c->h_next )
{
CvRect rect = cvBoundingRect(c, 0);
rcs.push_back(rect);
}
sort(rcs.begin(), rcs.end(), compareRect); //compareRect是自定义的一个比较函数
vector<CvRect>::iterator itr,itr_next;

float aveHeight = mycvGetRectAveHeight(rcs);
float aveWidth = mycvGetRectAveWidth(rcs);
float maxWidth = mycvGetRectMaxWidth(rcs);
float maxHeight = mycvGetRectMaxHeight(rcs);

for ( itr = rcs.begin(),itr_next=itr+1; itr != rcs.end(); )
{
CvRect rc = *itr;
if(itr_next!= rcs.end())
{
CvRect rcnext = *(itr_next);

if ( (rc.x+rc.width>rcnext.x)||((rc.x<rcnext.x) && (rc.x+rc.width>rcnext.x+rcnext.width)) )
{
rc.x = min(rc.x,rcnext.x);
rc.y = min(rc.y,rcnext.y);
rc.width = max((rc.x+rc.width),(rcnext.x+rcnext.width))-rc.x;
rc.height = max((rc.y+rc.height),(rcnext.y+rcnext.height))-rc.y;

*itr = rc;
itr_next++;
}
else
{
comrcs.push_back(rc);
itr = itr_next++;
}
}
else
{
itr++;
comrcs.push_back(rc);
}
}

for ( itr = comrcs.begin(); itr != comrcs.end(); itr++ )
{
CvRect rc = *itr;
cvDrawRect(image, cvPoint(rc.x, rc.y), cvPoint(rc.x + rc.width, rc.y + rc.height), CV_RGB(255, 255, 255));

cvNamedWindow("字符分割", CV_WINDOW_AUTOSIZE);
cvShowImage("字符分割", image);

IplImage* imgNo = cvCreateImage(cvSize(rc.width , rc.height), IPL_DEPTH_8U, 1);
cvSetImageROI(image, rc);
cvCopyImage(image, imgNo);
cvResetImageROI(image);
cvResetImageROI(imgNo);

IplImage* dst = cvCreateImage(cvSize(rc.width , rc.height), IPL_DEPTH_8U, 1);
cvResize(imgNo, dst);
characters.push_back(dst);
}

return characters;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: