1. 程式人生 > >OpenCV切割影象與合併影象

OpenCV切割影象與合併影象

首先是影象的分割

Mat spliteTest(Mat image)

{
long cols = image.cols;
long rows = image.rows;
Mat nullImage(Size(cols/2, rows), CV_LOAD_IMAGE_GRAYSCALE);  //取一半列數的大小
Mat subImage = image(Range::all(), Range(0,cols/2));   //將需要的影象讀取出來
subImage.copyTo(nullImage(Rect(0, 0, cols/2, rows)));   //複製進指定的Mat裡
return nullImage;
}


int main()
{
Mat image = imread("Red.bmp", CV_LOAD_IMAGE_GRAYSCALE);  

Mat nullImage = spliteTest(image);

imshow("nullImage", nullImage);  //分割後的影象

imshow("redImage", image);   //分割前的影象

}

其次是影象的合併

Mat spliteImageAndCon(Mat image)

{
long cols = image.cols;
long rows = image.rows;
Mat nullImage(Size(cols, rows), CV_LOAD_IMAGE_GRAYSCALE);
long con_cols = 0;
long con_rows = 0;
long cols_div = cols / width;
long cols_remain = cols % width;
for (long i = 0; i <cols_div; i++)
{
//取全部行,
Mat subImage = image(Range::all(), Range(i*width, (i + 1)*width)); //確定目標塊的位置
subImage.copyTo(nullImage(Rect(i*width, 0, width, rows)));  //確定合併的位置
}
Mat subImage = image(Range::all(), Range(cols_div*width, cols_div*width + cols_remain)); //合併剩下的部分即可
subImage.copyTo(nullImage(Rect(cols_div*width, 0, cols_remain, rows)));
return nullImage;

}

下面附上全部的測試程式碼:

#include<stdio.h>
#include<cuda_runtime.h>
#include<device_launch_parameters.h>
#include <iostream>
#include <opencv/highgui.h>
#include <string>
#include <math.h>




using namespace std;
using namespace cv;
const int width = 200; //從左往右多少列


Mat spliteImageAndCon(Mat image)
{
long cols = image.cols;
long rows = image.rows;
Mat nullImage(Size(cols, rows), CV_LOAD_IMAGE_GRAYSCALE);
long con_cols = 0;
long con_rows = 0;
long cols_div = cols / width;
long cols_remain = cols % width;
for (long i = 0; i <cols_div; i++)
{
//取全部行,
Mat subImage = image(Range::all(), Range(i*width, (i + 1)*width));
subImage.copyTo(nullImage(Rect(i*width, 0, width, rows)));
}
Mat subImage = image(Range::all(), Range(cols_div*width, cols_div*width + cols_remain));
subImage.copyTo(nullImage(Rect(cols_div*width, 0, cols_remain, rows)));
return nullImage;
}


Mat spliteTest(Mat image)
{
long cols = image.cols;
long rows = image.rows;
Mat nullImage(Size(cols/2, rows), CV_LOAD_IMAGE_GRAYSCALE);  //取一半列數的大小
Mat subImage = image(Range::all(), Range(0,cols/2));
subImage.copyTo(nullImage(Rect(0, 0, cols/2, rows)));
return nullImage;
}


int main()
{


Mat image = imread("Red.bmp", CV_LOAD_IMAGE_GRAYSCALE);

//Mat nullImage = spliteImageAndCon(image);
Mat nullImage = spliteTest(image);

imshow("nullImage", nullImage);
imshow("redImage", image);


//printf("%f  %f ", cols, rows);
////  rows 和 cols
//Mat subImage = image(Range(0,200),Range(0,100));
////imshow("subImage", subImage);
////imshow("image", image);


//////Size(cols,rows)
//Mat test(Size(600, 600), CV_LOAD_IMAGE_GRAYSCALE);
//////x軸和y軸 ,width和height
//subImage.copyTo(test(Rect(100, 0, 100, 200)));
//imshow("test", test);

waitKey(0);
return 0;
}