将矩形图像转化为正方形(两边补像素)

如题 直接贴代码

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
#include 

using namespace std;
using namespace cv;

int _tmain(int argc, _TCHAR* argv[])
{
	Mat L=imread("1.jpg");
	cvNamedWindow("le.jpg", CV_WINDOW_AUTOSIZE);
	imshow("le.jpg", L);	

	long oRows = L.rows; //原图的高
	long oCols = L.cols*L.channels(); //原图像素数据的宽
	
	long NdR = L.rows > L.cols ? L.rows : L.cols;//新图的边长

	Mat New(NdR, NdR, CV_8UC3, Scalar(1, 1, 1));
	
	long nNR = NdR * 3; //New 矩阵的宽
	long nmidd = (L.rows - L.cols) / 2 * 3; //新图空白的部分
	//两个矩阵的指针
	uchar *pL = L.data;
	uchar *pN = New.data;

	if (L.isContinuous()) //判断原图的存储方式
	{
		if (L.rows > L.cols)
		{
			for (long i = 0; i < NdR; i++)
			{
				for (long j = nmidd; j <= oCols + nmidd; j++)
				{
					//将原图的相应位置的像素赋值给新图
					*(pN + (i*nNR + j)) = *(pL + (i*L.cols*L.channels() + j - nmidd));
				}
			}
		}
		else if (L.rows < L.cols)
		{
			for (long i = ((L.cols - L.rows) / 2); i < (L.rows + (L.cols - L.rows) / 2); i++)
			{
				for (long j = 0; j <= oCols; j++)
				{
					//将原图的相应位置的像素赋值给新图
					*(pN + (i*nNR + j)) = *(pL + ((i - (L.cols - L.rows) / 2)*L.cols*L.channels() + j));
				}				
			}
		}
		else
		{
			New = L;
		}
	}

	imwrite("new.jpg", New);
	return 0;
}


原图
将矩形图像转化为正方形(两边补像素)_第1张图片

处理后

将矩形图像转化为正方形(两边补像素)_第2张图片

你可能感兴趣的:(图像处理)