《learning opencv》ex8-2 解決方案
有如下任務(wù):
- 讀取并顯示一張圖像怜奖,當鼠標左鍵點擊圖片時稳捆,在圖片上顯示當前位置的像素點
- 鼠標右鍵點擊圖像時榴嗅,記錄鼠標所點位置的坐標和對應(yīng)像素點,并保存在文本文件中
針對以上任務(wù)傀履,利用C++實現(xiàn)的代碼如下所示:
#include<iostream>
#include<opencv2/opencv.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<sstream>
#include<fstream>
using namespace cv;
/*
2. create a program that reads in and displays an image.When the user's mouse clicks on the image,read in the corresponding
pixel values(blue,green,red) and write those values as text to the screen at the mouse location
a. For the program of Ex2,display the mouse coordinates of the individual image when clicking anywhere within the three-image
display.
*/
void HandlerMouseEvent(int event, int x, int y, int flags,void* p)
{
Mat img = (*static_cast<Mat*>(p)); //獲取當前圖像
Mat img_clone = img.clone();
std::string filename = "coord_pixel.txt"; //文件名
std::fstream out_file;
if (event == EVENT_LBUTTONDOWN) //得到圖像像素值
{
int blue = img_clone.at<Vec3b>(y, x)[0];
int green = img_clone.at<Vec3b>(y, x)[1];
int red = img_clone.at<Vec3b>(y, x)[2];
std::stringstream s_str; //格式化字符串 像素值
s_str << "(" << blue << "," << green << "," << red << ")";
std::string showText = s_str.str();
putText(img_clone, showText, Point(x, y), 0, 1.0, Scalar(0, 0, 255), 1, 8, 0);
imshow("ex2", img_clone);
}
else if (event == EVENT_RBUTTONDOWN) //新加入坐標和像素值保存至map中
{
int blue = img_clone.at<Vec3b>(y, x)[0];
int green = img_clone.at<Vec3b>(y, x)[1];
int red = img_clone.at<Vec3b>(y, x)[2];
std::stringstream s_str; //格式化字符串 像素值
s_str << "(" << blue << "," << green << "," << red << ")";
std::string showText = s_str.str();
std::stringstream s_coordinate; //格式化字符串缆巧,坐標
s_coordinate << "(" << x << "," << y << ")";
std::string str_coordinate = s_coordinate.str();
out_file.open(filename, std::fstream::app | std::fstream::out);
if (!out_file)
{
std::cerr << "文件打開失敗" << std::endl;
exit(0);
}
out_file << str_coordinate << ": " << showText << std::endl;
}
}
int main()
{
//加載一副圖像布持,并創(chuàng)建一個窗口
Mat img = imread("ex2.jpg");
namedWindow("ex2");
setMouseCallback("ex2", HandlerMouseEvent, &img);
HandlerMouseEvent(0, 0,0,0,&img);
imshow("ex2", img);
waitKey();
return 0;
}
實現(xiàn)效果圖如下:
記錄的坐標點效果: