gpt4 book ai didi

java - 检测图像中的矩形会产生不需要的结果(opencv,java)

转载 作者:搜寻专家 更新时间:2023-11-01 02:25:52 26 4
gpt4 key购买 nike

我有这张图片,我已经对其进行了阈值处理以将其转换为二进制图像和黑白图像。见下图:

Example 1

我想用一个字母提取每个盒子,这是通过以下代码完成的:

 List<MatOfPoint> contours = new ArrayList<MatOfPoint>();  
Imgproc.findContours(destination3, contours, new Mat(), Imgproc.RETR_LIST,Imgproc.CHAIN_APPROX_SIMPLE);

MatOfPoint2f approxCurve = new MatOfPoint2f();
int x = 1;
//For each contour found
for (int i=0; i<contours.size(); i++)
{
//Convert contours(i) from MatOfPoint to MatOfPoint2f
MatOfPoint2f contour2f = new MatOfPoint2f( contours.get(i).toArray() );
//Processing on mMOP2f1 which is in type MatOfPoint2f
double approxDistance = Imgproc.arcLength(contour2f, true)*0.02;
Imgproc.approxPolyDP(contour2f, approxCurve, approxDistance, true);

//Convert back to MatOfPoint
MatOfPoint points = new MatOfPoint( approxCurve.toArray() );

// Get bounding rect of contour
Rect rect = Imgproc.boundingRect(points);
if(rect.height > 50 && rect.height < 100) {
// draw enclosing rectangle (all same color, but you could use variable i to make them unique)
//Core.rectangle(destination, new Point(rect.x,rect.y), new Point(rect.x+rect.width,rect.y+rect.height), new Scalar(255, 0, 255), 3);
Rect roi = new Rect(rect.x, rect.y, rect.width, rect.height);
Mat cropped = new Mat(destination3, roi);
Highgui.imwrite("letter"+x+".jpg", cropped);
x++;
}
}

但是提取出来的字母是全黑的,看起来就像是填充了白色的字母一样,如下图所示。我该如何解决?我的代码有什么问题?

current output

最佳答案

来自 findContours() 的文档: (强调我的)

Note: Source image is modified by this function. Also, the function does not take into account 1-pixel border of the image (it's filled with 0's and used for neighbor analysis in the algorithm), therefore the contours touching the image border will be clipped.

您看到的奇怪图像是 findContours()destination3 进行修改的结果。通过调用 clone() 将数据的深拷贝传递给 findContours(),您应该能够获得正确的结果。您调用 findContours() 的行将如下所示:

Imgproc.findContours(destination3.clone(), contours, new Mat(), Imgproc.RETR_LIST,Imgproc.CHAIN_APPROX_SIMPLE);
// ^^ Vive la difference!

关于java - 检测图像中的矩形会产生不需要的结果(opencv,java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23016194/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com