我需要将一些图像转换为二进制文件以进行OCR。
以下是我正在使用的功能:
Mat binarize(Mat & Img, Mat& res, float blocksize, bool inverse)
{
Img.convertTo(Img,CV_32FC1,1.0/255.0);
CalcBlockMeanVariance(Img,res, blocksize, inverse);
res=1.0-res;
res=Img+res;
if (inverse) {
cv::threshold(res,res,0.85,1,cv::THRESH_BINARY_INV);
} else {
cv::threshold(res,res,0.85,1,cv::THRESH_BINARY);
}
cv::resize(res,res,cv::Size(res.cols/2,res.rows/2));
return res;
}
CalcBlockMeanVariance
:
void CalcBlockMeanVariance(Mat& Img,Mat& Res,float blockSide, bool inverse) //21 blockSide - the parameter (set greater for larger font on image)
{
Mat I;
Img.convertTo(I,CV_32FC1);
Res=Mat::zeros(Img.rows/blockSide,Img.cols/blockSide,CV_32FC1);
Mat inpaintmask;
Mat patch;
Mat smallImg;
Scalar m,s;
for(int i=0;i<Img.rows-blockSide;i+=blockSide)
{
for (int j=0;j<Img.cols-blockSide;j+=blockSide)
{
patch=I(Range(i,i+blockSide+1),Range(j,j+blockSide+1));
cv::meanStdDev(patch,m,s);
if(s[0]>0.01) // Thresholding parameter (set smaller for lower contrast image)
{
Res.at<float>(i/blockSide,j/blockSide)=m[0];
}else
{
Res.at<float>(i/blockSide,j/blockSide)=0;
}
}
}
cv::resize(I,smallImg,Res.size());
if (inverse) {
cv::threshold(Res,inpaintmask,0.02,1.0,cv::THRESH_BINARY_INV);
} else {
cv::threshold(Res,inpaintmask,0.02,1.0,cv::THRESH_BINARY);
}
Mat inpainted;
smallImg.convertTo(smallImg,CV_8UC1,255);
inpaintmask.convertTo(inpaintmask,CV_8UC1);
inpaint(smallImg, inpaintmask, inpainted, 5, INPAINT_TELEA);
cv::resize(inpainted,Res,Img.size());
Res.convertTo(Res,CV_32FC1,1.0/255.0);
}
当我将1
传递给CalcBlockMeanVariance
blockSide
时,我得到了这个结果,我试图提升blockSide
,但这只会导致更糟糕的结果。
在:
后:
有人可以建议使用不同的方法将此图像转换为二进制文件作为OCR的准备工作吗?
感谢。
答案 0 :(得分:7)
我认为您可以使用Otsu方法进行阈值处理。您可以将它应用于整个图像或图像块。我做了以下步骤:
Otsu
方法对所需输入进行阈值处理。 Closing
结果。Python代码
image = cv2.imread('image4.png', cv2.IMREAD_GRAYSCALE) # reading image
if image is None:
print 'Can not find the image!'
exit(-1)
# thresholding image using ostu method
ret, thresh = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
# applying closing operation using ellipse kernel
N = 3
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (N, N))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
# showing the result
cv2.imshow('thresh', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
<强>解释强>
在第一部分中,我使用imread
读取输入图像并检查图像是否正确打开!
image = cv2.imread('image4.png', cv2.IMREAD_GRAYSCALE) # reading image
if image is None:
print 'Can not find the image!'
exit(-1)
现在使用otsu
方法以thresh
方式作为参数,使用THRESH_BINARY_INV | THRESH_OTSU
方法对图像进行阈值处理。 otsu
方法基于优化问题,找到阈值的最佳值。因此,我通过给出0
的下限和255
的上限来提供阈值的可能值范围。
ret, thresh = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
使用Ellipse
内核完成关闭图像去除黑洞的操作。
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (N, N))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
<强>结果强>