OpenCV切割大图(边界扩充,全黑图剔除)

针对分辨率万级以上的图片,无法直接打开,需切割后处理。
关键函数:

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");
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值