图像切割转载自:https://blog.csdn.net/ranghanqiao5058/article/details/79237180
图像拼接转载自:https://www.jb51.net/article/154636.htm
亲测有用!
图像切割:vs2015运行
#include <opencv2/core/core.hpp>
#include "opencv2/opencv.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <opencv2/imgproc/imgproc.hpp>
#include <vector>
using namespace std;
using namespace cv;
using std::vector;
void main()
{ //设置分割后图像存储路径
string outpath = "E:\\college-to-graduate\\image\\splitresult\\";
Mat img = imread("E:\\college-to-graduate\\image\\test image\\0013.jpg"); //将图像放在项目工程里,使用imread函数读取
int t = 0;
int m = img.cols / 128; //m*n是切割后子图像的个数
int n = img.rows / 128;
vector<Mat> ceil_img; //迭代器ceil_img存储子图像
vector<int> name; //迭代器name存储子图像的名字,从0到m*n-1
for (t; t < m*n; t++)
name.push_back(t);
Mat image_cut, roi_img, tim_img;
for (int j = 0; j <n; j++)
{
for (int i = 0; i < m; i++)
{
Rect rect(i * 128, j * 128, 128, 128);
image_cut = Mat(img, rect);
roi_img = image_cut.clone();
ceil_img.push_back(roi_img);
}
}
for (int t = 0; t < m*n; t++)
imwrite(outpath + to_string(name[t]) + ".jpg", ceil_img[t]);
}
图像拼接:Pycharm
import PIL.Image as Image
import os
IMAGES_PATH = 'E:\\college-to-graduate\\image\\splitresult\\' # 图片集地址
IMAGES_FORMAT = ['.jpg', '.JPG'] # 图片格式
IMAGE_SIZE = 128 # 每张小图片的大小
IMAGE_ROW = 2 # 图片间隔,也就是合并成一张图后,一共有几行
IMAGE_COLUMN = 2 # 图片间隔,也就是合并成一张图后,一共有几列
IMAGE_SAVE_PATH = 'E:\\college-to-graduate\\image\\new\\final.jpg' # 图片转换后的地址
# 获取图片集地址下的所有图片名称
image_names = [name for name in os.listdir(IMAGES_PATH) for item in IMAGES_FORMAT if
os.path.splitext(name)[1] == item]
# 简单的对于参数的设定和实际图片集的大小进行数量判断
if len(image_names) != IMAGE_ROW * IMAGE_COLUMN:
raise ValueError("合成图片的参数和要求的数量不能匹配!")
# 定义图像拼接函数
def image_compose():
to_image = Image.new('RGB', (IMAGE_COLUMN * IMAGE_SIZE, IMAGE_ROW * IMAGE_SIZE)) # 创建一个新图
# 循环遍历,把每张图片按顺序粘贴到对应位置上
for y in range(1, IMAGE_ROW + 1):
for x in range(1, IMAGE_COLUMN + 1):
from_image = Image.open(IMAGES_PATH + image_names[IMAGE_COLUMN * (y - 1) + x - 1]).resize(
(IMAGE_SIZE, IMAGE_SIZE), Image.ANTIALIAS)
to_image.paste(from_image, ((x - 1) * IMAGE_SIZE, (y - 1) * IMAGE_SIZE))
return to_image.save(IMAGE_SAVE_PATH) # 保存新图
image_compose() # 调用函数