在下面的代码中,我尝试预处理图像,并使用findContours
将每个字符提取为图像。在
Mat inImage = Imgcodecs.imread("CaptureMultiLines.jpg", Imgcodecs.CV_LOAD_IMAGE_COLOR);
Mat destination = new Mat(inImage.rows(), inImage.cols(), inImage.type());
ImageProcUtils.showImage("initial", inImage);
// convert to grayscale
Imgproc.cvtColor(inImage, destination, Imgproc.COLOR_BGR2GRAY);
ImageProcUtils.showImage("grayscaleimage", destination);
Mat binImg = new Mat(inImage.rows(), inImage.cols(), inImage.type());
// binarize the image
double thresh = Imgproc.threshold(destination, binImg, 127, 255, Imgproc.THRESH_BINARY_INV);
ImageProcUtils.showImage("Binary Image", binImg);
// dilation
Mat dilMat = new Mat(inImage.rows(), inImage.cols(), inImage.type());
Mat kernel = Mat.ones(2,1, CvType.CV_8U); // able to extract character
Imgproc.dilate(binImg, dilMat, kernel);
ImageProcUtils.showImage("Dilated Image", dilMat);
// find contours
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();
Imgproc.findContours(dilMat.clone(), contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
System.out.println();
ImageProcUtils.showImage("Contours", dilMat);
CharacterSegmentation inst = new CharacterSegmentation();
for (int j = 0; j < contours.size(); j++) {
Imgproc.drawContours(dilMat, contours, j, new Scalar(255,0,0));
}
Mat drawing = Mat.zeros( dilMat.size(), CvType.CV_8UC3 );
Point centroid = inst.massCenterMatOfPoint2f(submat);
for( int i = 0; i< contours.size(); i++ )
{
Rect box = Imgproc.boundingRect(contours.get(i));
Mat submat = dilMat.submat(box);
int[] flattenedArr = inst.flattenAnImage(submat);
ImageProcUtils.printArray("Contour.."+i, flattenedArr);
Imgcodecs.imwrite("character-Line"+ i +".jpg", submat);
}
下面是我正在使用的图像
我可以成功地提取字符,但不能保持顺序。我想根据每个字符在图像中的出现来命名它。例如,F
应该命名为Character-0-0
,这意味着它出现在第一行和第一列。类似地,B
为Character-2-7
我知道有很多类似的线索
Trying to segment characters and save it in order to image files. But contours are being drawn in a different order?OpenCV findContours are not in orderHow can I sort contours from left to right and top to bottom?
但是,我还是不知道如何实现这一点。在
我也尝试了下面的Python代码,但还是没有成功
^{pr2}$
试试这个:
这是我用来做同样事情的代码,但是使用python:
希望这会有帮助。这将根据字符的x和y坐标对轮廓进行排序。在
相关问题 更多 >
编程相关推荐