I have this image and my goal is to extract text from the image and save those texts as a string.My program has been able to detect text from the image but now i want to extract the characters and save it as a string. Is there a way to do it? Following is my code which i used to detect the texts in an image. I followed the tutorial as mentioned in this thread:- Extracting text OpenCV.
When i ran the program, i could see that the texts were bounded by rectangles but now how can i extract the characters from the rectangles and save it as a string? Is there a way to do it?
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace std;
using namespace cv;
vector<cv::Rect> detectLetters(cv::Mat img)
{
std::vector<cv::Rect> boundRect;
cv::Mat img_gray, img_sobel, img_threshold, element;
cvtColor(img, img_gray, CV_BGR2GRAY);
cv::Sobel(img_gray, img_sobel, CV_8U, 1, 0, 3, 1, 0, cv::BORDER_DEFAULT);
cv::threshold(img_sobel, img_threshold, 0, 255, CV_THRESH_OTSU+CV_THRESH_BINARY);
element = getStructuringElement(cv::MORPH_RECT, cv::Size(17, 3) );
cv::morphologyEx(img_threshold, img_threshold, CV_MOP_CLOSE, element); //Does the trick
std::vector< std::vector< cv::Point> > contours;
cv::findContours(img_threshold, contours, 0, 1);
std::vector<std::vector<cv::Point> > contours_poly( contours.size() );
for( int i = 0; i < contours.size(); i++ )
if (contours[i].size()>100)
{
cv::approxPolyDP( cv::Mat(contours[i]), contours_poly[i], 3, true );
cv::Rect appRect( boundingRect( cv::Mat(contours_poly[i]) ));
if (appRect.width>appRect.height)
boundRect.push_back(appRect);
}
return boundRect;
}
int main()
{
Mat img;
img = imread("3d.JPG");
std::vector<cv::Rect> letterBBoxes1=detectLetters(img);
for(int i=0; i< letterBBoxes1.size(); i++)
cv::rectangle(img,letterBBoxes1[i],cv::Scalar(0,255,0),3,8,0);
imshow("image",img);
cvWaitKey(0);
}
Link of my output image is as follows:- http://s26.photobucket.com/user/rebecca1995/media/image_zps3f31a352.jpg.html.
Thanks.