Rumah > Soal Jawab > teks badan
代码功能:将图片中的一部分截取出来
报错图片
代码如下:
#pragma warning(disable:4996) //for sprintf()
#include "makegei.h"
#include <stdio.h>
#define H 40 //500
#define W 30 //400
#define BASE_RATIO 1.25
GenerateGEI::GenerateGEI(const char* folderpath)
{
gei_name = new char[100];
sprintf(gei_name, ".\\%s\\gei_.png", folderpath); //产生的GEI储存位置
num = 0;
}
GenerateGEI::~GenerateGEI(void)
{
delete gei_name;
}
int GenerateGEI::InsertImage(Mat image)
{
num++;
Process(image);
return 1;
}
int GenerateGEI::Process(Mat image)
{
Mat origin = FindContours(image);
Mat normal = Resize(origin);
//Mat show_gei = CalGei(normal);
imwrite(gei_name, normal);
return 1;
}
//RNG G_RNG(1234);
Mat GenerateGEI::FindContours(Mat image)
{
Mat image_tmp = image.clone(); //用于findContours,因为该函数使用后会导致原图改变,所以要复制一个用于该函数
#ifdef _DEBUG
cv::imshow("image", image);
cv::waitKey(500);
#endif
std::vector<Contours> contours; //每个轮廓的所有角点理论上只需要contours[0]
cv::findContours(image_tmp, contours, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE); //findContours只能处理8UC1和32SC1
cv::Rect r0 = cv::boundingRect(cv::Mat(contours[0]));
cv::Mat gait_img_roi = image(r0);
return gait_img_roi;
}
Mat GenerateGEI::Resize(Mat image)
{
float ra = image.rows / image.cols;
cv::Mat gait_roi_tmp;
Mat gait_img2 = Mat::zeros(H, W, CV_8UC1);
// if(ra>= BASE_RATIO)
{
double resize_scale = (double)H / image.rows;
cv::resize(image, gait_roi_tmp, cv::Size(), resize_scale, resize_scale); //按比例缩放
for (int i = 0; i<gait_roi_tmp.rows; i++)
{
uchar* p_tmp = gait_roi_tmp.ptr<uchar>(i);
uchar* p = gait_img2.ptr<uchar>(i);
for (int j = (W - gait_roi_tmp.cols) / 2, k = 0; k<gait_roi_tmp.cols; k++, j++)
{
p[j] = p_tmp[k];
}
}
}
return gait_img2;
}
void main()
{
char folderpath[100] = "\\yyb\\";
char* filename = "010-nm-05-072-088.png"; //图片名称
GenerateGEI* generate = new GenerateGEI(folderpath); //传入当前文件夹路径,方便作为生成的GEI文件名
Mat image = cv::imread(filename, 0); //按单通道读入
generate->InsertImage(image);
delete generate;
}