一、前言
在进行图像处理时,经常碰到要从一张完整的图像中截取某一部分图像保存成另一个图像,同时知道该图像是从原图像的哪里截取的。因此,这里提供该工具代码。
二、实现
以下代码实现用鼠标从输入图像截取图像,并以截取图像在输入图像中的矩形左上角和右下角的坐标命名。代码如下:
////////////////////////////////////
/*
* author: holamirai(@163.com)
*/
///////////////////////////////
#include"iostream"
#include"opencv2/opencv.hpp"
using namespace std;
void on_mouse(int Event,int x,int y,int flags,void* param );
IplImage *src = cvLoadImage("sg.jpg",1);
CvPoint point1,point2;
CvFont font = cvFont(2, 1);
int main(int argc, char* argv[])
{
if (argc != 2)
{
printf("please input the source image`s name.\n");
return 0;
}
cvNamedWindow("src",CV_WINDOW_AUTOSIZE);
src = cvLoadImage(argv[1], CV_LOAD_IMAGE_UNCHANGED);
if (!src)
{
printf("ERROR:\n can`t load image.\n");
return 0;
}
cvShowImage("src",src);
cvSetMouseCallback("src",on_mouse,NULL);
while (cvWaitKey(10) != 'q') { }
return 0;
}
void on_mouse(int Event,int x,int y,int flags,void* param )
{
IplImage *copy = cvCloneImage(src);
bool roi = false;
if (Event == CV_EVENT_MOUSEMOVE)
{
char pt[15];
sprintf_s(pt, "(%d,%d)", x, y);
cvPutText(copy,pt, cvPoint(x, y), &font, CV_RGB(255, 0, 0));
cvShowImage("src", copy);
}
if (Event == CV_EVENT_LBUTTONDOWN)
{
point1 = cvPoint(x, y);
char pt[15];
sprintf_s(pt, "(%d,%d)", x, y);
cvPutText(copy, pt, cvPoint(x, y), &font, CV_RGB(255, 0, 0));
cvShowImage("src", copy);
}
if (Event == CV_EVENT_MOUSEMOVE && flags == CV_EVENT_FLAG_LBUTTON)
{
char pt[15],point1_str[15];
sprintf_s(pt, "(%d,%d)", x, y);
sprintf_s(point1_str, "(%d,%d)", point1.x, point1.y);
cvPutText(copy, point1_str, point1, &font, CV_RGB(255, 0, 0));
cvPutText(copy, pt, cvPoint(x, y), &font, CV_RGB(255, 0, 0));
cvRectangle(copy, point1, cvPoint(x, y),CV_RGB(0,255,0));
cvShowImage("src", copy);
}
if(Event == CV_EVENT_LBUTTONUP)
{
point2 = cvPoint(x,y);
cvRectangle(copy, point1, point2, CV_RGB(0, 255, 0));
roi = true;
}
if(roi)
{
// 以 ROI 区域坐标命名
// 不允许从左到右,从上到下截图
if (point2.x <= point1.x || point2.y <= point1.y)
{
printf("the second point is not big than the first point.\n");
return;
}
char filename[40];
sprintf(filename,"%d,%d--%d,%d.jpg",point1.x, point1.y, point2.x, point2.y);
IplImage *dst = cvCreateImage(cvSize(point2.y - point1.y , point2.x - point1.x),src->depth,src->nChannels);
cvSetImageROI(src,cvRect(point1.x,point1.y,(point2.y - point1.y) , (point2.x - point1.x) ) );
cvCopy(src,dst);
cvResetImageROI(src);
cvNamedWindow("dst",CV_WINDOW_AUTOSIZE);
cvShowImage("dst",dst);
cvSaveImage(filename,dst);
}
}
运行
运行结果如下图所示,在当前目录下将生产一个92,89–288,270.jpg文件:
转载请注明作者和出处:http://blog.csdn.net/holamirai,未经允许请勿用于商业用途。