那如何可以实现用鼠标动态调整这个阈值?
时间: 2024-03-02 19:53:55 浏览: 18
可以使用 OpenCV 的鼠标事件来实现用鼠标动态调整阈值。具体实现方式如下:
```c++
#include <opencv2/opencv.hpp>
using namespace cv;
Mat img, gray, binary, dst;
int thresholdValue = 127; // 初始阈值
const int maxThresholdValue = 255;
void onTrackbar(int, void*)
{
threshold(gray, binary, thresholdValue, maxThresholdValue, THRESH_BINARY_INV); // 二值化
std::vector<std::vector<Point>> contours;
std::vector<Vec4i> hierarchy;
findContours(binary, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); // 查找轮廓
dst = img.clone();
for (size_t i = 0; i < contours.size(); i++)
{
double area = contourArea(contours[i]); // 计算轮廓面积
if (area > 100) // 如果轮廓面积过小,可能是噪声,忽略
{
drawContours(dst, contours, static_cast<int>(i), Scalar(0, 0, 255), 2); // 将轮廓圈出来
}
}
imshow("image", dst);
}
void onMouse(int event, int x, int y, int, void*)
{
if (event == EVENT_LBUTTONDOWN)
{
thresholdValue += 10;
if (thresholdValue > maxThresholdValue)
{
thresholdValue = maxThresholdValue;
}
setTrackbarPos("threshold", "image", thresholdValue);
onTrackbar(0, 0);
}
else if (event == EVENT_RBUTTONDOWN)
{
thresholdValue -= 10;
if (thresholdValue < 0)
{
thresholdValue = 0;
}
setTrackbarPos("threshold", "image", thresholdValue);
onTrackbar(0, 0);
}
}
int main()
{
img = imread("image.jpg");
cvtColor(img, gray, COLOR_BGR2GRAY);
namedWindow("image", WINDOW_NORMAL);
createTrackbar("threshold", "image", &thresholdValue, maxThresholdValue, onTrackbar); // 创建阈值滑动条
setMouseCallback("image", onMouse); // 设置鼠标事件回调函数
onTrackbar(0, 0);
waitKey(0);
return 0;
}
```
在上述代码中,首先读入图像,然后将图像转为灰度图像,创建阈值滑动条,设置鼠标事件回调函数。当鼠标左键按下时,阈值增加 10,当鼠标右键按下时,阈值减少 10,然后调用 onTrackbar 函数进行二值化和轮廓查找,最后将轮廓圈出来并显示图像。需要注意的是,通过调整轮廓面积阈值可以控制是否将小的黑色和灰色区域忽略。