gpt4 book ai didi

java - 安卓 OpenCV : color detection giving weird result

转载 作者:行者123 更新时间:2023-11-28 01:44:44 26 4
gpt4 key购买 nike

我刚刚学会了如何从 OpenCV Java, Getting region of interest from image 中检测颜色.

最后,我想知道如何检测AA电池(有无黑胶)

我现在正在尝试检测图片中的电池,但电池并没有完全变黑,这反过来又给我带来了奇怪的结果:

enter image description here

我用黑色胶带盖住电池并再次尝试,结果似乎更好,但它在两个不同的部分检测电池:

enter image description here

代码:

private Bitmap findRoiBlack(Bitmap sourceBitmap) {
Bitmap roiBitmap = null;
Scalar green = new Scalar(0, 255, 0, 255);
Mat sourceMat = new Mat(sourceBitmap.getWidth(), sourceBitmap.getHeight(), CvType.CV_8UC3);
Utils.bitmapToMat(sourceBitmap, sourceMat);
Mat roiTmp = sourceMat.clone();

final Mat hsvMat = new Mat();
sourceMat.copyTo(hsvMat);

// convert mat to HSV format for Core.inRange()
Imgproc.cvtColor(hsvMat, hsvMat, Imgproc.COLOR_RGB2HSV);

Scalar lowerb = new Scalar(0, 0, 0); // lower color border for BLACK
Scalar upperb = new Scalar(180, 255, 30); // upper color border for BLACK

//Scalar lowerb = new Scalar(0, 0, 200); // lower color border for WHITE
//Scalar upperb = new Scalar(180, 255, 255); // upper color border for WHITE
Core.inRange(hsvMat, lowerb, upperb, roiTmp); // select only blue pixels

// find contours
List<MatOfPoint> contours = new ArrayList<>();
List<RotatedRect> boundingRects = new ArrayList<>();
Imgproc.findContours(roiTmp, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);

// find appropriate bounding rectangles
for (MatOfPoint contour : contours) {
MatOfPoint2f areaPoints = new MatOfPoint2f(contour.toArray());
RotatedRect boundingRect = Imgproc.minAreaRect(areaPoints);

double rectangleArea = boundingRect.size.area();

// test min ROI area in pixels
if (rectangleArea > 400) {
Point rotated_rect_points[] = new Point[4];
boundingRect.points(rotated_rect_points);

Rect rect = Imgproc.boundingRect(new MatOfPoint(rotated_rect_points));

// test vertical ROI orientation
if (rect.height > rect.width) {
Imgproc.rectangle(sourceMat, rect.tl(), rect.br(), green, 3);
}
}
}

roiBitmap = Bitmap.createBitmap(sourceMat.cols(), sourceMat.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(sourceMat, roiBitmap);
return roiBitmap;
}

最佳答案

最简单的方法 - 为电池添加颜色标记。另一种方法是为您安装的垂直 channel 设置坚实、清晰可辨的背景(甚至可能是背光——在这种情况下,您应该在白色/高亮度背景上找到黑色/低亮度物体)。如果不可能并且您有纯色背景 - 尝试“反转”方法:不要尝试寻找电池(因为它有多种颜色) - 寻找背景(因为它有一种纯色) - 可能具有“非背景”颜色的对象电池(还有额外的提示:电池是“垂直”矩形,比例为 1/4(AAA 电池直径为 10.5 毫米,长度为 44.6 毫米),它大约位于图像的垂直中心,上面有 Chrome 的高亮度元素顶部和底部等)。

关于java - 安卓 OpenCV : color detection giving weird result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45607575/

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