C++ OpenCV 将黑点框出来

本文介绍了一种图像处理技术,通过二值化、轮廓检测等步骤,实现从原始图像中精确地分离出目标物体。文章详细展示了使用OpenCV库进行图像预处理、灰度转换、阈值设定、降噪、腐蚀操作及轮廓检测的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.效果图如下:

2.代码如下:

做了测试,发现将图片二值化是最最重要的,一定要,不然抠出来的黑点不精确

// 	// 二值化图,主要将灰色部分转成白色,使内容为黑色
 	threshold(image, image, 165, 255, THRESH_BINARY);
#include "BoundingRect.h"
//#include "stdafx.h"
#include  <iostream>
#include  <stdio.h>
#include <opencv2/opencv.hpp>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2\imgproc\types_c.h>

using namespace cv;
using namespace std;

BoundingRect::BoundingRect()
{
	// Declares a vector of vectors for store the contours
	Mat originalimage;
	Mat image;

	// Loads the original image
	originalimage = imread("black.jpg");
	imshow("originalimage",originalimage);
	// Converts original image to an 8UC1 image
	cvtColor(originalimage, image, CV_BGR2GRAY);
// 	imshow("cvtColor", image);
// 	// 高斯模糊,主要用于降噪
 //	GaussianBlur(image, image, Size(3, 3), 0);
// 	imshow("GaussianBlur图", image);
// 	// 二值化图,主要将灰色部分转成白色,使内容为黑色
 	threshold(image, image, 165, 255, THRESH_BINARY);
// 	imshow("threshold图", image);
// 	// 中值滤波,同样用于降噪
// 	medianBlur(image, image, 3);
// 	imshow("medianBlur图", image);
// 	// 腐蚀操作,主要将内容部分向高亮部分腐蚀,使得内容连接,方便最终区域选取
// 	erode(image, image, Mat(9, 9, CV_8U));
	// Finds contours
	vector<vector<Point> > v;
	vector<Vec4i> hierarchy;
	Mat result;
	Rect rect;
	findContours(image, v, hierarchy, RETR_CCOMP, CV_CHAIN_APPROX_NONE);
	for (int i = 0; i < hierarchy.size(); i++)
	{
		rect = boundingRect(v.at(i));
	// 画最小的圆,贴着黑色
	drawContours(originalimage, v, i, Scalar(0, 0, 255), 1, 8, hierarchy);
	// 画矩形包围圆
	rectangle(originalimage, rect, Scalar(255, 0, 0));
	}
	namedWindow("Ejemplo");
	imshow("Ejemplo", originalimage);
	waitKey(60000);
}


BoundingRect::~BoundingRect()
{
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值