#include <opencv2/opencv.hpp>
#include <iostream>
// 全局变量,用于存储图像
cv::Mat image;
// 鼠标回调函数
void onMouse(int event, int x, int y, int flags, void* userdata) {
if (event == cv::EVENT_MOUSEMOVE) {
// 获取鼠标位置的像素值
cv::Vec3b pixel = image.at<cv::Vec3b>(y, x);
// 输出像素值
std::cout << "鼠标位置 (" << x << ", " << y << ") 的像素值: ("
<< static_cast<int>(pixel[0]) << ", "
<< static_cast<int>(pixel[1]) << ", "
<< static_cast<int>(pixel[2]) << ")" << std::endl;
}
}
int main() {
// 读取图像
image = cv::imread("path_to_your_image.jpg");
if (image.empty()) {
std::cout << "无法读取图像!" << std::endl;
return -1;
}
// 创建窗口
cv::namedWindow("Image", cv::WINDOW_NORMAL);
// 设置鼠标回调函数
cv::setMouseCallback("Image", onMouse, NULL);
// 显示图像
cv::imshow("Image", image);
// 等待按键
cv::waitKey(0);
return 0;
}
C++代码显示图片中鼠标位置的像素的像素值
最新推荐文章于 2025-08-12 21:47:50 发布