cru*_*ian 2 java opencv computer-vision
我是OpenCV的新手,我想开展物体检测以帮助我的FRC机器人团队.我正在尝试使用HSV滤镜和HoughCircles在网络摄像头图像中找到一个网球并在其周围画一个圆圈.这是我的代码:
Mat currentFrame = new Mat();
Mat hsv = new Mat();
Mat threshImage = new Mat();
Mat circles = new Mat();
while (true) {
camera.read(currentFrame);
Imgproc.resize(currentFrame, currentFrame, new Size(WIDTH, HEIGHT));
Imgproc.cvtColor(currentFrame, hsv, Imgproc.COLOR_RGB2HSV);
hsvWindow.showImage(hsv);
Core.inRange(hsv, new Scalar(50, 100, 0), new Scalar(95, 255, 255), threshImage);
threshWindow.showImage(threshImage);
Imgproc.HoughCircles(threshImage, circles, Imgproc.CV_HOUGH_GRADIENT, 2, 100, 100, 100, 0, 500);
for (int i = 0; i < circles.cols(); i++) {
double[] vCircle = circles.get(0, i);
Point pt = new Point(Math.round(vCircle[0]), Math.round(vCircle[1]));
int radius = (int)Math.round(vCircle[2]);
Core.circle(currentFrame, pt, radius, new Scalar(255, 0, 0), 2);
}
drawWindow.showImage(currentFrame);
}
Run Code Online (Sandbox Code Playgroud)
原始图像,hsv图像和过滤后的图像都在此相册中:http://imgur.com/a/hO8vs
当我在这里使用参数运行HoughCircles时,它会在钢琴凳和玩具兔上找到圆圈,而不是网球,它看起来像一个大的白色圆圈.
我修好了它!在摆弄了HoughCircles的参数并模糊和阈值化二进制图像之后,它发现它是可靠的,但圆圈是抖动和不一致的.所以,我用findContours替换了HoughCircles,循环遍历轮廓寻找最大的轮廓,并使用了minEnclosingCircle.这是现在的代码:
Mat currentFrame = new Mat(), hsv = new Mat(), threshImage = new Mat();
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
while (true) {
camera.read(currentFrame);
Imgproc.resize(currentFrame, currentFrame, new Size(WIDTH, HEIGHT));
Imgproc.cvtColor(currentFrame, hsv, Imgproc.COLOR_RGB2HSV);
hsvWindow.showImage(hsv);
Core.inRange(hsv, new Scalar(50, 100, 50), new Scalar(95, 255, 255), threshImage);
Imgproc.blur(threshImage, threshImage, new Size(10, 10));
Imgproc.threshold(threshImage, threshImage, 150, 255, Imgproc.THRESH_BINARY);
threshWindow.showImage(threshImage);
Imgproc.findContours(threshImage, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
double maxArea = 0;
float[] radius = new float[1];
Point center = new Point();
for (int i = 0; i < contours.size(); i++) {
MatOfPoint c = contours.get(i);
if (Imgproc.contourArea(c) > maxArea) {
MatOfPoint2f c2f = new MatOfPoint2f(c.toArray());
Imgproc.minEnclosingCircle(c2f, center, radius);
}
}
Core.circle(currentFrame, center, (int)radius[0], new Scalar(255, 0, 0), 2);
drawWindow.showImage(currentFrame);
}
Run Code Online (Sandbox Code Playgroud)
我知道这对于那些希望专门使用HoughCircles的人来说可能不是特别有用,但它证明了模糊二进制图像的能力.如果您在许多事物中寻找一个圆圈,您可以查找轮廓并将轮廓区域与其封闭圆圈的区域进行比较.