#include "stdafx.h"
#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
struct MyPoint
{
float x;
float y;
MyPoint(float w, float h) : x(w), y(h) {}
};
struct Mydata
{
Mat img;
vector<MyPoint> *out;
Mydata(Mat image, vector<MyPoint> &out0) : img(image), out(&out0) {}
};
void onMouse(int event, int x, int y, int flags, void* param)
{
Mydata data = *((Mydata*)(param));
switch (event)
{
case EVENT_LBUTTONDOWN:
if (static_cast<int>((data.img).channels()) == 1)
{
cout << "at(" << x << "," << y << ")value is:" << static_cast<int>((data.img).at<uchar>(x, y)) << endl;
data.out->push_back(MyPoint(x, y));
}
else if (static_cast<int>((data.img).channels() == 3))
{
cout << "at (" << x << ", " << y << ")" << endl;
data.out->push_back(MyPoint(x, y));
}
circle(data.img, Point(x, y), 1, Scalar(255, 0, 0), -1);
putText(data.img, to_string(data.out->size()-1) + ": " + to_string(x) + "," + to_string(y), Point(x, y), FONT_HERSHEY_PLAIN, 1.0, Scalar(255, 255, 0), 1);
imshow("image", (data.img));
}
}
struct compare_xy
{
vector<MyPoint> result;
compare_xy(vector<MyPoint> data): result(data) {};
bool operator ()(const int& i, const int& j) const
{
return (fabs(result[i].y - result[j].y)<1e-3 ? result[i].x < result[j].x : result[i].y < result[j].y);
}
};
int main()
{
Mat img = imread("C:\\Desktop\\2.bmp");
imshow("image", img);
Mat img2 = img.clone();
vector<MyPoint> result;
Mydata data(img, result);
setMouseCallback("image", onMouse, &data);
waitKey(0);
imshow("image1", data.img);
vector<int> index(result.size(), 0);
for (int i = 0; i != index.size(); i++)
{
index[i] = i;
}
std::sort(index.begin(), index.end(), compare_xy(result));
for (int i = 0; i < index.size(); i++)
{
circle(img2, Point((int)result[index[i]].x, (int)result[index[i]].y), 1, Scalar(255, 0, 0), -1);
putText(img2, to_string(i) + ": " + to_string((int)result[index[i]].x) + "," + to_string((int)result[index[i]].y), Point((int)result[index[i]].x, (int)result[index[i]].y), FONT_HERSHEY_PLAIN, 1.0, Scalar(255, 255, 0), 1);
}
imshow("image2", img2);
waitKey(0);
system("pause");
return 0;
}
python类似
import cv2
def on_EVENT_LBUTTONDOWN(event, x, y, flags, param):
img_src = param[0]
if event == cv2.EVENT_LBUTTONDOWN:
xy = "%d,%d" % (x, y)
cv2.circle(img_src, (x, y), 1, (255, 0, 0), thickness = -1)
cv2.putText(img_src, xy, (x, y), cv2.FONT_HERSHEY_PLAIN,
1.0, (0,0,0), thickness = 1)
cv2.imshow("image", img_src)
img = cv2.imread('./test/num_1.jpeg')
a = [0,0]
cv2.namedWindow("image")
cv2.setMouseCallback("image", on_EVENT_LBUTTONDOWN, [img,a])
while(1):
if cv2.waitKey(0)&0xFF==27:
break
cv2.destroyAllWindows()