兩種滑動視窗相關程式碼
阿新 • • 發佈:2019-01-05
功能:利用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;
}
#endif // !SLIDINGWND_H_
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
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);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
原圖
執行生成