对于imshow,如果单独显示一幅图片,如imshow("img",路飞.jpg)。这样是可以的,系统会自己默认创建一个img窗口。
但是如果在没有事先 建立窗口namedWindow("img", 1),同时还在img上有一些操做,那么这时候系统是不能显示这个窗口的,必须要显式的建立窗口。
比如下面这个,在int main()中,只是 namedWindow("草帽", 1),进而//imshow("草帽", img);
而没有namedWindow("img", 1),进而//imshow("img", img),那么在运行程序的时候,在出来"草帽"窗口的时候,对其进行截屏操做不会有任何响应。
#include "stdafx.h"
#include"opencv2/opencv.hpp"
#include"opencv2/highgui/highgui.hpp"
#include"iostream"
#include<stdio.h>
using namespace std;
using namespace cv;
//Mat img, dst, img1, img2;
Mat org, dst, img, tmp;
void om_mouse(int event, int x, int y, int flags, void* ustc)
{
char zifu[256];
static Point pre_=(-1, -1);
static Point cur_=(-1, -1);
if (event == CV_EVENT_LBUTTONDOWN)//左键按下
{
org.copyTo(img);
pre_ = Point(x, y);
sprintf_s(zifu, "(%d,%d)", x, y);
circle(img, pre_, 5, Scalar(0, 0, 255), 5);
putText(img, zifu, pre_, CV_FONT_HERSHEY_COMPLEX, 0.5, Scalar(255, 0, 0), 1, 8);
imshow("img", img);
waitKey(0);
}
//else if (event == CV_EVENT_MOUSEMOVE&&!(flags &CV_EVENT_FLAG_LBUTTON))//左键没按,只是鼠标移动
//{
// img.copyTo(tmp);
// cur_ = Point(x, y);
// sprintf_s(zifu, "(%d,%d)", x, y);
// circle(tmp, cur_, 5, Scalar(0, 0, 255), 1, 8);
// putText(tmp, zifu, cur_, CV_FONT_HERSHEY_COMPLEX, 0.5, Scalar(0, 0, 255), 1, 8);
// imshow("img", tmp);
//}
else if (event == CV_EVENT_MOUSEMOVE && (flags&CV_EVENT_FLAG_LBUTTON))//按下左键,鼠标动
{
img.copyTo(tmp);
cur_ = Point(x, y);
sprintf_s(zifu, "(%d,%d)", x, y);
putText(tmp, zifu, cur_, CV_FONT_HERSHEY_COMPLEX, 0.5, Scalar(0, 0, 255), 1, 8);
rectangle(tmp, pre_, cur_, Scalar(0, 0, 255), 1, 8);
imshow("img", tmp);
}
else if (event == CV_EVENT_LBUTTONUP)//左键放开
{
org.copyTo(img);
cur_ = Point(x, y);
circle(img, cur_, 5, Scalar(0, 0, 255), 1, 8);
rectangle(img, pre_, cur_, Scalar(0, 0, 255), 1, 8);
imshow("img", img);
//保存截图
int width = abs(pre_.x - cur_.x);
int height = abs(pre_.y - cur_.y);
if (width == 0 || height == 0)
{
cout << "无法截取";
}
dst = org(Rect(min(pre_.x, cur_.x), min(pre_.y, cur_.y), width, height));
imshow("dst", dst);
waitKey(0);
}
}
int main()
{
org = imread("C:\\Users\\one piece\\Desktop\\路飞草帽.jpg");
org.copyTo(img);
//namedWindow("草帽", 1);
namedWindow("img", 1);
setMouseCallback("img", om_mouse,0);//调用回调函数
//imshow("草帽", img);
imshow("img1", img);
waitKey(0);
imwrite("C:\\Users\\one piece\\Desktop\\路飞草帽11.jpg", dst);
}