java rectangle_Java Core.rectangle方法代码示例

这段Java代码展示了如何利用OpenCV库找到图像中的矩形。首先将图像转换为灰度,然后寻找轮廓,对每个轮廓进行逼近处理以找到近似四边形。通过检查轮廓的面积、凸度和角度,筛选出矩形,并用Core.rectangle方法画出边界框。
摘要由CSDN通过智能技术生成

import org.opencv.core.Core; //导入方法依赖的package包/类

public void findRectangle() {

Imgproc.cvtColor(originalImage, image, Imgproc.COLOR_BGR2GRAY);

setFilter();

this.rects.clear();

//Find Contours

Imgproc.findContours(image, contours, hierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE, new Point(0, 0));

//For conversion later on

MatOfPoint2f approxCurve = new MatOfPoint2f();

//For each contour found

for (int i = 0; i < contours.size(); i++) {

//Convert contours 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;

if (approxDistance > 1) {

//Find Polygons

Imgproc.approxPolyDP(contour2f, approxCurve, approxDistance, true);

//Convert back to MatOfPoint

MatOfPoint points = new MatOfPoint(approxCurve.toArray());

//Rectangle Checks - Points, area, convexity

if (points.total() == 4 && Math.abs(Imgproc.contourArea(points)) > 1000 && Imgproc.isContourConvex(points)) {

double cos = 0;

double mcos = 0;

for (int sc = 2; sc < 5; sc++) {

// TO-DO Figure a way to check angle

if (cos > mcos) {

mcos = cos;

}

}

if (mcos < 0.3) {

// Get bounding rect of contour

Rect rect = Imgproc.boundingRect(points);

// if (Math.abs(rect.height - rect.width) < 1000) {

System.out.println(i + "| x: " + rect.x + " + width("+rect.width+"), y: " + rect.y + "+ width("+rect.height+")");

rects.add(rect);

Core.rectangle(originalImage, rect.tl(), rect.br(), new Scalar(20, 20, 20), -1, 4, 0);

Imgproc.drawContours(originalImage, contours, i, new Scalar(0, 255, 0, .8), 2);

// Highgui.imwrite("detected_layers"+i+".png", originalImage);

// }

}

}

}

}

// Pass raw parameters

ImageDetection id = new ImageDetection();

HyperTextBuilder.rects = this.rects;

HyperTextBuilder.rect_height = this.HEIGHT;

HyperTextBuilder.rect_width = this.WIDTH;

id.setData(Utility.matToBufferedImage(originalImage));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值