针对分辨率万级以上的图片,无法直接打开,需切割后处理。
关键函数:
1.图片分割: Rect rect(x,y,width,height) 四个参数对应左上角x,y坐标,切割的宽和高
2.边界扩充:如果分割区域和图片区域大小有冲突,会报错,所以需要先扩充图片大小
void cv::copyMakeBorder ( InputArray src,
OutputArray dst,
int top,
int bottom,
int left,
int right,
int borderType,
const Scalar & value = Scalar()
) //分别对应上、下、左、右边界扩充像素数目,borderType扩充模式,可直接赋像素颜色
3.全黑图剔除:int cv::countNonZero ( InputArray src ) //返回矩阵中非0元素的个数,注意:输入为单通道图
4.三通道转为单通道:cvtColor(src,dst,CV_BGR2GRAY)
code:
// ImageSegmentation.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include "pch.h"
#include <iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
void PicCut() {
Mat pic_whole = imread("D:\\Documents\\jingwei_round1_train_20190619\\image_1.png"); //47161x50141
int cut_width = 1500, cut_height = 1500;
int rows = pic_whole.rows;
int cols = pic_whole.cols;
if (rows >= cols) {
int rem = rows % cut_width;
int dis = cut_width - rem;
int add_cols = rows - cols + dis;
int add_rows = dis;
copyMakeBorder(pic_whole, pic_whole, 0, add_rows, 0, add_cols, BORDER_CONSTANT, Scalar(0, 0, 0)); // top,bottom,left,right
}
else if (rows < cols) {
int rem = cols % cut_height;
int dis = cut_height - rem;
int add_rows = cols - rows + dis;
int add_cols = dis;
copyMakeBorder(pic_whole, pic_whole, 0, add_rows, 0, add_cols, BORDER_CONSTANT, Scalar(0, 0, 0));
}
//imshow("test", pic_whole);
//waitKey(1000);
for (int i = 0; i < pic_whole.cols;) {
for (int j = 0; j < pic_whole.rows;) {
Rect rect(i, j, cut_width, cut_height); //(x,y,width,heigth)
stringstream ss;
int name_i = i / cut_width;
int name_j = j / cut_height;
ss << "D:\\Documents\\jingwei_round1_train_20190619\\image_1_cut_pics\\pic_cuts_" << name_i << "_" << name_j << ".bmp";
//Mat pic_cuts = Mat(pic_whole, rect);
//Mat pic_copy = pic_cuts.clone();
//imshow("pic_copy",pic_copy);
Mat pic_cuts;
pic_whole(rect).copyTo(pic_cuts);
//imshow("pic_copy", pic_cuts);
//waitKey(1000);
Mat pic_gray;
cvtColor(pic_cuts, pic_gray, CV_BGR2GRAY); //转为灰度图
int num_zero = countNonZero(pic_gray); //统计矩阵中非0个数,排除全黑图像输出
if (num_zero != 0) {
imwrite(ss.str(), pic_cuts);
}
j += cut_height;
}
i += cut_width;
}
}
void main()
{
PicCut();
cout << "cut finished!" << endl;
system("pause");
}