1.鼠标手动截取矩形图像,并保存文件夹
定义一个鼠标回调函数(鼠标的动作),在主函数中定义响应setMouseCallback("capframe", onMouseRectPicking, 0),并批量保存图片
#include
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace std;
using namespace cv;
Mat img;//原始图像
Mat tmp,roi;
int ROI_count;
bool select_flag = false;
Rect m_select;
Point origin;
void onMouseRectPicking(int event, int x, int y, int, void*)
{
if (select_flag)
{
m_select.x = origin.x;//不一定要等鼠标弹起才计算矩形框,而应该在鼠标按下开始到弹起这段时间实时计算所选矩形框
m_select.y = origin.y;
m_select.width = 20;//矩形宽度和高度
m_select.height = 20;
}
if (event == CV_EVENT_LBUTTONDOWN)
{
select_flag = true; //鼠标按下的标志赋真值
origin = Point(x, y); //保存下来单击捕捉到的点
m_select = Rect(x, y, 0, 0); //这里一定要初始化,宽和高为(0,0)是因为在opencv中Rect矩形框类内的点是包含左上角那个点的,但是不含右下角那个点
}
else if (event == CV_EVENT_LBUTTONUP)
{
select_flag = false;
ROI_count++;
}
}
int main(int argc, char* argv[] )
{
img=imread("D:/picture20/8.jpg");
bool isRect = true;
namedWindow("capframe", CV_WINDOW_AUTOSIZE);
setMouseCallback("capframe", onMouseRectPicking, 0);
char pic_name[40];
ROI_count=0;
while(1)
{
img.copyTo(tmp);
rectangle(tmp, m_select, Scalar(255,0,0), 0.1); // 画矩形框
imshow("capframe",tmp);
if(isRect){
if((m_select.x!=0)&&(m_select.y!=0)&&(m_select.width!=0)&&(m_select.height!=0))
{
sprintf(pic_name,"D:/weed/%d.jpg",ROI_count);
Mat ROI = img(m_select);
imshow("ROI",ROI);
imwrite(pic_name,ROI);
}
}
char key = waitKey(30);
if(key == 27)
break;
}
waitKey(0);
return 0;
}
2. 合并保存后的小图片
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace std;
using namespace cv;
void main()
{
vectorinput(100);//定义一个Mat型的input数组
char pic_name[40];
for (int i = 0; i < 100;i++)
{
sprintf(pic_name,"D:/beijing/%d.jpg",i+1);
input[i] = imread(pic_name);
}
vectortemp(100);
Mat finalpic;
int perwidth=input[0].cols;
int perheight=input[0].rows;
Size bigsize(perwidth * 10, perheight*10);//合并后图片size
finalpic.create(bigsize, CV_MAKETYPE(input[0].depth(), 3));//创建合并后图片
finalpic = Scalar::all(0);
for (int i = 0; i < 10;i++)
for (int j = 0; j < 10;j++)
{
temp[i*10+j] = finalpic(Rect(j*perwidth, i*perheight, perwidth, perheight));
input[i*10+j].copyTo(temp[i*10+j]); //copy图片到对应位置
}
imshow("merge1", finalpic);
imwrite("merge1.jpg", finalpic);
waitKey(0);
}