图像滑动窗口 利用opencv和matlab

功能:利用opencv实现图像滑动窗口操作(即利用已知尺寸的窗口遍历整幅图像,形成许多子图像)

vs2015+opencv3.1

2016.10

函数实现

#ifndef SLIDINGWND_H_
#define SLIDINGWND_H_
//简单的滑动窗口的形成
#include<iostream>
#include<opencv2\opencv.hpp>
using namespace std;
using namespace cv;
//基于矩形窗口的图像滑动窗口操作,返回值为滑动窗口的数目
//@src 输入图像
//@wnd 输出结果
//@wndSize 滑动窗口的大小
//@ x_percent 滑动窗口在x方向步长的百分比,x_step=x_percent*wndSize.width
//@ y_percent 滑动窗口在y方向步长的百分比,y_step=y_percent*wndSize.height
int slidingWnd(Mat& src, vector<Mat>& wnd, Size& wndSize, double x_percent, double y_percent)
{
    int count = 0;  //记录滑动窗口的数目
    int x_step = cvCeil(x_percent*wndSize.width);
    int y_step = cvCeil(y_percent*wndSize.height);
    /*String wndName = "F:\\wnd\\";
    char temp[1000];*/
    int64 count1 = getTickCount();
    double freq = getTickFrequency();
    //利用窗口对图像进行遍历
    for (int i = 0; i < src.cols- wndSize.width; i+=y_step)
    {
        for (int j = 0; j < src.rows- wndSize.height; j+=x_step)
        {
            Rect roi(Point(j, i), wndSize);
            Mat ROI = src(roi);
            wnd.push_back(ROI);
            count++;
        }
    }
    int64 count2 = getTickCount();
    double time = (count2 - count1) / freq;
    cout << "Time=" << time * 100 << "ms"<<endl;
    cout << count << endl;
    return count;
}




main.cpp

#include<iostream>
#include<opencv2\opencv.hpp>
#include"slidingWnd.h"
using namespace std;
using namespace cv;

void main()
{
    String imgName = "F:\\lena_gray.jpg";
    Mat src = imread(imgName);
    cvtColor(src, src, COLOR_RGB2GRAY);

    vector<Mat> wnd;
    int count=slidingWnd(src, wnd, Size(30, 30),0.3,0.3);
    imshow("src", src);
    waitKey(0);

原文链接:http://blog.csdn.net/jiamuju84/article/details/52893320

2.matlab滑动窗口截取图片并保存

该代码的作用是对图片进行滑动截取保存

clc;
clear all;

maindir = 'D:\MyDataSet\airplane\wheel\JPEGImages';
sundir =  fullfile( maindir, '*.jpg' );
images = dir(sundir);% 在这个子文件夹下找后缀为jpg的文件
% 遍历每张图片
for j = 1 : length( images )
        imagepath = fullfile( maindir,images( j ).name )
         imgdata = imread( imagepath );   % 这里进行你的读取操作
new_folder = strcat('F:\matlab\tools\output\',num2str(j))
mkdir(new_folder);

%num1,num2是你要设定的矩形框长和宽
num1=375;
num2=500;
[m,n,ch]=size(imgdata);
mm=m-num1;
nn=n-num2;
filenum=1;
for k=1:100:mm
   for kk=1:100:nn
   B=imgdata(k:k+num1,kk:kk+num2,:)
   imshow(B);
%   file = ['.\output\',num2str(floor((k+kk-1)/10)),'.jpg'];
   file = [new_folder,'\',num2str(filenum),'.jpg'];
   filenum=filenum+1;
   imwrite(B,file);
   if (kk+num2)>=n
       break;
   end
   if (k+num1)>=m
       break;
   end
   end
end
end


原文链接:http://blog.csdn.net/run_it_faraway/article/details/76862506