【原创】opencv 分割重组图片

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/ocl/ocl.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <cv.h>
#include <cxcore.h>

#include <stdlib.h>
#include <string.h>

using namespace cv;

static Scalar GRID_EMPTY_COLOR = Scalar(0x33, 0x33, 0x33, 0xFF);

int main( int argc, char** argv )
{
//read image
Mat img;
string filename="lena.jpg";
img=imread(filename,CV_LOAD_IMAGE_COLOR);

Size size(img.cols, img.rows);

Mat mRgba15;
mRgba15.create(size, CV_MAKETYPE(img.depth(), 3));

Mat cells[16];
Mat mCells15[16];
int rows = img.rows;
int cols = img.cols;

rows = rows - rows%4;
cols = cols - cols%4;

for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
int k = i * 4 + j;
Range rowRan(i * img.rows / 4, (i + 1) * img.rows / 4);
Range colRan(j * img.cols/ 4, (j + 1) * img.cols / 4);
cells[k] = img(rowRan, colRan);
}
}


for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
int k = i * 4 + j;
Rect rect = Rect(j * img.cols/ 4, i * img.rows / 4, img.cols / 4, img.rows / 4);
mCells15[k] = mRgba15(rect);
}
}

rows = rows - rows%4;
cols = cols - cols%4;
for (int i = 0; i < 16; i++)
{
int idx = 15-i;
if (idx == 15)
mCells15[i].setTo(GRID_EMPTY_COLOR);
else {
cells[idx].copyTo(mCells15[i]);
}
}


for (int i = 0; i < 16; i++)
cells[i].release();

for (int i = 1; i < 4; i++) {
line(mRgba15, Point(0, i * rows / 4), Point(cols, i * rows / 4), Scalar(0, 255, 0, 255), 3);
line(mRgba15, Point(i * cols / 4, 0), Point(i * cols / 4, rows), Scalar(0, 255, 0, 255), 3);
}

imshow( "puzzle", mRgba15 );
cvWaitKey(0); //等待按键


return -1;
}

 

posted @ 2013-10-11 16:24  大山爸  阅读(1189)  评论(0)    收藏  举报