diff --git a/DENSENET_MERGE_TODO b/DENSENET_MERGE_TODO new file mode 100644 index 00000000000..3a2541a64f1 --- /dev/null +++ b/DENSENET_MERGE_TODO @@ -0,0 +1,15 @@ + +list of the issues blocking the merge of the DenseNet feature branch: + +- critical +-- replacement of GPL'd code (including removal from history) +-- update build process / Makefile to match current practice +-- tests +-- trivial: remove DenseNet README.md header +-- trivial: remove this todo file + +- unclear neccessity, semantics, and/or priority +-- general cleanup of commit sequence (probably mostly squashing) +-- input interface changes (i.e. jpeg filname as input -> ?) +-- output interface changes (?, but probably something: image support size, multiple layer output, alignment, etc.) +-- if still reading image files after any iface changes and removal of GPL code, use XX instead of YY diff --git a/Makefile b/Makefile index 54437f1e914..8cce7bfe514 100644 --- a/Makefile +++ b/Makefile @@ -44,6 +44,10 @@ NONGEN_CXX_SRCS := $(shell find \ -name "*.cpp" -or -name "*.hpp" -or -name "*.cu" -or -name "*.cuh") LINT_REPORT := $(BUILD_DIR)/cpp_lint.log FAILED_LINT_REPORT := $(BUILD_DIR)/cpp_lint.error_log +# STITCHPYRAMID is for stitching multiresolution feature pyramids. (exclude test files) +STITCHPYRAMID_SRC := $(shell find src/stitch_pyramid ! -name "test_*.cpp" -name "*.cpp") +STITCHPYRAMID_HDRS := $(shell find src/stitch_pyramid -name "*.h") +STITCHPYRAMID_SO := src/stitch_pyramid/libPyramidStitcher.so # PY$(PROJECT)_SRC is the python wrapper for $(PROJECT) PY$(PROJECT)_SRC := python/$(PROJECT)/py$(PROJECT).cpp PY$(PROJECT)_SO := python/$(PROJECT)/py$(PROJECT).so @@ -96,13 +100,18 @@ LIBRARIES := cudart cublas curand \ PYTHON_LIBRARIES := boost_python python2.7 WARNINGS := -Wall -COMMON_FLAGS := -DNDEBUG -O2 $(foreach includedir,$(INCLUDE_DIRS),-I$(includedir)) +COMMON_FLAGS := -O2 $(foreach includedir,$(INCLUDE_DIRS),-I$(includedir)) +#COMMON_FLAGS := -O3 -DENABLE_ALLOC_TRACE $(foreach includedir,$(INCLUDE_DIRS),-I$(includedir)) +#COMMON_FLAGS := -DNDEBUG -O2 $(foreach includedir,$(INCLUDE_DIRS),-I$(includedir)) CXXFLAGS += -pthread -fPIC $(COMMON_FLAGS) NVCCFLAGS := -ccbin=$(CXX) -Xcompiler -fPIC $(COMMON_FLAGS) LDFLAGS += $(foreach librarydir,$(LIBRARY_DIRS),-L$(librarydir)) \ $(foreach library,$(LIBRARIES),-l$(library)) PYTHON_LDFLAGS := $(LDFLAGS) $(foreach library,$(PYTHON_LIBRARIES),-l$(library)) +#SHARED_LDFLAGS := -shared -Wl,--no-undefined # for gcc, this is probably a more sane default: any undefined syms will give a link error +SHARED_LDFLAGS := -shared + ############################## # Define build targets @@ -139,22 +148,42 @@ tools: init $(TOOL_BINS) examples: init $(EXAMPLE_BINS) + +stitch: $(STITCHPYRAMID_SO) + +.PHONY : stitch + +$(STITCHPYRAMID_SO): $(STITCHPYRAMID_HDRS) $(STITCHPYRAMID_SRC) + $(CXX) $(SHARED_LDFLAGS) -o $(STITCHPYRAMID_SO) $(STITCHPYRAMID_SRC) $(CXXFLAGS) -ljpeg + py$(PROJECT): py -py: init $(STATIC_NAME) $(PY$(PROJECT)_SRC) $(PROTO_GEN_PY) - $(CXX) -shared -o $(PY$(PROJECT)_SO) $(PY$(PROJECT)_SRC) \ +py: init $(STATIC_NAME) $(PY$(PROJECT)_SRC) $(PROTO_GEN_PY) $(STITCHPYRAMID_SO) + $(CXX) $(SHARED_LDFLAGS) -o $(PY$(PROJECT)_SO) $(PY$(PROJECT)_SRC) -L./src/stitch_pyramid -lPyramidStitcher -I./src/stitch_pyramid \ $(STATIC_NAME) $(CXXFLAGS) $(PYTHON_LDFLAGS) @echo mat$(PROJECT): mat -mat: init $(STATIC_NAME) $(MAT$(PROJECT)_SRC) - $(MATLAB_DIR)/bin/mex $(MAT$(PROJECT)_SRC) $(STATIC_NAME) \ - CXXFLAGS="\$$CXXFLAGS $(CXXFLAGS) $(WARNINGS)" \ - CXXLIBS="\$$CXXLIBS $(LDFLAGS)" \ +mat: init $(STATIC_NAME) $(MAT$(PROJECT)_SRC) $(STITCHPYRAMID_SO) + $(MATLAB_DIR)/bin/mex -g $(MAT$(PROJECT)_SRC) $(STATIC_NAME) \ + CXXFLAGS="\$$CXXFLAGS $(CXXFLAGS) $(WARNINGS)" -I./python/caffe \ + CXXLIBS="\$$CXXLIBS $(LDFLAGS)" -L./src/stitch_pyramid -lPyramidStitcher \ -o $(MAT$(PROJECT)_SO) @echo +mkoctfile_mat$(PROJECT): mkoctfile_mat + +# CXXFLAGS="-Wall -fpic -O2" mkoctfile --mex matlab/caffe/matcaffe.cpp libcaffe.a -pthread -I/usr/local/include -I/usr/include/python2.7 -I/usr/local/lib/python2.7/dist-packages/numpy/core/include -I./src -I./include -I/usr/local/cuda/include -I/opt/intel/mkl/include -Wall -L/usr/lib -L/usr/local/lib -L/usr/local/cuda/lib64 -L/usr/local/cuda/lib -L/opt/intel/mkl/lib -L/opt/intel/mkl/lib/intel64 -lcudart -lcublas -lcurand -lprotobuf -lopencv_core -lopencv_highgui -lglog -lmkl_rt -lmkl_intel_thread -lleveldb -lsnappy -lpthread -lboost_system -lopencv_imgproc -L/home/moskewcz/git_work/caffe/python/caffe/stitch_pyramid -lPyramidStitcher -I./python/caffe -o matlab/caffe/caffe + + +mkoctfile_mat: init $(STATIC_NAME) $(MAT$(PROJECT)_SRC) $(STITCHPYRAMID_SO) + CXXFLAGS="$$CXXFLAGS $(CXXFLAGS)" \ + DL_LDFLAGS="$$DL_LDFLAGS $(SHARED_LDFLAGS)" \ + LFLAGS="$$LFLAGS $(LDFLAGS) -L./src/stitch_pyramid -lPyramidStitcher" \ + mkoctfile --mex -g -v $(MAT$(PROJECT)_SRC) $(STATIC_NAME) -o $(MAT$(PROJECT)_SO) + @echo + $(NAME): init $(PROTO_OBJS) $(OBJS) $(CXX) -shared -o $(NAME) $(OBJS) $(CXXFLAGS) $(LDFLAGS) $(WARNINGS) @echo diff --git a/README.md b/README.md index 586c412901e..096bf7dd8cb 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,75 @@ +# -- WARNING: THIS IS AN FORK/FEATURE BRANCH OF [CAFFE](http://github.com/BVLC/caffe) (PR PENDING). -- +## DenseNet + +[DenseNet: Implementing Efficient ConvNet Descriptor Pyramids](http://arxiv.org/abs/1404.1869)
+Forrest Iandola, Matt Moskewicz, Sergey Karayev, Ross Girshick, Trevor Darrell, and Kurt Keutzer.
+Arxiv technical report, April 2014. + +Licensing
+Except where noted in individual files, all new code files / changes in this branch are: +Copyright (c) 2013 Matthew Moskewicz and Forrest Iandola +and are BSD 2-Clause licensed with the same as the original source (see [LICENSE](LICENSE)). + +The two example images are taken from the PASCAL vision benchmark set. + +DenseNet APIs in Matlab and Python
+The DenseNet API is fairly similar to the popular `featpyramid.m` HOG extraction API from the [voc-release5 Deformable Parts Model code](https://github.com/rbgirshick/voc-dpm/blob/master/features/featpyramid.m). Our primary API function is called `convnet_featpyramid()`. + +Running DenseNet in Matlab
+`caffe/matlab/caffe/featpyramid_matcaffe_demo.m` is a good example to start with. Or, we can walk through it together here: + +```matlab + %Caffe setup: + model_def_file = 'CAFFE_ROOT/python/caffe/imagenet/imagenet_rcnn_batch_1_input_1100x1100_output_conv5.prototxt' + % NOTE: you'll have to get the pre-trained ILSVRC network + model_file = 'path/to/alexnet_train_iter_470000'; + caffe('init', model_def_file, model_file); + caffe('set_mode_gpu') %CPU mode works too + caffe('set_phase_test') + + %using DenseNet: + image = 'myImage.jpg' %must be JPEG + pyra = convnet_featpyramid(image) +``` + +Running DenseNet in Matlab (advanced users)
+```matlab + % (you need to do Caffe setup first, as shown in above example) + image = 'myImage.jpg' + + %optional parameters (code will still run with incomplete or nonexistant pyra_params): + pyra_params.interval = 5; %octaves per pyramid scale + pyra_params.img_padding = 16 %padding around image (in pixels) + pyra_params.feat_minWidth = 6; %select smallest scale in pyramid (in output feature dimensions) + pyra_params.feat_minHeight = 6; %in output feature dimensions + pyra = convnet_featpyramid(image, pyra_params) + + %taking a look at the output pyramid: + scales: [40x1 double] %resolution of each pyramid scale + feat: {40x1 cell} %descriptors (one cell array per scale) + imwidth: 353 %input image size in pixels + imheight: 500 + feat_padx: 1 %border padding around descriptors (img_padding/sbin) + feat_pady: 1 + sbin: 16 %approx. downsampling factor from pixels to descriptors + padx: 1 %extra copy of feat_pad{x,y}. silly...should remove? + pady: 1 + num_levels: 40 %num scales in pyramid + valid_levels: [40x1 logical] +``` + +Running DenseNet in Python
+The Python API is similar to the Matlab API described above. +`caffe/python/caffe/featpyramid_demo.py` is a good starting point for using DenseNet in Python. + + +Other notes: +- As with many other operations in Caffe, you'll need to download a pretrained Alexnet CNN prior to running our DenseNet demo. +- For most of our default examples, we use the 'Alexnet' network and output descriptors from the conv5 layer. You can adjust these decisions by editing the 'prototxt' files used at setup time. + + +## Original Caffe README.md follows + [Caffe: Convolutional Architecture for Fast Feature Extraction](http://caffe.berkeleyvision.org) Created by [Yangqing Jia](http://daggerfs.com), UC Berkeley EECS department. diff --git a/include/caffe/featpyra_common.hpp b/include/caffe/featpyra_common.hpp new file mode 100644 index 00000000000..14906b78eb9 --- /dev/null +++ b/include/caffe/featpyra_common.hpp @@ -0,0 +1,79 @@ +#include "caffe/imagenet_mean.hpp" +#include "boost/shared_ptr.hpp" +#include "caffe/caffe.hpp" +#include + +namespace caffe { + + using namespace std; + using boost::shared_ptr; + +//switch RGB to BGR indexing (for Caffe convention) + inline int get_BGR(int channel_RGB) { assert( channel_RGB < 3 ); return 2 - channel_RGB; } + + struct densenet_params_t { + uint32_t interval; // # scales per octave + uint32_t img_padding; // in image pixels (at scale=1.0). could later allow per-dim img_padx/img_pady as alternative. + uint32_t feat_minWidth; //smallest desired output scale, in terms of descriptor dimensions + uint32_t feat_minHeight; + densenet_params_t( void ) { // default values + interval = 10; + img_padding = 16; + feat_minWidth = 1; + feat_minHeight = 1; + } + }; + + typedef vector< float > vect_float; + typedef shared_ptr< vect_float > p_vect_float; + typedef vector< p_vect_float > vect_p_vect_float; + + typedef vector< uint32_t > vect_uint32_t; + typedef shared_ptr< vect_uint32_t > p_vect_uint32_t; + + // a sketch of a possible shared output type for python/matlab interfaces. missing dims for feats. + struct densenet_output_t { + p_vect_float imwidth; // not including padding + p_vect_float imheight; + p_vect_uint32_t feat_padx; + p_vect_uint32_t feat_pady; + p_vect_float scales; + vect_p_vect_float feats; + uint32_t nb_planes; + }; + + static void raw_do_forward( shared_ptr > net_, vect_p_vect_float const & bottom ) { + vector*>& input_blobs = net_->input_blobs(); + CHECK_EQ(bottom.size(), input_blobs.size()); + for (unsigned int i = 0; i < input_blobs.size(); ++i) { + assert( bottom[i]->size() == uint32_t(input_blobs[i]->count()) ); + const float* const data_ptr = &bottom[i]->front(); + switch (Caffe::mode()) { + case Caffe::CPU: + memcpy(input_blobs[i]->mutable_cpu_data(), data_ptr, + sizeof(float) * input_blobs[i]->count()); + break; + case Caffe::GPU: + cudaMemcpy(input_blobs[i]->mutable_gpu_data(), data_ptr, + sizeof(float) * input_blobs[i]->count(), cudaMemcpyHostToDevice); + break; + default: + LOG(FATAL) << "Unknown Caffe mode."; + } // switch (Caffe::mode()) + } + //const vector*>& output_blobs = net_->ForwardPrefilled(); + net_->ForwardPrefilled(); + } + + // get sbin as product of strides. note that a stride of 0 in the + // caffe strides vector indictes a layer has no stride. such layers + // are ignored in this calculation + static uint32_t get_sbin( shared_ptr > net_ ) { + vect_uint32_t const & strides = net_->layer_strides(); + uint32_t ret = 1; + for( vect_uint32_t::const_iterator i = strides.begin(); i != strides.end(); ++i ) { if( *i ) { ret *= (*i); } } + return ret; + } + + template< typename T > inline std::string str(T const & i) { std::stringstream s; s << i; return s.str(); } // convert T i to string +} diff --git a/include/caffe/imagenet_mean.hpp b/include/caffe/imagenet_mean.hpp new file mode 100644 index 00000000000..254e371ea30 --- /dev/null +++ b/include/caffe/imagenet_mean.hpp @@ -0,0 +1,18 @@ +#ifndef IMAGENET_MEAN_H +#define IMAGENET_MEAN_H + +//mean of all imagenet classification images +// calculation: +// 1. mean of all imagenet images, per pixel location +// 2. take the mean image, and get the mean pixel for R,G,B +// (did it this way because we already had the 'mean of all images, per pixel location') + + +#define IMAGENET_MEAN_R 122.67f +#define IMAGENET_MEAN_G 116.66f +#define IMAGENET_MEAN_B 104.00f + +static float const IMAGENET_MEAN_RGB[3] = {IMAGENET_MEAN_R, IMAGENET_MEAN_G, IMAGENET_MEAN_B}; +static float const IMAGENET_MEAN_BGR[3] = {IMAGENET_MEAN_B, IMAGENET_MEAN_G, IMAGENET_MEAN_R}; + +#endif diff --git a/include/caffe/net.hpp b/include/caffe/net.hpp index b5a57b3c5a4..cb415624463 100644 --- a/include/caffe/net.hpp +++ b/include/caffe/net.hpp @@ -62,6 +62,8 @@ class Net { inline const string& name() { return name_; } // returns the layer names inline const vector& layer_names() { return layer_names_; } + // returns the layer strides + inline const vector& layer_strides() { return layer_strides_; } // returns the blob names inline const vector& blob_names() { return blob_names_; } // returns the blobs @@ -91,6 +93,7 @@ class Net { // Individual layers in the net vector > > layers_; vector layer_names_; + vector layer_strides_; vector layer_need_backward_; // blobs stores the blobs that store intermediate results between the // layers. diff --git a/matlab/caffe/convnet_featpyramid.m b/matlab/caffe/convnet_featpyramid.m new file mode 100644 index 00000000000..9e155227865 --- /dev/null +++ b/matlab/caffe/convnet_featpyramid.m @@ -0,0 +1,44 @@ + +% wrapper for DenseNet convnet_pyramid. +% provides some extra output params that you wouldn't get with caffe('convnet_featpyramid', ...) + +% YOU MUST CALL caffe('init', ...) BEFORE RUNNING THIS. +function pyra = convnet_featpyramid(imgFname, pyra_params) + + %set defaults for params not passed by user + if( ~exist('pyra_params') || ~isfield(pyra_params, 'interval') ) + pyra_params.interval = 5; + end + if( ~exist('pyra_params') || ~isfield(pyra_params, 'img_padding') ) + pyra_params.img_padding = 16; + end + if( ~exist('pyra_params') || ~isfield(pyra_params, 'feat_minWidth') ) + pyra_params.feat_minWidth = 1; + end + if( ~exist('pyra_params') || ~isfield(pyra_params, 'feat_minHeight') ) + pyra_params.feat_minHeight = 1; + end + + % compute the pyramid: + pyra = caffe('convnet_featpyramid', imgFname, pyra_params); + + % add DPM-style fields: + %pyra.sbin = 16; + pyra.padx = pyra.feat_padx; % for DPM conventions + pyra.pady = pyra.feat_pady; + pyra.num_levels = length(pyra.scales); + pyra.valid_levels = true(pyra.num_levels, 1); + + pyra.imsize = [pyra.imheight pyra.imwidth]; + pyra.feat = permute_feat(pyra.feat); % [d h w] -> [h w d] + pyra.scales = double(pyra.scales); %get_detection_trees prefers double +end + +% input: pyra.feat{:}, with dims [d h w] +% output: pyra.feat{:}, with dims [h w d] +function feat = permute_feat(feat) + for featIdx = 1:length(feat) + feat{featIdx} = permute( feat{featIdx}, [2 3 1] ); + end +end + diff --git a/matlab/caffe/convnet_featpyramid_cache.m b/matlab/caffe/convnet_featpyramid_cache.m new file mode 100644 index 00000000000..390a2839cda --- /dev/null +++ b/matlab/caffe/convnet_featpyramid_cache.m @@ -0,0 +1,120 @@ + +% wrapper for DenseNet convnet_pyramid. +% provides some extra output params that you wouldn't get with caffe('convnet_featpyramid', ...) +% this 'cache' verison enables precomputing features once (not once per pascal category... REALLY ONCE.) + +% to enable caching, you simply define 'pyra_params.feature_dir' + +% YOU MUST CALL caffe('init', ...) BEFORE RUNNING THIS. +function pyra = convnet_featpyramid_cache(imgFname, pyra_params, feature_dir) + %set defaults for params not passed by user + if( ~exist('pyra_params') || ~isfield(pyra_params, 'interval') ) + pyra_params.interval = 5; + end + if( ~exist('pyra_params') || ~isfield(pyra_params, 'img_padding') ) + pyra_params.img_padding = 16; + end + + %save the user's minWidth and minHeight (if it exists) + if( exist('pyra_params') && isfield(pyra_params, 'feat_minWidth') ) + local_pyra_params.feat_minWidth = pyra_params.feat_minWidth; + else + local_pyra_params.feat_minWidth = 1; + end + if( exist('pyra_params') && isfield(pyra_params, 'feat_minHeight') ) + local_pyra_params.feat_minHeight = pyra_params.feat_minHeight; + else + local_pyra_params.feat_minHeight = 1; + end + + % only use caching if user provided pyra_params.feature_dir. + if( exist('feature_dir') == 1 ) % ==1 means 'exists in workspace' + useCache = true; + [path basename ext] = fileparts(imgFname); + cache_location = [feature_dir '/' basename '.mat']; + pyra = try_cache(imgFname, pyra_params, cache_location); %returns [] if cached object does not exist + else + useCache = false; + cache_location = ''; + pyra = []; + end + + if isempty(pyra) + %for 'cache' version, we compute all scales, then prune the too-small ones in Matlab. + pyra_params.feat_minWidth = 1; + pyra_params.feat_minHeight = 1; + + % compute the pyramid: + pyra = caffe('convnet_featpyramid', imgFname, pyra_params); + + % add DPM-style fields: + pyra.sbin = 16; + pyra.padx = pyra.feat_padx; % for DPM conventions + pyra.pady = pyra.feat_pady; + pyra.num_levels = length(pyra.scales); + pyra.valid_levels = true(pyra.num_levels, 1); + + pyra.imsize = [pyra.imheight pyra.imwidth]; + pyra.feat = permute_feat(pyra.feat); % [d h w] -> [h w d] + pyra.scales = double(pyra.scales); %get_detection_trees prefers double + pyra.im = imgFname; + + if useCache == true + save(cache_location, 'pyra'); + end + end + + pyra = prune_small_scales(pyra, local_pyra_params); +end + +function pyra = try_cache(imgFname, pyra_params, cache_location) + try + load(cache_location); %contains pyra + assert( exist('pyra') == 1 ); %make sure we actually loaded the pyramid. + + [path basename_gold ext] = fileparts(imgFname); + [path basename_input ext] = fileparts(pyra.im); + assert( strcmp(basename_input, basename_gold) == 1 ) %make sure we got the right pyramid + %assert( strcmp(pyra.im, imgFname) == 1 ) %make sure we got the right pyramid + display(' found cached features'); + catch + pyra = []; + end +end + +% input: pyra.feat{:}, with dims [d h w] +% output: pyra.feat{:}, with dims [h w d] +function feat = permute_feat(feat) + for featIdx = 1:length(feat) + feat{featIdx} = permute( feat{featIdx}, [2 3 1] ); + end +end + +% needs feat_minHeight and feat_minWidth to be defined in pyra_params. +% prune too-small scales +function pyra = prune_small_scales(pyra, pyra_params) + + if( ~exist('pyra_params') || ~isfield(pyra_params, 'feat_minWidth') ) + return; + end + if( ~exist('pyra_params') || ~isfield(pyra_params, 'feat_minHeight') ) + return; + end + + num_scales = length(pyra.scales); + num_pruned = 0; + + for scaleIdx = 1:num_scales + [h w d] = size(pyra.feat{scaleIdx}); + if (h < pyra_params.feat_minHeight) || (w < pyra_params.feat_minWidth) + %found a scale that's too small. prune it. + pyra.valid_levels(scaleIdx) = false; + pyra.feat{scaleIdx} = []; %clear the too-small scale, just to be safe. + pyra.scales(scaleIdx) = NaN; + num_pruned = num_pruned + 1; + end + end + display([' had to remove last ' int2str(num_pruned) ' scales, because they were smaller than the minimum that you specified in (feat_minWidth, feat_minHeight)']) +end + + diff --git a/matlab/caffe/featpyramid_matcaffe_demo.m b/matlab/caffe/featpyramid_matcaffe_demo.m new file mode 100644 index 00000000000..13fd81ea325 --- /dev/null +++ b/matlab/caffe/featpyramid_matcaffe_demo.m @@ -0,0 +1,62 @@ + +% Demo of the matlab wrapper to construct ConvNet feature pyramids +% +% input +% imfn image filename +% use_gpu 1 to use the GPU, 0 to use the CPU +% +% output +% N row structure array with two fields: scale, feats +% scale: scalar +% feats: 2D numeric array +% +% You may need to do the following before you start matlab: +% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda/lib64 +% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 +% Or the equivalent based on where things are installed on your system +% +% Usage: +% imfn = '../../examples/cat.jpg'; +% pyra = featpyramid_matcaffe_demo(imfn, 1); + +function pyra = featpyramid_matcaffe_demo(imfn, use_gpu) + if ~exist('imfn', 'var') + imfn = './pascal_000001.jpg' + %imfn = '../../python/caffe/imagenet/pascal_009959.jpg'; + end + + %model_def_file = '../../examples/imagenet_deploy.prototxt'; + model_def_file = '../../python/caffe/imagenet/imagenet_rcnn_batch_1_input_1100x1100_output_conv5.prototxt' + % NOTE: you'll have to get the pre-trained ILSVRC network + model_file = '../../examples/alexnet_train_iter_470000'; + + % init caffe network (spews logging info) + caffe('init', model_def_file, model_file); + + % set to use GPU or CPU + if exist('use_gpu', 'var') && use_gpu + caffe('set_mode_gpu'); + else + caffe('set_mode_cpu'); + end + + % put into test mode + caffe('set_phase_test'); + + % optionally, pass parmeters as second argument to convnet_featpyramid (set here to the defaults) + pyra_params.interval = 10; + pyra_params.img_padding = 16; + pyra_params.feat_minWidth = 1; + pyra_params.feat_minHeight = 1; + + pyra = convnet_featpyramid(imfn, pyra_params); + %pyra = caffe('convnet_featpyramid', imfn, pyra_params ); % call with parameters ... + % pyra = caffe('convnet_featpyramid', imfn ); % ... or with no parameters + + %keyboard + %visualize one scale: + colormap(gray); + %imagesc(squeeze(sum(pyra.feat{1}, 1))); + imagesc(squeeze(sum(pyra.feat{1}, 3))); + + diff --git a/matlab/caffe/get_featureSlice.m b/matlab/caffe/get_featureSlice.m new file mode 100644 index 00000000000..2b61597aa40 --- /dev/null +++ b/matlab/caffe/get_featureSlice.m @@ -0,0 +1,97 @@ + + +% @param pyra... should contain 'sbin' and 'scales' +% @param bbox.{x1 x2 y1 y2} -- in image coordinates. -- must be round numbers. +% @param templateSize = desired shape of output in feature descriptor units (e.g. [6 10] root filter) +% (could pass in image_size ... though we currently don't use it, and imsize is typically in pyra) +function [featureSlice, scaleIdx, roundedBox_in_px] = get_featureSlice(pyra, bbox, templateSize) + + %1. tweak bbox to match the aspect ratio of templateSize + %bbox = match_aspect_ratio(bbox, templateSize); + + %2. select a scale in the pyramid + + bbox_desc = bbox_mult(bbox, 1.0/single(pyra.sbin)); % unscaled image -> unscaled descriptor coords. + bbox_desc_dim = [bbox_desc.y2 - bbox_desc.y1, bbox_desc.x2 - bbox_desc.x1]; %bbox dim in the space of scale=1 descriptors. + bbox_desc_scale = templateSize / bbox_desc_dim; %scale factor from (scale=1) to a scale where bbox fits in templateSize + %bbox_desc_scale = (templateSize-1) / bbox_desc_dim; %pretend that template size is slightly smaller... so featureSlice will be slightly outside orig bbox + + scale_to_use = mean(bbox_desc_scale); %avg of scale factors for x and y dims. + [scale_to_use, scaleIdx] = findNearestScale(scale_to_use, pyra.scales); %best precomputed approx of scale_to_use + + padx_desc_scaled = pyra.padx; %this is in descriptor cells and not image pixels. + pady_desc_scaled = pyra.pady; + + scale_width_desc = size(pyra.feat{scaleIdx},2); + scale_height_desc = size(pyra.feat{scaleIdx},1); + + %3. rip out a slice from the appropriate scale + + % center bbox_to_use on (bbox_desc.x2 - bbox_desc.x1), (bbox_desc.y2 - bbox_desc.y1) + + bbox_desc_x_center = bbox_desc.x1 + (bbox_desc.x2 - bbox_desc.x1)/2.0; + bbox_desc_y_center = bbox_desc.y1 + (bbox_desc.y2 - bbox_desc.y1)/2.0; + bbox_to_use.x1 = ceil(bbox_desc_x_center*scale_to_use - templateSize(2)/2.0 + padx_desc_scaled); %(center - templateWidth/2) + bbox_to_use.x1 = max(1, bbox_to_use.x1); % make sure we didn't fall off the edge + bbox_to_use.x2 = bbox_to_use.x1 + templateSize(2) - 1; + bbox_to_use.y1 = ceil(bbox_desc_y_center*scale_to_use - templateSize(1)/2.0 + pady_desc_scaled); %(center - templateHeight/2) + bbox_to_use.y1 = max(1, bbox_to_use.y1); % make sure we didn't fall off the edge + bbox_to_use.y2 = bbox_to_use.y1 + templateSize(1) - 1; + + %4. make sure the slice fits into the overall space. + + if(bbox_to_use.x2 > scale_width_desc) %if we fell off the edge... + x_offset = bbox_to_use.x2 - scale_width_desc; %amount by which we fell off the edge + bbox_to_use.x1 = bbox_to_use.x1 - x_offset; + bbox_to_use.x2 = bbox_to_use.x2 - x_offset; + end + if(bbox_to_use.y2 > scale_height_desc) %if we fell off the edge... + y_offset = bbox_to_use.y2 - scale_height_desc; %amount by which we fell off the edge + bbox_to_use.y1 = bbox_to_use.y1 - y_offset; + bbox_to_use.y2 = bbox_to_use.y2 - y_offset; + end + + %bbox_to_use + %scale_to_use + %scaleIdx + try + featureSlice = pyra.feat{scaleIdx}(bbox_to_use.y1 : bbox_to_use.y2, bbox_to_use.x1 : bbox_to_use.x2, :); + catch + display('problem with get_featureSlice... you can debug it') + keyboard + end + + %4. project rounded box back to img space (approx) -- for debugging + roundedBox_in_px = bbox_mult(bbox_to_use, (pyra.sbin / scale_to_use)); + %roundedBox_in_px = bbox_add(roundedBox_in_px, -pyra.padx*pyra.sbin/scale_to_use); %assume padx==pady + roundedBox_in_px.x1 = roundedBox_in_px.x1 - pyra.padx*pyra.sbin/scale_to_use; + roundedBox_in_px.x2 = roundedBox_in_px.x2 - pyra.padx*pyra.sbin/scale_to_use; + roundedBox_in_px.y1 = roundedBox_in_px.y1 - pyra.pady*pyra.sbin/scale_to_use; + roundedBox_in_px.y2 = roundedBox_in_px.y2 - pyra.pady*pyra.sbin/scale_to_use; +end + +% multiply a bbox.{x1 x2 y1 y2} by some value. +function bbox_out = bbox_mult(bbox, multiplier) + bbox_out.x1 = bbox.x1 * multiplier; + bbox_out.x2 = bbox.x2 * multiplier; + bbox_out.y1 = bbox.y1 * multiplier; + bbox_out.y2 = bbox.y2 * multiplier; +end + +% add some value to a bbox.{x1 x2 y1 y2}. +function bbox_out = bbox_add(bbox, num_to_add) + bbox_out.x1 = bbox.x1 + num_to_add; + bbox_out.x2 = bbox.x2 + num_to_add; + bbox_out.y1 = bbox.y1 + num_to_add; + bbox_out.y2 = bbox.y2 + num_to_add; +end + +% @param scale_to_use = a scale that maps bbox to templateSize +% @param scales = list of scales that we computed in our pyramid +function [scale_to_use, scaleIdx] = findNearestScale(scale_to_use, scales) + + %scaleIdx = index of nearestScale in the list of scales + [nearestScale_distance, scaleIdx] = min(abs(scale_to_use - scales)); + scale_to_use = scales(scaleIdx); +end + diff --git a/matlab/caffe/matcaffe.cpp b/matlab/caffe/matcaffe.cpp index ddbacca1579..1e9a59f3b3e 100644 --- a/matlab/caffe/matcaffe.cpp +++ b/matlab/caffe/matcaffe.cpp @@ -9,11 +9,28 @@ #include "mex.h" #include "caffe/caffe.hpp" +#include "stitch_pyramid/PyramidStitcher.h" //also includes JPEGImage, Patchwork, etc +#include "boost/shared_ptr.hpp" +#include "caffe/featpyra_common.hpp" +#include #define MEX_ARGS int nlhs, mxArray **plhs, int nrhs, const mxArray **prhs using namespace caffe; // NOLINT(build/namespaces) + uint32_t mx_to_u32( string const & err_str, mxArray const * const mxa ) { + if( !mxIsNumeric( mxa ) ) { mexErrMsgTxt( (err_str + ": expected a numeric value, got something else. ").c_str()); } + uint32_t const sz = mxGetNumberOfElements( mxa ); + if( sz != 1 ) { mexErrMsgTxt( (err_str+": expected a single element, but got " + str(sz) + ".").c_str()); } + return uint32_t(mxGetScalar(mxa)); +} + +static mxArray * u32_to_mx( uint32_t const val ) { // returned as float (i.e. scalar single) + mxArray * const mxa = mxCreateNumericMatrix( 1, 1, mxSINGLE_CLASS, mxREAL ); + *(float*)(mxGetData(mxa)) = (float)val; + return mxa; +} + // The pointer to the internal caffe::Net instance static shared_ptr > net_; @@ -87,6 +104,78 @@ static mxArray* do_forward(const mxArray* const bottom) { return mx_out; } +template< typename T > +T sz_from_dims( uint32_t const num_dims, T const * const dims ) { + T ret = 1; + for( uint32_t dim = 0; dim < num_dims; ++dim ) { ret *= dims[dim]; } + return ret; +} + +typedef vector< mxArray * > vect_rp_mxArray; +//typedef vector< float > vect_float; // now defined in featpyra_common.hpp +//typedef shared_ptr< vect_float > p_vect_float; +//typedef vector< p_vect_float > vect_p_vect_float; + +p_vect_float make_p_vect_float( size_t const num ) { + p_vect_float ret( new vect_float ); + ret->resize( num, 0.0f ); + return ret; +}; + +/* +static void raw_do_forward( vect_p_vect_float const & bottom ) { + vector*>& input_blobs = net_->input_blobs(); + CHECK_EQ(bottom.size(), input_blobs.size()); + for (unsigned int i = 0; i < input_blobs.size(); ++i) { + assert( bottom[i]->size() == uint32_t(input_blobs[i]->count()) ); + const float* const data_ptr = &bottom[i]->front(); + switch (Caffe::mode()) { + case Caffe::CPU: + memcpy(input_blobs[i]->mutable_cpu_data(), data_ptr, + sizeof(float) * input_blobs[i]->count()); + break; + case Caffe::GPU: + cudaMemcpy(input_blobs[i]->mutable_gpu_data(), data_ptr, + sizeof(float) * input_blobs[i]->count(), cudaMemcpyHostToDevice); + break; + default: + LOG(FATAL) << "Unknown Caffe mode."; + } // switch (Caffe::mode()) + } + //const vector*>& output_blobs = net_->ForwardPrefilled(); + net_->ForwardPrefilled(); +} +*/ + +static p_vect_float copy_output_blob_data( uint32_t const output_blob_ix ) +{ + + const vector*>& output_blobs = net_->output_blobs(); + if( ! (output_blob_ix < output_blobs.size() ) ) { + LOG(FATAL) << "!(output_blobs_ix < output_blobs.size())"; + } + Blob * const output_blob = output_blobs[output_blob_ix]; + + int batchsize = net_->output_blobs()[0]->num(); + int depth = net_->output_blobs()[0]->channels(); + int width = net_->output_blobs()[0]->width(); + int height = net_->output_blobs()[0]->height(); + mwSize dims[4] = {batchsize, width, height, depth}; + + if( sz_from_dims( 4, dims ) != (uint32_t)output_blob->count() ) { + LOG(FATAL) << "sz_from_dims( 4, dims ) != output_blob->count()"; + } + p_vect_float ret = make_p_vect_float( (uint32_t)output_blob->count() ); + float * const dest = &ret->front(); + switch (Caffe::mode()) { + case Caffe::CPU: memcpy(dest, output_blob->cpu_data(), sizeof(float) * ret->size() ); break; + case Caffe::GPU: cudaMemcpy(dest, output_blob->gpu_data(), sizeof(float) * ret->size(), cudaMemcpyDeviceToHost); break; + default: LOG(FATAL) << "Unknown Caffe mode."; + } // switch (Caffe::mode()) + return ret; +} + + // The caffe::Caffe utility functions. static void set_mode_cpu(MEX_ARGS) { Caffe::set_mode(Caffe::CPU); @@ -114,12 +203,17 @@ static void set_device(MEX_ARGS) { Caffe::SetDevice(device_id); } + static void init(MEX_ARGS) { + // this isn't good enough, but it's better than nothing. see + // https://code.google.com/p/google-glog/issues/detail?id=113 + static bool glog_is_init = 0; + if( !glog_is_init ) { google::InitGoogleLogging("matcaffe"); glog_is_init=1; } + if (nrhs != 2) { LOG(ERROR) << "Only given " << nrhs << " arguments"; mexErrMsgTxt("Wrong number of arguments"); } - char* param_file = mxArrayToString(prhs[0]); char* model_file = mxArrayToString(prhs[1]); @@ -130,6 +224,21 @@ static void init(MEX_ARGS) { mxFree(model_file); } + +static void is_init(MEX_ARGS) { + if ( (nrhs != 0) ) { + LOG(ERROR) << "Given " << nrhs << " arguments, expected 0."; + mexErrMsgTxt("Wrong number of arguments"); + } + if (nlhs != 1) { + LOG(ERROR) << "Caller wanted " << nlhs << " outputs, but this function always produces 1."; + mexErrMsgTxt("Wrong number of outputs"); + } + bool ret = (bool)net_; //null check + plhs[0] = u32_to_mx(ret); +} + + static void forward(MEX_ARGS) { if (nrhs != 1) { LOG(ERROR) << "Only given " << nrhs << " arguments"; @@ -139,6 +248,215 @@ static void forward(MEX_ARGS) { plhs[0] = do_forward(prhs[0]); } + +void check_dims_equal( uint32_t const num_dims, uint32_t const * const dims_a, uint32_t const * const dims_b ) { + bool dims_eq = 1; + for( uint32_t dim = 0; dim < num_dims; ++dim ) { if( dims_a[dim] != dims_b[dim] ) { dims_eq = 0; } } + if( !dims_eq ) { throw( std::runtime_error( "dims unequal" ) ); } +} + +void check_input_blobs_dims( uint32_t const num_dims, uint32_t const * const dims_b ) +{ + if( num_dims != 4 ) { throw( std::runtime_error( "wrong # dims" ) ); } + int batchsize = net_->input_blobs()[0]->num(); + int depth = net_->input_blobs()[0]->channels(); + int width = net_->input_blobs()[0]->width(); + int height = net_->input_blobs()[0]->height(); + uint32_t dims[4] = {batchsize, depth, height, width}; + check_dims_equal( 4, dims, dims_b ); +} + +p_vect_float p_vect_float_from_output_blob_0( void ) { + if( net_->num_outputs() != 1 ) { + LOG(FATAL) << "expecting 1 output blob, but got " << net_->num_outputs(); + } + int batchsize = net_->output_blobs()[0]->num(); + if( batchsize != 1 ) { + LOG(FATAL) << "expecting batchsize=1, but got batchsize=" << batchsize; + } + return copy_output_blob_data( 0 ); +} + +p_vect_float JPEGImage_to_p_float( JPEGImage &jpeg ){ + int depth = jpeg.depth(); + int height = jpeg.height(); + int width = jpeg.width(); + int batchsize = 1; + uint32_t dims[4] = {batchsize, depth, height, width}; + check_input_blobs_dims( 4, dims ); + + uint32_t const ret_sz = sz_from_dims( 4U, dims ); + p_vect_float ret = make_p_vect_float( ret_sz ); + uint8_t* jpegPtr = jpeg.bits(); + + //copy jpeg into jpeg_float_npy + for(int ch_src=0; ch_srcsize()); + ret->at(rix) = jpegPtr[y*width*depth + x*depth + ch_src] - ch_mean; + } + } + } + return ret; +} + +// @param out output a list of mxArray *'s, one list element per scale, each holding a 3D numeric array of the features +// @param scaleLocs = location of each scale on planes (see unstitch_pyramid_locations in PyramidStitcher.cpp) +// @param descriptor_planes -- each element of the list is a plane of Caffe descriptors +// typically, descriptor_planes = blobs_top. +// @param depth = #channels (typically 256 for conv5) +static mxArray * unstitch_planes( vector const & scaleLocs, vect_p_vect_float const & descriptor_planes, int depth) { + uint32_t const nbScales = scaleLocs.size(); + mxArray * const ret = mxCreateCellMatrix( nbScales, 1 ); + assert( ret ); + + for(uint32_t i=0; ioutput_blobs()[0]->channels(); + uint32_t width = net_->output_blobs()[0]->width(); + uint32_t height = net_->output_blobs()[0]->height(); + + int planeID = scaleLocs[i].planeID; + assert( uint32_t(planeID) < descriptor_planes.size() ); + p_vect_float dp = descriptor_planes[planeID]; + + uint32_t const dp_dims[3] = {width,height,depth}; + + // row-major / C / numpy / caffe dims (note: the matlab dims of descriptor_planes are (correctly) the reverse of this) + // dims[3] = {depth, height, width}; + + mwSize ret_dims[3] = {depth, scaleLocs[i].height, scaleLocs[i].width }; // desired column-major / F / matlab dims + mxArray * const ret_scale = mxCreateNumericArray( 3, ret_dims, mxSINGLE_CLASS, mxREAL ); + float * const ret_scale_data = (float * )mxGetData( ret_scale ); + mwSize ret_sz = sz_from_dims( 3, ret_dims ); + for( uint32_t x = 0; x < uint32_t(ret_dims[2]); ++x ) { + for( uint32_t y = 0; y < uint32_t(ret_dims[1]); ++y ) { + for( uint32_t d = 0; d < uint32_t(ret_dims[0]); ++d ) { + uint32_t const rix = d + y*ret_dims[0] + x*ret_dims[0]*ret_dims[1]; + assert( rix < uint32_t(ret_sz) ); + uint32_t const dp_x = x + scaleLocs[i].xMin; + uint32_t const dp_y = y + scaleLocs[i].yMin; + uint32_t const dp_ix = dp_x + dp_y*dp_dims[0] + d*dp_dims[0]*dp_dims[1]; + //ret_scale_data[rix] = float(d) + 1000.0*y + 1000000.0*x; + if( dp_ix >= dp->size() ) { + printf( "x=%s scaleLocs[i].xMin=%s y=%s scaleLocs[i].yMin=%s scaleLocs[i].height=%s scaleLocs[i].width=%s\n", str(x).c_str(), str(scaleLocs[i].xMin).c_str(), str(y).c_str(), str(scaleLocs[i].yMin).c_str(), str(scaleLocs[i].height).c_str(), str(scaleLocs[i].width).c_str() ); + printf( "dp_ix=%s dp->size()=%s dp_x=%s width=%s dp_y=%s height=%s d=%s depth=%s\n", str(dp_ix).c_str(), str(dp->size()).c_str(), str(dp_x).c_str(), str(width).c_str(), str(dp_y).c_str(), str(height).c_str(), str(d).c_str(), str(depth).c_str() ); + } + assert(dp_ix < dp->size()); + ret_scale_data[rix] = dp->at(dp_ix); + } + } + } + mxSetCell( ret, i, ret_scale ); + } + return ret; +} + + + +char const * fnames[] = { "scales", "feat", "imwidth", "imheight", "feat_padx", "feat_pady", "sbin" }; + +static void convnet_featpyramid(MEX_ARGS) { + + if ( !net_ ) { + LOG(ERROR) << "convnet was not initialized. please call 'init' and select CPU or GPU mode."; + mexErrMsgTxt("convnet was not initialized. please call 'init' and select CPU or GPU mode."); + } + if ( (nrhs < 1) || (nrhs > 2) ) { + LOG(ERROR) << "Given " << nrhs << " arguments, expected 1 or 2."; + mexErrMsgTxt("Wrong number of arguments"); + } + if (nlhs != 1) { + LOG(ERROR) << "Caller wanted " << nlhs << " outputs, but this function always produces 1."; + mexErrMsgTxt("Wrong number of outputs"); + } + char *fn_cs = mxArrayToString(prhs[0]); + if( !fn_cs ) { mexErrMsgTxt("Could not convert first argument to a string."); } + string const file( fn_cs ); + mxFree(fn_cs); + + + densenet_params_t params; // ctor sets params to defaults + + if( nrhs > 1 ) { // (try to) parse second arg as params + mxArray const * const mx_params = prhs[1]; + if( !mxIsStruct( mx_params ) ) { + mexErrMsgTxt("Expected second argument to be a struct, but it was not."); } + uint32_t const npes = mxGetNumberOfElements( mx_params ); + if( npes != 1 ) { + mexErrMsgTxt(("Expected second argument to be a struct with one element, but it had " + str(npes) + ".").c_str()); } + uint32_t const nf = mxGetNumberOfFields( mx_params ); + for( uint32_t fi = 0; fi != nf; ++fi ) { + char const * const fn = mxGetFieldNameByNumber( mx_params, fi ); + assert( fn ); + mxArray const * const mx_f = mxGetFieldByNumber( mx_params, 0, fi ); + assert( mx_f ); + if( 0 ) { } + else if( !strcmp( fn, "interval" ) ) { params.interval = mx_to_u32( "for param interval", mx_f ); } + else if( !strcmp( fn, "img_padding" ) ) { params.img_padding = mx_to_u32( "for param img_padding", mx_f ); } + else if( !strcmp( fn, "feat_minHeight" ) ) { params.feat_minHeight = mx_to_u32( "for param feat_minHeight", mx_f ); } + else if( !strcmp( fn, "feat_minWidth" ) ) { params.feat_minWidth = mx_to_u32( "for param feat_minWidth", mx_f ); } + else { mexErrMsgTxt( ("unknown parameter " + string(fn) ).c_str() ); } + } + } + + int sbin = get_sbin(net_); //for conv5 layer features + int planeDim = net_->input_blobs()[0]->width(); //assume that all preallocated blobs are same size + int resultDepth = net_->output_blobs()[0]->channels(); + + uint32_t const img_minHeight = params.feat_minHeight * sbin; + uint32_t const img_minWidth = params.feat_minWidth * sbin; + + assert(net_->input_blobs()[0]->width() == net_->input_blobs()[0]->height()); //assume square planes in Caffe. (can relax this if necessary) + assert(net_->input_blobs()[0]->num() == 1); //for now, one plane at a time.) + //TODO: verify/assert that top-upsampled version of input img fits within planeDim + + Patchwork patchwork = stitch_pyramid(file, img_minWidth, img_minHeight, params.img_padding, params.interval, planeDim); + int nbPlanes = patchwork.planes_.size(); + + vect_p_vect_float blobs_top; + //prep input data for Caffe feature extraction + for(int planeID=0; planeID scaleLocations = unstitch_pyramid_locations(patchwork, sbin); + uint32_t const ret_rows = patchwork.scales_.size(); + assert( scaleLocations.size() == ret_rows ); + + mxArray * const feats = unstitch_planes( scaleLocations, blobs_top, resultDepth ); + mxArray * const scale = mxCreateNumericMatrix( ret_rows, 1, mxSINGLE_CLASS, mxREAL ); + float * const scale_ptr = (float*)(mxGetData(scale)); + for( uint32_t r = 0; r < ret_rows; ++r ) { scale_ptr[r] = patchwork.scales_[r]; } + + int feat_padx = params.img_padding / sbin; + int feat_pady = params.img_padding / sbin; + + mxArray * ret = mxCreateStructMatrix( 1, 1, sizeof(fnames)/sizeof(char*), fnames ); // see fnames for field names + mxSetFieldByNumber( ret, 0, 0, scale ); + mxSetFieldByNumber( ret, 0, 1, feats ); + mxSetFieldByNumber( ret, 0, 2, u32_to_mx( patchwork.imwidth_ ) ); + mxSetFieldByNumber( ret, 0, 3, u32_to_mx( patchwork.imheight_ ) ); + mxSetFieldByNumber( ret, 0, 4, u32_to_mx( feat_padx ) ); + mxSetFieldByNumber( ret, 0, 5, u32_to_mx( feat_pady ) ); + mxSetFieldByNumber( ret, 0, 6, u32_to_mx( sbin ) ); + + plhs[0] = ret; +} + + /** ----------------------------------------------------------------- ** Available commands. **/ @@ -151,15 +469,21 @@ static handler_registry handlers[] = { // Public API functions { "forward", forward }, { "init", init }, + { "is_init", is_init }, { "set_mode_cpu", set_mode_cpu }, { "set_mode_gpu", set_mode_gpu }, { "set_phase_train", set_phase_train }, { "set_phase_test", set_phase_test }, { "set_device", set_device }, + // featpyramid functions + { "convnet_featpyramid",convnet_featpyramid }, + // The end. { "END", NULL }, }; +// building with mkoctfile +// cd ~/git_work/caffe ; CXXFLAGS="-Wall -fpic -O2" mkoctfile --mex matlab/caffe/matcaffe.cpp libcaffe.a -pthread -I/usr/local/include -I/usr/include/python2.7 -I/usr/local/lib/python2.7/dist-packages/numpy/core/include -I./src -I./include -I/usr/local/cuda/include -I/opt/intel/mkl/include -Wall -L/usr/lib -L/usr/local/lib -L/usr/local/cuda/lib64 -L/usr/local/cuda/lib -L/opt/intel/mkl/lib -L/opt/intel/mkl/lib/intel64 -lcudart -lcublas -lcurand -lprotobuf -lopencv_core -lopencv_highgui -lglog -lmkl_rt -lmkl_intel_thread -lleveldb -lsnappy -lpthread -lboost_system -lopencv_imgproc -L/home/moskewcz/git_work/caffe/python/caffe/stitch_pyramid -lPyramidStitcher -I./python/caffe -o matlab/caffe/caffe /** ----------------------------------------------------------------- ** matlab entry point: caffe(api_command, arg1, arg2, ...) diff --git a/matlab/caffe/pascal_000001.jpg b/matlab/caffe/pascal_000001.jpg new file mode 100644 index 00000000000..a1373660198 Binary files /dev/null and b/matlab/caffe/pascal_000001.jpg differ diff --git a/matlab/caffe/test_get_featureSlice.m b/matlab/caffe/test_get_featureSlice.m new file mode 100644 index 00000000000..ae9575dbc46 --- /dev/null +++ b/matlab/caffe/test_get_featureSlice.m @@ -0,0 +1,50 @@ + +function test_getFeatureSlice() + + %TODO: add voc-release5/features to path. + addpath('../../voc-release5/bin') + addpath('../../voc-release5/features') + addpath('../../voc-release5/vis') + + im = imread('./pascal_000001.jpg'); + + %bare bones model to run DPM's HOG code + model.sbin = 4; + %model.features.sbin = model.sbin; + model.padx = 8; + model.pady = 8; + model.interval = 10; + model.features.extra_octave = 0; + model.features.dim = 32; + model.features.truncation_dim = 32; + + pyra = featpyramid(im, model, model.padx, model.pady); + + templateSize = [6 10]; + imageSize = size(im); + bbox.x1 = 110; + bbox.x2 = 190; + bbox.y1 = 100; + bbox.y2 = 148; + + pyra.sbin = model.sbin; + [featureSlice, scaleIdx] = get_featureSlice(pyra, bbox, templateSize); + + % if using convnets... + %figure(1) + %colormap(gray); + %imagesc(sum(featureSlice,3)) + + % if using HOG... + figure(2) + w = foldHOG(featureSlice); + visualizeHOG(w); + + figure(3); + w = foldHOG(pyra.feat{scaleIdx}); + visualizeHOG(w); + +end + + + diff --git a/python/caffe/featpyramid_demo.py b/python/caffe/featpyramid_demo.py new file mode 100644 index 00000000000..9cee5f1c3f5 --- /dev/null +++ b/python/caffe/featpyramid_demo.py @@ -0,0 +1,73 @@ +''' +test cases for multiscale pyramids of Convnet features. + + used power_wrapper.py as a starting point. +''' + +import numpy as np +import os +import sys +#import gflags +import time +import caffe + +#for visualization, can be removed easily: +from matplotlib import cm, pyplot +import pylab + +def test_featpyramid_allScales(caffenet, imgFname): + + densenet_params = dict() + densenet_params['interval'] = 10 + densenet_params['img_padding'] = 16 + densenet_params['feat_minWidth'] = 10 #smallest desired scale, in terms of feature map dims + densenet_params['feat_minHeight'] = 10 + + start_time = time.time() + pyra = caffenet.extract_featpyramid(imgFname, densenet_params) # THE CRUX ... + # pyra = caffenet.extract_featpyramid(imgFname) # ... or THE CRUX without parameters + pyra_time = time.time() - start_time + print " computed pyra in %f sec" %pyra_time + + feat = pyra["feat"] + + output_dir = 'output_pyra' + try: + os.makedirs( output_dir ) + except OSError, e: + pass + + for i in xrange(0, len(feat)): + print 'feat[%d] shape: '%i + print feat[i].shape + + #prep for visualization (sum over depth of descriptors) + flat_descriptor = np.sum(feat[i], axis=1) #e.g. (1, depth=256, height=124, width=124) -> (1, 124, 124) + flat_descriptor = flat_descriptor[0] #(1, 124, 124) -> (124, 124) ... first image (in a batch size of 1) + + #visualization + pyplot.figure() + pyplot.title('Welcome to deep learning land. You have arrived.') + pyplot.imshow(flat_descriptor, cmap = cm.gray, interpolation='nearest') + pylab.savefig( output_dir + '/flat_descriptor_scale%d.jpg' % i) + + print "\n pyra scales:" + print pyra["scales"] + print "pyra[imwidth] = %d, pyra[imheight]=%d" % (pyra['imwidth'], pyra['imheight']) + +if __name__ == "__main__": + + imgFname = './imagenet/pascal_009959.jpg' + model_def = './imagenet/imagenet_rcnn_batch_1_input_2000x2000_output_conv5.prototxt' + pretrained_model = '../../examples/alexnet_train_iter_470000' + use_gpu = False + #use_gpu = True + + caffenet = caffe.CaffeNet(model_def, pretrained_model) + caffenet.set_phase_test() + if use_gpu: + caffenet.set_mode_gpu() + else: + caffenet.set_mode_cpu() + + test_featpyramid_allScales(caffenet, imgFname) diff --git a/python/caffe/imagenet/featpyramid_tests.py b/python/caffe/imagenet/featpyramid_tests.py new file mode 100644 index 00000000000..31250eb5a28 --- /dev/null +++ b/python/caffe/imagenet/featpyramid_tests.py @@ -0,0 +1,101 @@ +''' +test cases for multiscale pyramids of Convnet features. + + used power_wrapper.py as a starting point. +''' + +import numpy as np +import os +import sys +import gflags +import time +import caffe +import time + +#for visualization, can be removed easily: +from matplotlib import cm, pyplot +import pylab + +#parameters to consider passing to C++ Caffe::featpyramid... +# image filename +# num scales (or something to control this) +# padding amount +# [batchsize is defined in prototxt... fine.] + +#hopefully caffenet is passed by ref... +def test_pyramid_IO(caffenet, imgFname): + #example_np_array = caffenet.testIO() #just return an array with 1 2 3 4... + example_np_array = caffenet.test_NumpyView() + + print example_np_array + print example_np_array[0].shape + + caffenet.testString('hi') + caffenet.testInt(1337) + + print "\n example dict from C++:" + example_dict = caffenet.test_return_dict() + print example_dict + +def test_featpyramid_allScales(caffenet, imgFname): + + densenet_params = dict() + densenet_params['interval'] = 10 + densenet_params['img_padding'] = 16 + densenet_params['feat_minWidth'] = 10 #smallest desired scale, in terms of feature map dims + densenet_params['feat_minHeight'] = 10 + + start_time = time.time() + pyra = caffenet.extract_featpyramid(imgFname, densenet_params) # THE CRUX ... + # pyra = caffenet.extract_featpyramid(imgFname) # ... or THE CRUX without parameters + pyra_time = time.time() - start_time + print " computed pyra in %f sec" %pyra_time + + feat = pyra["feat"] + + # optional breakpoint... + #from IPython import embed + #embed() + output_dir = 'output_pyra' + try: + os.makedirs( output_dir ) + except OSError, e: + pass + + for i in xrange(0, len(feat)): + print 'feat[%d] shape: '%i + print feat[i].shape + + #prep for visualization (sum over depth of descriptors) + flat_descriptor = np.sum(feat[i], axis=1) #e.g. (1, depth=256, height=124, width=124) -> (1, 124, 124) + flat_descriptor = flat_descriptor[0] #(1, 124, 124) -> (124, 124) ... first image (in a batch size of 1) + + #visualization + pyplot.figure() + pyplot.title('Welcome to deep learning land. You have arrived.') + pyplot.imshow(flat_descriptor, cmap = cm.gray, interpolation='nearest') + pylab.savefig( output_dir + '/flat_descriptor_scale%d.jpg' % i) + + print "\n pyra scales:" + print pyra["scales"] + print "pyra[imwidth] = %d, pyra[imheight]=%d" % (pyra['imwidth'], pyra['imheight']) + +if __name__ == "__main__": + + #pretend that these flags came off the command line: + imgFname = './pascal_009959.jpg' + #imgFname = '/media/big_disk/datasets/INRIA_PASCAL_jpg/VOCdevkit/VOC2007/Images/crop001002.jpg' + #model_def = '../../../examples/imagenet_deploy.prototxt' + model_def = './imagenet_rcnn_batch_1_input_2000x2000_output_conv5.prototxt' + pretrained_model = '../../../examples/alexnet_train_iter_470000' + use_gpu = True + + caffenet = caffe.CaffeNet(model_def, pretrained_model) + caffenet.set_phase_test() + if use_gpu: + caffenet.set_mode_gpu() + + + #experiments... + #test_pyramid_IO(caffenet, imgFname) + test_featpyramid_allScales(caffenet, imgFname) diff --git a/python/caffe/imagenet/imagenet_rcnn_batch_1_input_1100x1100_output_conv5.prototxt b/python/caffe/imagenet/imagenet_rcnn_batch_1_input_1100x1100_output_conv5.prototxt new file mode 100644 index 00000000000..064dd1cd3ab --- /dev/null +++ b/python/caffe/imagenet/imagenet_rcnn_batch_1_input_1100x1100_output_conv5.prototxt @@ -0,0 +1,208 @@ +name: "DenseNet_1100" +input: "data" +input_dim: 1 +input_dim: 3 +input_dim: 1100 +input_dim: 1100 +layers { + layer { + name: "conv1" + type: "conv" + num_output: 96 + kernelsize: 11 + stride: 4 + weight_filler { + type: "gaussian" + std: 0.01 + } + bias_filler { + type: "constant" + value: 0. + } + blobs_lr: 1. + blobs_lr: 2. + weight_decay: 1. + weight_decay: 0. + } + bottom: "data" + top: "conv1" +} +layers { + layer { + name: "relu1" + type: "relu" + } + bottom: "conv1" + top: "conv1" +} +layers { + layer { + name: "pool1" + type: "pool" + pool: MAX + kernelsize: 3 + stride: 2 + } + bottom: "conv1" + top: "pool1" +} +layers { + layer { + name: "norm1" + type: "lrn" + local_size: 5 + alpha: 0.0001 + beta: 0.75 + } + bottom: "pool1" + top: "norm1" +} +layers { + layer { + name: "conv2" + type: "conv" + num_output: 256 + group: 2 + kernelsize: 5 + pad: 2 + weight_filler { + type: "gaussian" + std: 0.01 + } + bias_filler { + type: "constant" + value: 1. + } + blobs_lr: 1. + blobs_lr: 2. + weight_decay: 1. + weight_decay: 0. + } + bottom: "norm1" + top: "conv2" +} +layers { + layer { + name: "relu2" + type: "relu" + } + bottom: "conv2" + top: "conv2" +} +layers { + layer { + name: "pool2" + type: "pool" + pool: MAX + kernelsize: 3 + stride: 2 + } + bottom: "conv2" + top: "pool2" +} +layers { + layer { + name: "norm2" + type: "lrn" + local_size: 5 + alpha: 0.0001 + beta: 0.75 + } + bottom: "pool2" + top: "norm2" +} +layers { + layer { + name: "conv3" + type: "conv" + num_output: 384 + kernelsize: 3 + pad: 1 + weight_filler { + type: "gaussian" + std: 0.01 + } + bias_filler { + type: "constant" + value: 0. + } + blobs_lr: 1. + blobs_lr: 2. + weight_decay: 1. + weight_decay: 0. + } + bottom: "norm2" + top: "conv3" +} +layers { + layer { + name: "relu3" + type: "relu" + } + bottom: "conv3" + top: "conv3" +} +layers { + layer { + name: "conv4" + type: "conv" + num_output: 384 + group: 2 + kernelsize: 3 + pad: 1 + weight_filler { + type: "gaussian" + std: 0.01 + } + bias_filler { + type: "constant" + value: 1. + } + blobs_lr: 1. + blobs_lr: 2. + weight_decay: 1. + weight_decay: 0. + } + bottom: "conv3" + top: "conv4" +} +layers { + layer { + name: "relu4" + type: "relu" + } + bottom: "conv4" + top: "conv4" +} +layers { + layer { + name: "conv5" + type: "conv" + num_output: 256 + group: 2 + kernelsize: 3 + pad: 1 + weight_filler { + type: "gaussian" + std: 0.01 + } + bias_filler { + type: "constant" + value: 1. + } + blobs_lr: 1. + blobs_lr: 2. + weight_decay: 1. + weight_decay: 0. + } + bottom: "conv4" + top: "conv5" +} +layers { + layer { + name: "relu5" + type: "relu" + } + bottom: "conv5" + top: "conv5" +} \ No newline at end of file diff --git a/python/caffe/imagenet/imagenet_rcnn_batch_1_input_2000x2000_output_conv5.prototxt b/python/caffe/imagenet/imagenet_rcnn_batch_1_input_2000x2000_output_conv5.prototxt new file mode 100644 index 00000000000..d78501d98ba --- /dev/null +++ b/python/caffe/imagenet/imagenet_rcnn_batch_1_input_2000x2000_output_conv5.prototxt @@ -0,0 +1,208 @@ +name: "DenseNet_2000" +input: "data" +input_dim: 1 +input_dim: 3 +input_dim: 2000 +input_dim: 2000 +layers { + layer { + name: "conv1" + type: "conv" + num_output: 96 + kernelsize: 11 + stride: 4 + weight_filler { + type: "gaussian" + std: 0.01 + } + bias_filler { + type: "constant" + value: 0. + } + blobs_lr: 1. + blobs_lr: 2. + weight_decay: 1. + weight_decay: 0. + } + bottom: "data" + top: "conv1" +} +layers { + layer { + name: "relu1" + type: "relu" + } + bottom: "conv1" + top: "conv1" +} +layers { + layer { + name: "pool1" + type: "pool" + pool: MAX + kernelsize: 3 + stride: 2 + } + bottom: "conv1" + top: "pool1" +} +layers { + layer { + name: "norm1" + type: "lrn" + local_size: 5 + alpha: 0.0001 + beta: 0.75 + } + bottom: "pool1" + top: "norm1" +} +layers { + layer { + name: "conv2" + type: "conv" + num_output: 256 + group: 2 + kernelsize: 5 + pad: 2 + weight_filler { + type: "gaussian" + std: 0.01 + } + bias_filler { + type: "constant" + value: 1. + } + blobs_lr: 1. + blobs_lr: 2. + weight_decay: 1. + weight_decay: 0. + } + bottom: "norm1" + top: "conv2" +} +layers { + layer { + name: "relu2" + type: "relu" + } + bottom: "conv2" + top: "conv2" +} +layers { + layer { + name: "pool2" + type: "pool" + pool: MAX + kernelsize: 3 + stride: 2 + } + bottom: "conv2" + top: "pool2" +} +layers { + layer { + name: "norm2" + type: "lrn" + local_size: 5 + alpha: 0.0001 + beta: 0.75 + } + bottom: "pool2" + top: "norm2" +} +layers { + layer { + name: "conv3" + type: "conv" + num_output: 384 + kernelsize: 3 + pad: 1 + weight_filler { + type: "gaussian" + std: 0.01 + } + bias_filler { + type: "constant" + value: 0. + } + blobs_lr: 1. + blobs_lr: 2. + weight_decay: 1. + weight_decay: 0. + } + bottom: "norm2" + top: "conv3" +} +layers { + layer { + name: "relu3" + type: "relu" + } + bottom: "conv3" + top: "conv3" +} +layers { + layer { + name: "conv4" + type: "conv" + num_output: 384 + group: 2 + kernelsize: 3 + pad: 1 + weight_filler { + type: "gaussian" + std: 0.01 + } + bias_filler { + type: "constant" + value: 1. + } + blobs_lr: 1. + blobs_lr: 2. + weight_decay: 1. + weight_decay: 0. + } + bottom: "conv3" + top: "conv4" +} +layers { + layer { + name: "relu4" + type: "relu" + } + bottom: "conv4" + top: "conv4" +} +layers { + layer { + name: "conv5" + type: "conv" + num_output: 256 + group: 2 + kernelsize: 3 + pad: 1 + weight_filler { + type: "gaussian" + std: 0.01 + } + bias_filler { + type: "constant" + value: 1. + } + blobs_lr: 1. + blobs_lr: 2. + weight_decay: 1. + weight_decay: 0. + } + bottom: "conv4" + top: "conv5" +} +layers { + layer { + name: "relu5" + type: "relu" + } + bottom: "conv5" + top: "conv5" +} \ No newline at end of file diff --git a/python/caffe/imagenet/pascal_009959.jpg b/python/caffe/imagenet/pascal_009959.jpg new file mode 100644 index 00000000000..e3317750b85 Binary files /dev/null and b/python/caffe/imagenet/pascal_009959.jpg differ diff --git a/python/caffe/pycaffe.cpp b/python/caffe/pycaffe.cpp index c32194ef998..37fd3980852 100644 --- a/python/caffe/pycaffe.cpp +++ b/python/caffe/pycaffe.cpp @@ -7,12 +7,16 @@ #include "boost/python.hpp" #include "boost/python/suite/indexing/vector_indexing_suite.hpp" +#include #include "numpy/arrayobject.h" #include // NOLINT(build/include_order) #include // NOLINT(build/include_order) #include "caffe/caffe.hpp" +#include "caffe/imagenet_mean.hpp" +#include "stitch_pyramid/PyramidStitcher.h" //also includes JPEGImage, Patchwork, etc +#include "caffe/featpyra_common.hpp" // Temporary solution for numpy < 1.7 versions: old macro, no promises. // You're strongly advised to upgrade to >= 1.7. @@ -26,11 +30,19 @@ using namespace caffe; // NOLINT(build/namespaces) using boost::python::extract; using boost::python::len; using boost::python::list; +using boost::python::dict; using boost::python::object; using boost::python::handle; using boost::python::vector_indexing_suite; +//TODO: remove... or agree on a good timer. +double read_timer_forPycaffe(){ + struct timeval start; + gettimeofday( &start, NULL ); + return (double)((start.tv_sec) + 1.0e-6 * (start.tv_usec)); //in seconds +} + // wrap shared_ptr > in a class that we construct in C++ and pass // to Python class CaffeBlob { @@ -216,6 +228,317 @@ struct CaffeNet { } } + //float* -> numpy -> boost python (which can be returned to Python) + boost::python::object array_to_boostPython_4d(float* pyramid_float, + int batchsize, int depth_, int MaxHeight_, int MaxWidth_) + { + + npy_intp dims[4] = {batchsize, depth_, MaxHeight_, MaxWidth_}; //in floats + PyArrayObject* pyramid_float_npy = (PyArrayObject*)PyArray_New( &PyArray_Type, 4, dims, NPY_FLOAT, 0, pyramid_float, 0, 0, 0 ); //not specifying strides + + //thanks: stackoverflow.com/questions/19185574 + boost::python::object pyramid_float_npy_boost(boost::python::handle<>((PyObject*)pyramid_float_npy)); + return pyramid_float_npy_boost; + } + + // for now, one batch at a time. (later, can modify this to allocate & fill a >1 batch 4d array) + // @param jpeg = typically a plane from Patchwork, in packed JPEG [RGB,RGB,RGB] format + // @return numpy float array of jpeg, in unpacked [BBBBB..,GGGGG..,RRRRR..] format with channel mean subtracted + PyArrayObject* JPEGImage_to_numpy_float(JPEGImage &jpeg){ + + int depth = jpeg.depth(); + int height = jpeg.height(); + int width = jpeg.width(); + int batchsize = 1; + npy_intp dims[4] = {batchsize, depth, height, width}; + + PyArrayObject* jpeg_float_npy = (PyArrayObject*)PyArray_New( &PyArray_Type, 4, dims, NPY_FLOAT, 0, 0, 0, 0, 0 ); //numpy malloc + + uint8_t* jpegPtr = jpeg.bits(); + + //copy jpeg into jpeg_float_npy + for(int ch_src=0; ch_srcoutput_blobs()[0]->num(); + int depth = net_->output_blobs()[0]->channels(); + int width = net_->output_blobs()[0]->width(); + int height = net_->output_blobs()[0]->height(); + npy_intp dims[4] = {batchsize, depth, height, width}; + printf(" in allocate_resultPlane(). OUTPUT_BLOBS... batchsize=%d, depth=%d, width=%d, height=%d \n", batchsize, depth, width, height); + + PyArrayObject* resultPlane = (PyArrayObject*)PyArray_New( &PyArray_Type, 4, dims, NPY_FLOAT, 0, 0, 0, 0, 0 ); //numpy malloc + return resultPlane; + } + + //pull list of scales out of patchwork; pack it into boost::python array + boost::python::object get_scales_boost(Patchwork patchwork){ + vector scales = patchwork.scales_; + int dim = scales.size(); + npy_intp dims[1] = {dim}; + + PyArrayObject* scales_npy = (PyArrayObject*)PyArray_New( &PyArray_Type, 1, dims, NPY_FLOAT, 0, 0, 0, 0, 0 ); //malloc new memory + for(int i=0; i((PyObject*)scales_npy)); + + return scales_npy_boost; + } + + // @param scaleLocs = location of each scale on planes (see unstitch_pyramid_locations in PyramidStitcher.cpp) + // @param descriptor_planes -- each element of the list is a plane of Caffe descriptors + // typically, descriptor_planes = blobs_top. + // @param depth = #channels (typically 256 for conv5) + // @return a list of numpy 'views', one list element per scale. + boost::python::list unstitch_planes(vector scaleLocs, boost::python::list descriptor_planes, int depth){ + + boost::python::list unstitched_features; + int nbScales = scaleLocs.size(); + int batchsize = 1; //TODO: assert that batchsize really is 1. + + for(int i=0; i((PyObject*)view_npy)); + unstitched_features.append(view_npy_boost); + } + + return unstitched_features; + } + + //void extract_featpyramid(string file){ + boost::python::dict extract_featpyramid(string file, dict params_dict = dict() ){ + + int sbin = get_sbin(net_); //for conv5 layer features + int planeDim = net_->input_blobs()[0]->width(); //assume that all preallocated blobs are same size + int resultDepth = net_->output_blobs()[0]->channels(); + + densenet_params_t params; // ctor sets params to defaults + list params_keys = params_dict.keys(); + for( uint32_t i = 0; i < len(params_keys); ++i) { + string const fn = extract(params_keys[i]); + object val = params_dict[params_keys[i]]; + if( 0 ) { } + else if( fn == "interval" ) { params.interval = extract(val); } + else if( fn == "img_padding" ) { params.img_padding = extract(val); } + else if( fn == "feat_minHeight" ) { params.feat_minHeight = extract(val); } + else if( fn == "feat_minWidth" ) { params.feat_minWidth = extract(val); } + else { throw runtime_error("unknown parameter " + string(fn) ); } + } + uint32_t const img_minHeight = params.feat_minHeight * sbin; + uint32_t const img_minWidth = params.feat_minWidth * sbin; + + assert(net_->input_blobs()[0]->width() == net_->input_blobs()[0]->height()); //assume square planes in Caffe. (can relax this if necessary) + assert(net_->input_blobs()[0]->num() == 1); //for now, one plane at a time.) + //TODO: verify/assert that top-upsampled version of input img fits within planeDim + +double start_patchwork = read_timer_forPycaffe(); + Patchwork patchwork = stitch_pyramid(file, img_minWidth, img_minHeight, params.img_padding, params.interval, planeDim); +double time_patchwork = read_timer_forPycaffe() - start_patchwork; +printf(" patchwork: %f sec \n", time_patchwork); + + int nbPlanes = patchwork.planes_.size(); + + boost::python::list blobs_bottom; //input buffer(s) for Caffe::Forward + boost::python::list blobs_top; //output buffer(s) for Caffe::Forward + + //prep input data for Caffe feature extraction + for(int planeID=0; planeID((PyObject*)currPlane_npy)); //numpy -> wrap in boost + boost::python::list blobs_bottom_tmp; //input to Caffe::Forward + blobs_bottom_tmp.append(currPlane_npy_boost); //put the output array in list [list length = 1, because batchsize = 1] + blobs_bottom.append(currPlane_npy_boost); //for long-term keeping (return a list that might be longer than 1) + + //prep output space + PyArrayObject* resultPlane_npy = allocate_resultPlane(); //gets resultPlane dims from shared ptr to net_->output_blobs() + boost::python::object resultPlane_npy_boost(boost::python::handle<>((PyObject*)resultPlane_npy)); //numpy -> wrap in boost + boost::python::list blobs_top_tmp; //output buffer for Caffe::Forward + blobs_top_tmp.append(resultPlane_npy_boost); //put the output array in list [list length = 1, because batchsize = 1] + blobs_top.append(resultPlane_npy_boost); //for long-term keeping (return a list that might be longer than 1) + +double start_forward = read_timer_forPycaffe(); + Forward(blobs_bottom_tmp, blobs_top_tmp); //lists of blobs... bottom[0]=curr input planes, top_tmp[0]=curr output descriptors +double time_forward = read_timer_forPycaffe() - start_forward; +printf(" forward plane: %f sec \n\n", time_forward); + } + + printf("\n\n in pycaffe.cpp extract_featpyramid(). planeDim=%d\n", planeDim); + +//double start_unstitch = read_timer_forPycaffe(); + vector scaleLocations = unstitch_pyramid_locations(patchwork, sbin); + boost::python::list unstitched_features = unstitch_planes(scaleLocations, blobs_top, resultDepth); + boost::python::object scales_npy_boost = get_scales_boost(patchwork); +//double time_unstitch = read_timer_forPycaffe() - start_unstitch; +//printf(" unstitch planes: %f sec \n", time_unstitch); + + boost::python::dict d; + //d["blobs_bottom"] = blobs_bottom; //for debugging -- stitched pyra in RGB + //d["blobs_top"] = blobs_top; //for debugging -- stitched descriptors + d["feat"] = unstitched_features; + d["scales"] = scales_npy_boost; + d["imwidth"] = patchwork.imwidth_; //input image dims + d["imheight"] = patchwork.imheight_; + d["feat_padx"] = params.img_padding / sbin; + d["feat_pady"] = params.img_padding / sbin; + d["sbin"] = sbin; + + return d; + } + + //return a list containing one 4D numpy/boost array. (toy example) + boost::python::list testIO() + { + int batchsize = 1; + int depth_ = 1; + int MaxHeight_ = 10; + int MaxWidth_ = 10; + + //prepare data that we'll send to Python + float* pyramid_float = (float*)malloc(sizeof(float) * batchsize * depth_ * MaxHeight_ * MaxWidth_); + memset(pyramid_float, 0, sizeof(float) * batchsize * depth_ * MaxHeight_ * MaxWidth_); + pyramid_float[10] = 123; //test -- see if it shows up in Python + + boost::python::object pyramid_float_npy_boost = array_to_boostPython_4d(pyramid_float, batchsize, depth_, MaxHeight_, MaxWidth_); + + boost::python::list blobs_top_boost; //list to return + blobs_top_boost.append(pyramid_float_npy_boost); //put the output array in list + + return blobs_top_boost; + } + + boost::python::dict test_return_dict() + { + int batchsize = 1; + int depth_ = 1; + int MaxHeight_ = 3; + int MaxWidth_ = 3; + + //prepare data that we'll send to Python + float* pyramid_float = (float*)malloc(sizeof(float) * batchsize * depth_ * MaxHeight_ * MaxWidth_); + memset(pyramid_float, 0, sizeof(float) * batchsize * depth_ * MaxHeight_ * MaxWidth_); + pyramid_float[4] = 123; //test -- see if it shows up in Python + + boost::python::object pyramid_float_npy_boost = array_to_boostPython_4d(pyramid_float, batchsize, depth_, MaxHeight_, MaxWidth_); + boost::python::list blobs_top_boost; //list to return + blobs_top_boost.append(pyramid_float_npy_boost); //put the output array in list + + string myStr = "ohai"; + + boost::python::dict d; + d["pyramid"] = blobs_top_boost; + d["note"] = myStr; + + //return blobs_top_boost; + return d; + } + + //return a slice ("view") of a numpy array + boost::python::list test_NumpyView() + { + int batchsize = 1; + int depth_ = 3; + int MaxHeight_ = 10; + int MaxWidth_ = 10; + + //setup numpy array + float* pyramid_float = (float*)malloc(sizeof(float) * batchsize * depth_ * MaxHeight_ * MaxWidth_); + memset(pyramid_float, 0, sizeof(float) * batchsize * depth_ * MaxHeight_ * MaxWidth_); + + for(int i=0; i((PyObject*)view_npy)); + blobs_top_boost_view.append(view_npy_boost); + + return blobs_top_boost_view; //compile error: return-statement with no value + //return blobs_top_boost; + } + + + void testString(string st){ + printf(" string from python: %s \n", st.c_str()); + } + + void testInt(int i){ + printf(" int from python: %d \n", i); + } + // The caffe::Caffe utility functions. void set_mode_cpu() { Caffe::set_mode(Caffe::CPU); } void set_mode_gpu() { Caffe::set_mode(Caffe::GPU); } @@ -248,6 +571,7 @@ struct CaffeNet { shared_ptr > net_; }; +BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(CaffeNet_extract_featpyramid_overloads, CaffeNet::extract_featpyramid, 1, 2); // The boost python module definition. @@ -261,6 +585,12 @@ BOOST_PYTHON_MODULE(pycaffe) { .def("set_phase_train", &CaffeNet::set_phase_train) .def("set_phase_test", &CaffeNet::set_phase_test) .def("set_device", &CaffeNet::set_device) + .def("testIO", &CaffeNet::testIO) //Forrest's test (return a numpy array) + .def("test_NumpyView", &CaffeNet::test_NumpyView) //Forrest's test (return view of a numpy array) + .def("testString", &CaffeNet::testString) + .def("test_return_dict", &CaffeNet::test_return_dict) + .def("testInt", &CaffeNet::testInt) + .def("extract_featpyramid", &CaffeNet::extract_featpyramid, CaffeNet_extract_featpyramid_overloads()) //NEW .def("blobs", &CaffeNet::blobs) .def("params", &CaffeNet::params); diff --git a/src/caffe/net.cpp b/src/caffe/net.cpp index e976dfd5fd0..cd265a21de9 100644 --- a/src/caffe/net.cpp +++ b/src/caffe/net.cpp @@ -67,6 +67,7 @@ void Net::Init(const NetParameter& in_param) { const LayerParameter& layer_param = layer_connection.layer(); layers_.push_back(shared_ptr >(GetLayer(layer_param))); layer_names_.push_back(layer_param.name()); + layer_strides_.push_back(layer_param.has_stride()?layer_param.stride():0); LOG(INFO) << "Creating Layer " << layer_param.name(); bool need_backward = param.force_backward(); // Figure out this layer's input and output diff --git a/src/stitch_pyramid/COPYING.txt b/src/stitch_pyramid/COPYING.txt new file mode 100644 index 00000000000..94a9ed024d3 --- /dev/null +++ b/src/stitch_pyramid/COPYING.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/src/stitch_pyramid/JPEGImage.cpp b/src/stitch_pyramid/JPEGImage.cpp new file mode 100644 index 00000000000..4ac7328e43b --- /dev/null +++ b/src/stitch_pyramid/JPEGImage.cpp @@ -0,0 +1,390 @@ +//-------------------------------------------------------------------------------------------------- +// Implementation of the paper "Exact Acceleration of Linear Object Detectors", 12th European +// Conference on Computer Vision, 2012. +// +// Copyright (c) 2012 Idiap Research Institute, +// Written by Charles Dubout +// +// This file is part of FFLD (the Fast Fourier Linear Detector) +// +// FFLD is free software: you can redistribute it and/or modify it under the terms of the GNU +// General Public License version 3 as published by the Free Software Foundation. +// +// FFLD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +// Public License for more details. +// +// You should have received a copy of the GNU General Public License along with FFLD. If not, see +// . +//-------------------------------------------------------------------------------------------------- + +#include "JPEGImage.h" +#include "imagenet_mean.hpp" //contains hard-coded imagenet RGB mean. from Caffe. + +#include +#include + +#include +#include + +using namespace FFLD; +using namespace std; + +//thanks: http://stackoverflow.com/questions/11641629/generating-a-uniform-distribution-of-integers-in-c +//uniform_distribution returns an INTEGER in [rangeLow, rangeHigh], inclusive. +inline int uniform_distribution(int rangeLow, int rangeHigh) +{ + int myRand = (int)rand(); + int range = rangeHigh - rangeLow + 1; //+1 makes it [rangeLow, rangeHigh], inclusive. + int myRand_scaled = (myRand % range) + rangeLow; + return myRand_scaled; +} + +// THIS IS VERY SLOWWWW: +//to avoid hard borders on images in plane (which look like edges to the convnet) +void JPEGImage::fill_with_rand(){ + int height = this->height(); + int width = this->width(); + int depth = this->depth(); + + for (int y = 0; y < height; y++){ + for (int x = 0; x < width; x++){ + for (int ch = 0; ch < depth; ch++){ + + this->bits()[y*width*depth + x*depth + ch] = (uint8_t)uniform_distribution(0, 255); + } + } + } +} + +//prefill plane with the average imagenet pixel value +void JPEGImage::fill_with_imagenet_mean(){ + int height = this->height(); + int width = this->width(); + int depth = this->depth(); + uint8_t* imagePtr = this->bits(); + + for (int ch = 0; ch < depth; ch++){ + uint8_t ch_mean = (uint8_t)IMAGENET_MEAN_RGB[ch]; + for (int y = 0; y < height; y++){ + for (int x = 0; x < width; x++){ + imagePtr[y*width*depth + x*depth + ch] = ch_mean; + //this->bits()[y*width*depth + x*depth + ch] = (uint8_t)uniform_distribution(0, 255); + } + } + } +} + +JPEGImage::JPEGImage() : width_(0), height_(0), depth_(0) +{ +} + +JPEGImage::JPEGImage(int width, int height, int depth, const uint8_t * bits) : width_(0), +height_(0), depth_(0) +{ + if ((width <= 0) || (height <= 0) || (depth <= 0)) + return; + + width_ = width; + height_ = height; + depth_ = depth; + bits_.resize(width * height * depth); + + if (bits) + copy(bits, bits + bits_.size(), bits_.begin()); +} + +JPEGImage::JPEGImage(const string & filename) : width_(0), height_(0), depth_(0) +{ + // Load the image + FILE * file = fopen(filename.c_str(), "rb"); + + if (!file) + return; + + jpeg_decompress_struct cinfo; + jpeg_error_mgr jerr; + + cinfo.err = jpeg_std_error(&jerr); + jpeg_create_decompress(&cinfo); + jpeg_stdio_src(&cinfo, file); + + if ((jpeg_read_header(&cinfo, TRUE) != JPEG_HEADER_OK) || (cinfo.data_precision != 8) || + !jpeg_start_decompress(&cinfo)) { + fclose(file); + return; + } + + vector bits(cinfo.image_width * cinfo.image_height * cinfo.num_components); + + for (int y = 0; y < cinfo.image_height; ++y) { + JSAMPLE * row = static_cast(&bits[y * cinfo.image_width * cinfo.num_components]); + + if (jpeg_read_scanlines(&cinfo, &row, 1) != 1) { + fclose(file); + return; + } + } + + jpeg_finish_decompress(&cinfo); + + fclose(file); + + // Recopy everyting if the loading was successful + width_ = cinfo.image_width; + height_ = cinfo.image_height; + depth_ = cinfo.num_components; + bits_.swap(bits); +} + +int JPEGImage::width() const +{ + return width_; +} + +int JPEGImage::height() const +{ + return height_; +} + +int JPEGImage::depth() const +{ + return depth_; +} + +const uint8_t * JPEGImage::bits() const +{ + return empty() ? 0 : &bits_[0]; +} + +uint8_t * JPEGImage::bits() +{ + return empty() ? 0 : &bits_[0]; +} + +const uint8_t * JPEGImage::scanLine(int y) const +{ + return (empty() || (y >= height_)) ? 0 : &bits_[y * width_ * depth_]; +} + +uint8_t * JPEGImage::scanLine(int y) +{ + return (empty() || (y >= height_)) ? 0 : &bits_[y * width_ * depth_]; +} + +bool JPEGImage::empty() const +{ + return (width() <= 0) || (height() <= 0) || (depth() <= 0); +} + +void JPEGImage::save(const string & filename, int quality) const +{ + if (empty()) + return; + + FILE * file = fopen(filename.c_str(), "wb"); + + if (!file) + return; + + jpeg_compress_struct cinfo; + jpeg_error_mgr jerr; + + cinfo.err = jpeg_std_error(&jerr); + jpeg_create_compress(&cinfo); + jpeg_stdio_dest(&cinfo, file); + + cinfo.image_width = width_; + cinfo.image_height = height_; + cinfo.input_components = depth_; + cinfo.in_color_space = (depth_ == 1) ? JCS_GRAYSCALE : JCS_RGB; + + jpeg_set_defaults(&cinfo); + jpeg_set_quality(&cinfo, quality, TRUE); + jpeg_start_compress(&cinfo, TRUE); + + for (int y = 0; y < height_; ++y) { + const JSAMPLE * row = static_cast(&bits_[y * width_ * depth_]); + jpeg_write_scanlines(&cinfo, const_cast(&row), 1); + } + + jpeg_finish_compress(&cinfo); + + fclose(file); +} + +JPEGImage JPEGImage::resize(int width, int height) const +{ + // Empty image + if ((width <= 0) || (height <= 0)) + return JPEGImage(); + + // Same dimensions + if ((width == width_) && (height == height_)) + return *this; + + JPEGImage result; + + result.width_ = width; + result.height_ = height; + result.depth_ = depth_; + result.bits_.resize(width * height * depth_); + + // Resize the image at each octave + int srcWidth = width_; + int srcHeight = height_; + + vector tmpSrc; + vector tmpDst; + + float scale = 0.5f; + int halfWidth = width_ * scale + 0.5f; + int halfHeight = height_ * scale + 0.5f; + + while ((width <= halfWidth) && (height <= halfHeight)) { + if (tmpDst.empty()) + tmpDst.resize(halfWidth * halfHeight * depth_); + + Resize(tmpSrc.empty() ? &bits_[0] : &tmpSrc[0], srcWidth, srcHeight, &tmpDst[0], halfWidth, + halfHeight, depth_); + + // Dst becomes src + tmpSrc.swap(tmpDst); + srcWidth = halfWidth; + srcHeight = halfHeight; + + // Next octave + scale *= 0.5f; + halfWidth = width_ * scale + 0.5f; + halfHeight = height_ * scale + 0.5f; + } + + Resize(tmpSrc.empty() ? &bits_[0] : &tmpSrc[0], srcWidth, srcHeight, &result.bits_[0], width, + height, depth_); + + return result; +} + +JPEGImage JPEGImage::crop(int x, int y, int width, int height) const +{ + // Empty image + if ((width <= 0) || (height <= 0) || (x + width <= 0) || (y + height <= 0) || (x >= width_) || + (y >= height_)) + return JPEGImage(); + + // Crop the coordinates to the image + width = min(x + width - 1, width_ - 1) - max(x, 0) + 1; + height = min(y + height - 1, height_ - 1) - max(y, 0) + 1; + x = max(x, 0); + y = max(y, 0); + + JPEGImage result; + + result.width_ = width; + result.height_ = height; + result.depth_ = depth_; + result.bits_.resize(width * height * depth_); + + for (int y2 = 0; y2 < height; ++y2) + for (int x2 = 0; x2 < width; ++x2) + for (int i = 0; i < depth_; ++i) + result.bits_[(y2 * width + x2) * depth_ + i] = + bits_[((y + y2) * width_ + x + x2) * depth_ + i]; + + return result; +} + +//TODO: remove const? +JPEGImage JPEGImage::pad(int padx, int pady, bool randPad) const +{ + // empty image + if( (padx < 0) || (pady < 0) ) + return JPEGImage(); + + int srcWidth = this->width(); + int srcHeight = this->height(); + + // new size with padding + int dstWidth = srcWidth + 2*padx; + int dstHeight = srcHeight + 2*pady; + + JPEGImage result; + result.width_ = dstWidth; + result.height_ = dstHeight; + result.depth_ = depth_; + result.bits_.resize(dstWidth * dstHeight * depth_); + + if(randPad == true) + result.fill_with_rand(); + //fill_with_rand(result); + + //rectangle packing offsets: + int x_off = padx; + int y_off = pady; + + //copy to padded image + for (int y = 0; y < srcHeight; y++){ + for (int x = 0; x < srcWidth; x++){ + for (int ch = 0; ch < depth_; ch++){ + + //result.bits_[...] = this->bits_[...]; + result.bits_[(y+y_off)*dstWidth*depth_ + (x+x_off)*depth_ + ch] = this->bits_[y*srcWidth*depth_ + x*depth_ + ch]; + } + } + } + return result; +} + +// Bilinear interpolation coefficient +namespace FFLD +{ +namespace detail +{ +struct Bilinear +{ + int x0; + int x1; + float a; + float b; +}; +} +} + +void JPEGImage::Resize(const uint8_t * src, int srcWidth, int srcHeight, uint8_t * dst, + int dstWidth, int dstHeight, int depth) +{ + if ((srcWidth == dstWidth) && (srcHeight == dstHeight)) { + copy(src, src + srcWidth * srcHeight * depth, dst); + return; + } + + const float xScale = static_cast(srcWidth) / dstWidth; + const float yScale = static_cast(srcHeight) / dstHeight; + + // Bilinear interpolation coefficients + vector cols(dstWidth); + + for (int j = 0; j < dstWidth; ++j) { + const float x = min(max((j + 0.5f) * xScale - 0.5f, 0.0f), srcWidth - 1.0f); + cols[j].x0 = x; + cols[j].x1 = min(cols[j].x0 + 1, srcWidth - 1); + cols[j].a = x - cols[j].x0; + cols[j].b = 1.0f - cols[j].a; + } + + for (int i = 0; i < dstHeight; ++i) { + const float y = min(max((i + 0.5f) * yScale - 0.5f, 0.0f), srcHeight - 1.0f); + const int y0 = y; + const int y1 = min(y0 + 1, srcHeight - 1); + const float c = y - y0; + const float d = 1.0f - c; + + for (int j = 0; j < dstWidth; ++j) + for (int k = 0; k < depth; ++k) + dst[(i * dstWidth + j) * depth + k] = + (src[(y0 * srcWidth + cols[j].x0) * depth + k] * cols[j].b + + src[(y0 * srcWidth + cols[j].x1) * depth + k] * cols[j].a) * d + + (src[(y1 * srcWidth + cols[j].x0) * depth + k] * cols[j].b + + src[(y1 * srcWidth + cols[j].x1) * depth + k] * cols[j].a) * c + 0.5f; + } +} diff --git a/src/stitch_pyramid/JPEGImage.h b/src/stitch_pyramid/JPEGImage.h new file mode 100644 index 00000000000..c827cd3915d --- /dev/null +++ b/src/stitch_pyramid/JPEGImage.h @@ -0,0 +1,113 @@ +//-------------------------------------------------------------------------------------------------- +// Implementation of the paper "Exact Acceleration of Linear Object Detectors", 12th European +// Conference on Computer Vision, 2012. +// +// Copyright (c) 2012 Idiap Research Institute, +// Written by Charles Dubout +// +// This file is part of FFLD (the Fast Fourier Linear Detector) +// +// FFLD is free software: you can redistribute it and/or modify it under the terms of the GNU +// General Public License version 3 as published by the Free Software Foundation. +// +// FFLD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +// Public License for more details. +// +// You should have received a copy of the GNU General Public License along with FFLD. If not, see +// . +//-------------------------------------------------------------------------------------------------- + +#ifndef FFLD_JPEGIMAGE_H +#define FFLD_JPEGIMAGE_H + +#include +#include +#include + +namespace FFLD +{ +/// The JPEGImage class allows to load/save an image from/to a jpeg file, and to apply basic +/// operations such as resizing or cropping to it. The pixels are stored contiguously in row-major +/// order (scanline 0: RGB RGB RGB, scanline 1: RGB RGB RGB...) +class JPEGImage +{ +public: + + void fill_with_rand(); //fill self with random numbers (e.g. before filling w/ data so we get rand-padding) + + void fill_with_imagenet_mean(); + + /// Constructs an empty image. An empty image has zero size. + JPEGImage(); + + /// Constructs an image with the given @p width, @p height and @p depth, and initializes it from + /// the given @p bits. + /// @note The returned image might be empty if any of the parameters is incorrect. + JPEGImage(int width, int height, int depth, const uint8_t * bits = 0); + + /// Constructs an image and tries to load the image from the jpeg file with the given + /// @p filename. + /// @note The returned image might be empty if the image could not be loaded. + JPEGImage(const std::string & filename); + + /// Returns the width of the image. + int width() const; + + /// Returns the height of the image. + int height() const; + + /// Returns the depth of the image. The image depth is the number of color channels. + int depth() const; + + /// Returns a pointer to the pixel data. + /// @note Returns a null pointer if the image is empty. + const uint8_t * bits() const; + + /// Returns a pointer to the pixel data. Returns a null pointer if the image is empty. + uint8_t * bits(); + + /// Returns a pointer to the pixel data at the scanline with index y. The first scanline is at + /// index 0. Returns a null pointer if the image is empty or if y is out of bounds. + const uint8_t * scanLine(int y) const; + + /// Returns a pointer to the pixel data at the scanline with index y. The first scanline is at + /// index 0. Returns a null pointer if the image is empty or if y is out of bounds. + uint8_t * scanLine(int y); + + /// Returns whether the image is empty. An empty image has zero size. + bool empty() const; + + /// Saves the image to a jpeg file with the given @p filename and @p quality. + void save(const std::string & filename, int quality = 100) const; + + /// Returns a copy of the image scaled to the given @p width and @p height. + /// If either the width or the height is zero or negative, the method returns an empty image. + JPEGImage resize(int width, int height) const; + + /// Returns a copy of a region of the image located at @p x and @p y, and of dimensions @p width + /// and @p height. + /// @note The returned image might be smaller if some of the coordinates are outside the image. + JPEGImage crop(int x, int y, int width, int height) const; + + // @param randPad = whether to use random numbers in padding (or, if false, use zero padding) + JPEGImage pad(int x, int y, bool randPad) const; + + +private: + // Blur and downscale an image by a factor 2 + static void Halve(const uint8_t * src, int srcWidth, int srcHeight, uint8_t * dst, + int dstWidth, int dstHeight, int depth); + + // Resize an image to the specified dimensions using bilinear interpolation + static void Resize(const uint8_t * src, int srcWidth, int srcHeight, uint8_t * dst, + int dstWidth, int dstHeight, int depth); + + int width_; + int height_; + int depth_; + std::vector bits_; +}; +} + +#endif diff --git a/src/stitch_pyramid/JPEGPyramid.cpp b/src/stitch_pyramid/JPEGPyramid.cpp new file mode 100644 index 00000000000..70817e028d7 --- /dev/null +++ b/src/stitch_pyramid/JPEGPyramid.cpp @@ -0,0 +1,232 @@ +//-------------------------------------------------------------------------------------------------- +// Implementation of the paper "Exact Acceleration of Linear Object Detectors", 12th European +// Conference on Computer Vision, 2012. +// +// Copyright (c) 2012 Idiap Research Institute, +// Written by Charles Dubout +// +// This file is part of FFLD (the Fast Fourier Linear Detector) +// +// FFLD is free software: you can redistribute it and/or modify it under the terms of the GNU +// General Public License version 3 as published by the Free Software Foundation. +// +// FFLD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +// Public License for more details. +// +// You should have received a copy of the GNU General Public License along with FFLD. If not, see +// . +//-------------------------------------------------------------------------------------------------- + +#include "JPEGPyramid.h" +#include "imagenet_mean.hpp" //contains hard-coded imagenet RGB mean. from Caffe. + +#include +#include +#include +#include +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +using namespace FFLD; +using namespace std; + +#include +template< typename T > inline std::string str(T const & i) { std::stringstream s; s << i; return s.str(); } // convert T i to string + +//TODO: make this uchar? +//linear interpolation, "lerp" +void JPEGPyramid::linear_interp(float val0, float val1, int n_elements, float* inout_lerp){ + + float n_elements_inv = 1 / (float)n_elements; + inout_lerp[0] = val0; + inout_lerp[n_elements-1] = val1; + + for(int i=1; i < (n_elements-1); i++){ + float frac_offset = (n_elements-i) * n_elements_inv; + + inout_lerp[i] = val0 * frac_offset + + val1 * (1 - frac_offset); + } +} + +// call this on each scaled image +// fills the image's padding with linear interpolated values from 'edge of img pixel' to 'imagenet mean' +void JPEGPyramid::AvgLerpPad(JPEGImage & image){ + + int width = image.width(); //including padding + int height = image.height(); + int depth = 3; + + float top_lerp[pady_+1]; //interpolated data to fill in above the current image column + float bottom_lerp[pady_+1]; + float left_lerp[padx_+1]; + float right_lerp[padx_+1]; + float currPx = 0; + + assert( padx_ == pady_ ); // corner padding assumes this (for now) + float corner_lerp[padx_+1]; + + uint8_t* imagePtr = image.bits(); + + //top, bottom, left, right + for(int ch=0; ch<3; ch++){ + float avgPx = IMAGENET_MEAN_RGB[ch]; + for(int x=padx_; x < width-padx_; x++){ + + //top + currPx = imagePtr[pady_*width*depth + x*depth + ch]; + linear_interp(currPx, avgPx, pady_+1, top_lerp); //populate top_lerp + for(int y=0; y - side of image + assert( padx_ == pady_ ); // corner padding assumes this (for now) + for( uint32_t dx = 0; dx != 2; ++ dx ) { + for( uint32_t dy = 0; dy != 2; ++ dy ) { + // x,y is coord of dx,dy valid corner pixel of un-padded image + uint32_t const x = dx ? (width-padx_-1) : padx_; + uint32_t const y = dy ? (height-pady_-1) : pady_; + for( uint32_t dd = 2; dd <= padx_; ++dd ) { + uint32_t const cx = x + ( dx ? dd : -dd ); // cx,y is point on existing dx padding, dd outside image + uint32_t const cy = y + ( dy ? dd : -dd ); // x,cy is point on existing dy padding, dd outside image + assert( x < width ); assert( y < height ); + assert( cx < width ); assert( cy < height ); + float const cx_y_v = imagePtr[y*width*depth + cx*depth + ch]; + float const x_cy_v = imagePtr[cy*width*depth + x*depth + ch]; + linear_interp(cx_y_v, x_cy_v, dd+1, corner_lerp); // populate corner_lerp + for( uint32_t ci = 1; ci < dd; ++ci ) { // fill in diagonal corner pixels + uint32_t const cix = x + ( dx ? ci : -ci ); + uint32_t const ciy = cy + ( dy ? -ci : ci ); + //printf( "dx=%s x=%s cx=%s ci=%s cix=%s dd=%s\n", + // str(dx).c_str(), str(x).c_str(), str(cx).c_str(), str(ci).c_str(), str(cix).c_str(), str(dd).c_str() ); + assert( cix < width ); assert( ciy < height ); + imagePtr[ciy*width*depth + cix*depth + ch] = corner_lerp[ci]; + } + } + // fill in all-mean outer half of corner (a triangle) + uint32_t const cor_x = dx ? (width-1) : 0; + uint32_t const cor_y = dy ? (height-1) : 0; + // cor_x,cor_y is coord of dx,dy corner pixel of image (including padding) + for( uint32_t dd = 0; dd < padx_; ++dd ) { + for( uint32_t ddi = 0; ddi < (padx_-dd); ++ddi ) { + uint32_t const tri_x = cor_x + ( dx ? -dd : dd ); + uint32_t const tri_y = cor_y + ( dy ? -ddi : ddi ); + assert( tri_x < width ); assert( tri_y < height ); + imagePtr[tri_y*width*depth + tri_x*depth + ch] = avgPx; + } + } + } + } + } +} + +JPEGPyramid::JPEGPyramid() : padx_(0), pady_(0), interval_(0) +{ +} + +JPEGPyramid::JPEGPyramid(int padx, int pady, int interval, const vector & levels) : padx_(0), +pady_(0), interval_(0) +{ + if ((padx < 1) || (pady < 1) || (interval < 1)) + return; + + padx_ = padx; + pady_ = pady; + interval_ = interval; + levels_ = levels; +} + +JPEGPyramid::JPEGPyramid(const JPEGImage & image, int padx, int pady, int interval, int upsampleFactor) : padx_(0), +pady_(0), interval_(0) +{ + if (image.empty() || (padx < 1) || (pady < 1) || (interval < 1)) + return; + + // Copmute the number of scales such that the smallest size of the last level is 5 + const int numScales = ceil(log(min(image.width(), image.height()) / 40.0) / log(2.0)) * interval; //'max_scale' in voc5 featpyramid.m + + // Cannot compute the pyramid on images too small + if (numScales < interval) + return; + + imwidth_ = image.width(); + imheight_ = image.height(); + padx_ = padx; + pady_ = pady; + interval_ = interval; + levels_.resize(numScales+1); + scales_.resize(numScales+1); + +#pragma omp parallel for + for (int i = 0; i <= numScales; ++i){ + //generic pyramid... not stitched. + + double scale = pow(2.0, static_cast(-i) / interval) * upsampleFactor; + JPEGImage scaled = image.resize(image.width() * scale + 0.5, image.height() * scale + 0.5); + bool use_randPad = false; + scaled = scaled.pad(padx, pady, use_randPad); //an additional deepcopy. (for efficiency, could have 'resize()' accept padding too + AvgLerpPad(scaled); //linear interpolate edge pixels to imagenet mean + + scales_[i] = scale; + levels_[i] = scaled; + } +} + +int JPEGPyramid::padx() const +{ + return padx_; +} + +int JPEGPyramid::pady() const +{ + return pady_; +} + +int JPEGPyramid::interval() const +{ + return interval_; +} + +const vector & JPEGPyramid::levels() const +{ + return levels_; +} + +bool JPEGPyramid::empty() const +{ + return levels().empty(); +} + diff --git a/src/stitch_pyramid/JPEGPyramid.h b/src/stitch_pyramid/JPEGPyramid.h new file mode 100644 index 00000000000..ca79c527a5b --- /dev/null +++ b/src/stitch_pyramid/JPEGPyramid.h @@ -0,0 +1,106 @@ +//-------------------------------------------------------------------------------------------------- +// Implementation of the paper "Exact Acceleration of Linear Object Detectors", 12th European +// Conference on Computer Vision, 2012. +// +// Copyright (c) 2012 Idiap Research Institute, +// Written by Charles Dubout +// +// This file is part of FFLD (the Fast Fourier Linear Detector) +// +// FFLD is free software: you can redistribute it and/or modify it under the terms of the GNU +// General Public License version 3 as published by the Free Software Foundation. +// +// FFLD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +// Public License for more details. +// +// You should have received a copy of the GNU General Public License along with FFLD. If not, see +// . +//-------------------------------------------------------------------------------------------------- + +#ifndef FFLD_JPEGPYRAMID_H +#define FFLD_JPEGPYRAMID_H + +#include "JPEGImage.h" + +using namespace std; + +namespace FFLD +{ +/// The JPEGPyramid class computes and stores the HOG features extracted from a jpeg image at +/// multiple scales. The scale of the pyramid level of index @c i is given by the following formula: +/// 2^(1 - @c i / @c interval), so that the first scale is at double the resolution of the original +/// image). Each level is padded with zeros horizontally and vertically by a fixed amount. The last +/// feature is special: it takes the value one in the padding and zero otherwise. +/// @note Define the PASCAL_JPEGPYRAMID_FELZENSZWALB_FEATURES flag during compilation to use +/// Felzenszwalb's original features (slower and not as accurate as they do no angular +/// interpolation, provided for compatibility only). +/// @note Define the PASCAL_JPEGPYRAMID_DOUBLE to use double scalar values instead of float (slower, +/// uses twice the amount of memory, and the increase in precision is not necessarily useful). +class JPEGPyramid +{ +public: + static const int NbChannels = 3; //RGB + + /// Type of a scalar value. + typedef float Scalar; + + /// Type of a pyramid level (matrix of cells). + typedef JPEGImage Level; + + /// Constructs an empty pyramid. An empty pyramid has no level. + JPEGPyramid(); + + /// Constructs a pyramid from parameters and a list of levels. + /// @param[in] padx Amount of horizontal zero padding (in cells). + /// @param[in] pady Amount of vertical zero padding (in cells). + /// @param[in] interval Number of levels per octave in the pyramid. + /// @param[in] levels List of pyramid levels. + /// @note The amount of padding and the interval should be at least 1. + JPEGPyramid(int padx, int pady, int interval, const std::vector & levels); + + /// Constructs a pyramid from the JPEGImage of a Scene. + /// @param[in] image The JPEGImage of the Scene. + /// @param[in] padx Amount of horizontal zero padding (in cells). + /// @param[in] pady Amount of vertical zero padding (in cells). + /// @param[in] interval Number of levels per octave in the pyramid. + /// @param[in] upsampleFactor = how big should top scale be? (compared to input img) + /// @note The amount of padding and the interval should be at least 1. + JPEGPyramid(const JPEGImage & image, int padx, int pady, int interval = 10, int upsampleFactor = 2); + + /// Returns whether the pyramid is empty. An empty pyramid has no level. + bool empty() const; + + /// Returns the amount of horizontal zero padding (in cells). + int padx() const; + + /// Returns the amount of vertical zero padding (in cells). + int pady() const; + + /// Returns the number of levels per octave in the pyramid. + int interval() const; + + /// Returns the pyramid levels. + /// @note Scales are given by the following formula: 2^(1 - @c index / @c interval). + const std::vector & levels() const; + + //upsampling/downsampling multipliers. (scales_[i] corresponds to levels_[i]) + vector scales_; + + //populate inout_lerp with a sliding range from val0 to val1 (for padding images) + void linear_interp(float val0, float val1, int n_elements, float* inout_lerp); + + //fill an image's padding with linear interpolated data: [from edge of img to imagenet mean] + void AvgLerpPad(JPEGImage & image); + + int imwidth_; + int imheight_; + + int padx_; + int pady_; + int interval_; + std::vector levels_; +}; +} + +#endif diff --git a/src/stitch_pyramid/Patchwork.cpp b/src/stitch_pyramid/Patchwork.cpp new file mode 100644 index 00000000000..3c58a4832cb --- /dev/null +++ b/src/stitch_pyramid/Patchwork.cpp @@ -0,0 +1,347 @@ +//-------------------------------------------------------------------------------------------------- +// Implementation of the paper "Exact Acceleration of Linear Object Detectors", 12th European +// Conference on Computer Vision, 2012. +// +// Copyright (c) 2012 Idiap Research Institute, +// Written by Charles Dubout +// +// This file is part of FFLD (the Fast Fourier Linear Detector) +// +// FFLD is free software: you can redistribute it and/or modify it under the terms of the GNU +// General Public License version 3 as published by the Free Software Foundation. +// +// FFLD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +// Public License for more details. +// +// You should have received a copy of the GNU General Public License along with FFLD. If not, see +// . +//-------------------------------------------------------------------------------------------------- + +#include "Patchwork.h" +#include "JPEGPyramid.h" + +#include +#include +#include +#include +#include +#include + +using namespace FFLD; +using namespace std; + +//static vars (TODO: make these not static...) +int Patchwork::MaxRows_(0); +int Patchwork::MaxCols_(0); +int Patchwork::HalfCols_(0); +int Patchwork::img_minWidth_(0); +int Patchwork::img_minHeight_(0); + +Patchwork::Patchwork() : padx_(0), pady_(0), interval_(0) +{ +} + +Patchwork::Patchwork(JPEGPyramid & pyramid) : padx_(pyramid.padx()), pady_(pyramid.pady()), +interval_(pyramid.interval()) +{ + //int sbin = 16; //convnet_downsampling_factor -- TODO: take as user input + //int templateWidth = (6+1)*sbin; //TODO: take as user input + //int templateHeight = (16+1)*sbin; + + imwidth_ = pyramid.imwidth_; + imheight_ = pyramid.imheight_; + scales_ = pyramid.scales_; //keep track of pyra scales + nbScales = pyramid.levels().size(); //Patchwork class variable + + //printf(" before prune_big_scales(). scales_.size()=%ld, pyramid.levels_.size()=%ld \n", scales_.size(), pyramid.levels_.size()); + prune_big_scales(pyramid); //remove scales that won't fit in (MaxRows, MaxCols) + prune_small_scales(pyramid, img_minWidth_, img_minHeight_); //img_minWidth and img_minHeight are configured in Patchwork::Init() + cout << " nbScales = " << nbScales << endl; + //printf(" after prune_big_scales(). scales_.size()=%ld, pyramid.levels_.size()=%ld \n", scales_.size(), pyramid.levels_.size()); + + rectangles_.resize(nbScales); + + for (int i = 0; i < nbScales; ++i) { + rectangles_[i].first.setWidth(pyramid.levels()[i].width()); //stitching includes padding in the img size. + rectangles_[i].first.setHeight(pyramid.levels()[i].height()); + } + + // Build the patchwork planes + const int nbPlanes = BLF(rectangles_); + cout << " nbPlanes = " << nbPlanes << endl; + + assert(nbPlanes >= 0); + + planes_.resize(nbPlanes); + #pragma omp parallel for + for (int i = 0; i < nbPlanes; ++i) { + planes_[i] = JPEGImage(MaxCols_, MaxRows_, JPEGPyramid::NbChannels); //JPEGImage(width, height, depth) + //planes_[i].fill_with_rand(); //random noise that will go between images on plane. (TODO: allow user to enable/disable) + planes_[i].fill_with_imagenet_mean(); //fill with imagenet avg pixel value + } + + int depth = JPEGPyramid::NbChannels; + + // [Forrest implemented... ] + //COPY scaled images -> fixed-size planes + #pragma omp parallel for + for (int i = 0; i < nbScales; ++i) { + + //currPlane is destination + JPEGImage* currPlane = &planes_[rectangles_[i].second]; //TODO: make sure my dereferencing makes sense. (trying to avoid deepcopy) + + //currLevel is source + const JPEGImage* currLevel = &pyramid.levels()[i]; + + int srcWidth = currLevel->width(); + int srcHeight = currLevel->height(); + + int dstWidth = currPlane->width(); + int dstHeight = currPlane->height(); + + //rectangle packing offsets: + int x_off = rectangles_[i].first.x(); + int y_off = rectangles_[i].first.y(); + + for (int y = 0; y < srcHeight; y++){ + for (int x = 0; x < srcWidth; x++){ + for (int ch = 0; ch < depth; ch++){ + + //currPlane.bits[...] = pyramid.levels()[i].data[...]; + currPlane->bits()[((y + y_off)*dstWidth*depth) + ((x + x_off)*depth) + ch] = currLevel->bits()[y*srcWidth*depth + x*depth + ch]; + } + } + } + } +} + +//remove scales that are bigger than one Patchwork plane +void Patchwork::prune_big_scales(JPEGPyramid & pyramid){ + + int first_valid_scale_idx = pyramid.levels_.size(); + + for(int i=0; i < pyramid.levels_.size(); i++){ + if( !((pyramid.levels_[i].width() > MaxCols_) || (pyramid.levels_[i].height() > MaxRows_)) ) + { + first_valid_scale_idx = i; + break; + } + } + + if(first_valid_scale_idx > 0){ + scales_.erase( scales_.begin(), scales_.begin() + first_valid_scale_idx); + pyramid.levels_.erase( pyramid.levels_.begin(), pyramid.levels_.begin() + first_valid_scale_idx); + nbScales = nbScales - first_valid_scale_idx; + printf(" had to remove first %d scales, because they didn't fit in Patchwork plane \n", first_valid_scale_idx); + } +} + +//remove scales that are smaller than the template +void Patchwork::prune_small_scales(JPEGPyramid & pyramid, int img_minWidth_, int img_minHeight_){ + + int last_valid_scale_idx = 0; + + //for(int i=0; i < pyramid.levels_.size(); i++){ + for(int i = pyramid.levels_.size()-1; i >= 0; i--){ +//printf("pyramid.levels_[%d].width=%d, img_minWidth_=%d \n", i, pyramid.levels_[i].width(), img_minWidth_); + if( ((pyramid.levels_[i].width() >= img_minWidth_) && (pyramid.levels_[i].height() >= img_minHeight_)) ) + { + last_valid_scale_idx = i; + break; + } + } + + //printf(" last_valid_scale_idx = %d \n", last_valid_scale_idx); + if(last_valid_scale_idx < pyramid.levels_.size()){ + scales_.erase( scales_.begin() + last_valid_scale_idx, scales_.end() ); + pyramid.levels_.erase( pyramid.levels_.begin() + last_valid_scale_idx, pyramid.levels_.end()); + int num_scales_to_remove = nbScales - last_valid_scale_idx; + nbScales = nbScales - num_scales_to_remove; + printf(" had to remove last %d scales, because they were smaller than the minimum that you specified in (feat_minWidth, feat_minHeight) \n", num_scales_to_remove); + } +} + +int Patchwork::padx() const +{ + return padx_; +} + +int Patchwork::pady() const +{ + return pady_; +} + +int Patchwork::interval() const +{ + return interval_; +} + +bool Patchwork::empty() const +{ + return planes_.empty(); +} + +bool Patchwork::Init(int maxRows, int maxCols, int img_minWidth, int img_minHeight) +{ + // It is an error if maxRows or maxCols are too small + if ((maxRows < 2) || (maxCols < 2)) + return false; + + // Temporary matrices + //JPEGPyramid::Matrix tmp(maxRows * JPEGPyramid::NbChannels, maxCols + 2); + + //int dims[2] = {maxRows, maxCols}; + MaxRows_ = maxRows; + MaxCols_ = maxCols; + HalfCols_ = maxCols / 2 + 1; + + img_minWidth_ = img_minWidth; + img_minHeight_ = img_minHeight; +} + +int Patchwork::MaxRows() +{ + return MaxRows_; +} + +int Patchwork::MaxCols() +{ + return MaxCols_; +} + +namespace FFLD +{ +namespace detail +{ +// Order rectangles by decreasing area. +class AreaComparator +{ +public: + AreaComparator(const vector > & rectangles) : + rectangles_(rectangles) + { + } + + /// Returns whether rectangle @p a comes before @p b. + bool operator()(int a, int b) const + { + const int areaA = rectangles_[a].first.area(); + const int areaB = rectangles_[b].first.area(); + + return (areaA > areaB) || ((areaA == areaB) && (rectangles_[a].first.height() > + rectangles_[b].first.height())); + } + +private: + const vector > & rectangles_; +}; + +// Order free gaps (rectangles) by position and then by size +struct PositionComparator +{ + // Returns whether rectangle @p a comes before @p b + bool operator()(const Rectangle & a, const Rectangle & b) const + { + return (a.y() < b.y()) || + ((a.y() == b.y()) && + ((a.x() < b.x()) || + ((a.x() == b.x()) && + ((a.height() > b.height()) || + ((a.height() == b.height()) && (a.width() > b.width())))))); + } +}; +} +} + +int Patchwork::BLF(vector > & rectangles) +{ + // Order the rectangles by decreasing area. If a rectangle is bigger than MaxRows x MaxCols + // return -1 + vector ordering(rectangles.size()); + + for (int i = 0; i < rectangles.size(); ++i) { + if ((rectangles[i].first.width() > MaxCols_) || (rectangles[i].first.height() > MaxRows_)) + return -1; + + ordering[i] = i; + } + + sort(ordering.begin(), ordering.end(), detail::AreaComparator(rectangles)); + + // Index of the plane containing each rectangle + for (int i = 0; i < rectangles.size(); ++i) + rectangles[i].second = -1; + + vector > gaps; + + // Insert each rectangle in the first gap big enough + for (int i = 0; i < rectangles.size(); ++i) { + pair & rect = rectangles[ordering[i]]; + + // Find the first gap big enough + set::iterator g; + + for (int i = 0; (rect.second == -1) && (i < gaps.size()); ++i) { + for (g = gaps[i].begin(); g != gaps[i].end(); ++g) { + if ((g->width() > rect.first.width()) && (g->height() > rect.first.height())) //Forrest -- avoid bizarre bounds error + //if ((g->width() >= rect.first.width()) && (g->height() >= rect.first.height())) + { + rect.second = i; + break; + } + } + } + + // If no gap big enough was found, add a new plane + if (rect.second == -1) { + set plane; + plane.insert(Rectangle(MaxCols_, MaxRows_)); // The whole plane is free + gaps.push_back(plane); + g = gaps.back().begin(); + rect.second = gaps.size() - 1; + } + + // Insert the rectangle in the gap + rect.first.setX(g->x()); + rect.first.setY(g->y()); + + //printf(" put scale %d in this gap: xMin=%d, xMax=%d, yMin=%d, yMax=%d \n", i, g->x(), g->x() + rect.first.width(), + // g->y(), g->y() + rect.first.height()); + + // Remove all the intersecting gaps, and add newly created gaps + for (g = gaps[rect.second].begin(); g != gaps[rect.second].end();) { + if (!((rect.first.right() < g->left()) || (rect.first.bottom() < g->top()) || + (rect.first.left() > g->right()) || (rect.first.top() > g->bottom()))) { + // Add a gap to the left of the new rectangle if possible + if (g->x() < rect.first.x()) + gaps[rect.second].insert(Rectangle(g->x(), g->y(), rect.first.x() - g->x(), + g->height())); + + // Add a gap on top of the new rectangle if possible + if (g->y() < rect.first.y()) + gaps[rect.second].insert(Rectangle(g->x(), g->y(), g->width(), + rect.first.y() - g->y())); + + // Add a gap to the right of the new rectangle if possible + if (g->right() > rect.first.right()) + gaps[rect.second].insert(Rectangle(rect.first.right() + 1, g->y(), + g->right() - rect.first.right(), + g->height())); + + // Add a gap below the new rectangle if possible + if (g->bottom() > rect.first.bottom()) + gaps[rect.second].insert(Rectangle(g->x(), rect.first.bottom() + 1, g->width(), + g->bottom() - rect.first.bottom())); + + // Remove the intersecting gap + gaps[rect.second].erase(g++); + } + else { + ++g; + } + } + } + + return gaps.size(); +} diff --git a/src/stitch_pyramid/Patchwork.h b/src/stitch_pyramid/Patchwork.h new file mode 100644 index 00000000000..66ee18fd312 --- /dev/null +++ b/src/stitch_pyramid/Patchwork.h @@ -0,0 +1,120 @@ +//-------------------------------------------------------------------------------------------------- +// Implementation of the paper "Exact Acceleration of Linear Object Detectors", 12th European +// Conference on Computer Vision, 2012. +// +// Copyright (c) 2012 Idiap Research Institute, +// Written by Charles Dubout +// +// This file is part of FFLD (the Fast Fourier Linear Detector) +// +// FFLD is free software: you can redistribute it and/or modify it under the terms of the GNU +// General Public License version 3 as published by the Free Software Foundation. +// +// FFLD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +// Public License for more details. +// +// You should have received a copy of the GNU General Public License along with FFLD. If not, see +// . +//-------------------------------------------------------------------------------------------------- + +#ifndef FFLD_PATCHWORK_H +#define FFLD_PATCHWORK_H + +#include "JPEGPyramid.h" +#include "Rectangle.h" + +#include +using namespace std; + +namespace FFLD +{ +/// The Patchwork class computes full convolutions much faster than the JPEGPyramid class. +class Patchwork +{ +public: + + /// Type of a patchwork plane . + typedef JPEGImage Plane; + + /// Type of a patchwork filter (plane + original filter size). + typedef std::pair > Filter; + + /// Constructs an empty patchwork. An empty patchwork has no plane. + Patchwork(); + + /// Constructs a patchwork from a pyramid. + /// @param[in] pyramid The pyramid of features. + /// @note If the pyramid is larger than the last maxRows and maxCols passed to the Init method + /// the Patchwork will be empty. + /// @note Assumes that the features of the pyramid levels are zero in the padded regions but for + /// the last feature, which is assumed to be one. + Patchwork(JPEGPyramid & pyramid); + + //remove scales that don't fit in planes + void prune_big_scales(JPEGPyramid & pyramid); + + //remove scales that are smaller than the template + void prune_small_scales(JPEGPyramid & pyramid, int img_minWidth_, int img_minHeight_); + + /// Returns the amount of horizontal zero padding (in cells). + int padx() const; + + /// Returns the amount of vertical zero padding (in cells). + int pady() const; + + /// Returns the number of levels per octave in the pyramid. + int interval() const; + + /// Returns whether the patchwork is empty. An empty patchwork has no plane. + bool empty() const; + + /// Returns the convolutions of the patchwork with filters (useful to compute the SVM margins). + /// @param[in] filters The filters. + /// @param[out] convolutions The convolutions (filters x levels). + //void convolve(const std::vector & filters, + // std::vector > & convolutions) const; + + /// Initializes the data structures. + /// @param[in] maxRows Maximum number of rows of a pyramid level (including padding). + /// @param[in] maxCols Maximum number of columns of a pyramid level (including padding). + /// @param[in] img_minWidth, img_minHeight = size of smallest desired scale (in pixels) + /// @returns Whether the initialization was successful. + /// @note Must be called before any other method (including constructors). + static bool Init(int maxRows, int maxCols, int img_minWidth, int img_minHeight); + + /// Returns the current maximum number of rows of a pyramid level (including padding). + static int MaxRows(); + + /// Returns the current maximum number of columns of a pyramid level (including padding). + static int MaxCols(); + + vector planes_; + int nbScales; + + int padx_; + int pady_; + int interval_; + vector > rectangles_; + vector scales_; + + static int MaxRows_; + static int MaxCols_; + static int HalfCols_; + + //size of smallest image scale desired by user + static int img_minWidth_; + static int img_minHeight_; + + //size of input image + int imwidth_; + int imheight_; + +private: + // Bottom-Left fill algorithm + static int BLF(vector > & rectangles); + +}; +} + +#endif diff --git a/src/stitch_pyramid/PyramidStitcher.cpp b/src/stitch_pyramid/PyramidStitcher.cpp new file mode 100644 index 00000000000..1fcc1b8645e --- /dev/null +++ b/src/stitch_pyramid/PyramidStitcher.cpp @@ -0,0 +1,95 @@ + +#include "SimpleOpt.h" +#include "JPEGPyramid.h" +#include "JPEGImage.h" +#include "Patchwork.h" +#include "PyramidStitcher.h" + +#include +#include +#include +#include +#include +#include + +using namespace FFLD; +using namespace std; + +//TODO: have a pyramid stitch class? + +// @param planeDim == width == height of planes to cover with images (optional) +// if planeDim <= 0, then ignore planeDim and compute plane size based on input image dims +Patchwork stitch_pyramid(string file, int img_minWidth, int img_minHeight, + int padding, int interval, int planeDim) +{ + JPEGImage image(file); + if (image.empty()) { + cerr << "\nInvalid image " << file << endl; + } + + int upsampleFactor = 2; //TODO: make this an input param? + //int upsampleFactor = 3; + + // Compute the downsample+stitch + JPEGPyramid pyramid(image, padding, padding, interval, upsampleFactor); //multiscale DOWNSAMPLE with (padx == pady == padding) + if (pyramid.empty()) { + cerr << "\nInvalid image " << file << endl; + } + + int planeWidth; + int planeHeight; + + if(planeDim > 0){ + planeWidth = planeDim; + planeHeight = planeDim; + } + else{ + planeWidth = (pyramid.levels()[0].width() + 15) & ~15; + planeHeight = (pyramid.levels()[0].height() + 15) & ~15; + planeWidth = max(planeWidth, planeHeight); //SQUARE planes for Caffe convnet + planeHeight = max(planeWidth, planeHeight); + } + + Patchwork::Init(planeHeight, planeWidth, img_minWidth, img_minHeight); + const Patchwork patchwork(pyramid); //STITCH + + return patchwork; +} + +//@param sbin = difference between input image dim and convnet feature dim +// e.g. if input img is 200x200 and conv5 is 25x25 ... 200/25=8 -> 8x downsampling in convnet +//JPEGPyramid unstitch_pyramid(Patchwork image_patchwork, float* convnet_planes, int sbin){ +vector unstitch_pyramid_locations(Patchwork &patchwork, + int sbin) +{ + int nbScales = patchwork.nbScales; + vector scaleLocations(nbScales); + int planeWidth = patchwork.MaxCols(); + int planeHeight = patchwork.MaxRows(); + + for(int i=0; i +#include +#include +#include + +using namespace FFLD; +using namespace std; + +// location of a scale within a stitched feature pyramid +// can be used for data in image space or feature decscriptor space +class ScaleLocation{ + public: + int xMin; + int xMax; + int yMin; + int yMax; + int width; + int height; + + int planeID; + //int scaleIdx; //TODO? +}; + + +//image -> multiscale pyramid -> stitch to same-sized planes for Caffe convnet +Patchwork stitch_pyramid(string file, int img_minWidth, int img_minHeight, + int padding, int interval, int planeDim); + +// coordinates for unstitching the feature descriptors from planes. +// sorted in descending order of size. +// (well, Patchwork sorts in descending order of size, and that survives here.) +vector unstitch_pyramid_locations(Patchwork &patchwork, + int sbin); + + +#endif + diff --git a/src/stitch_pyramid/README.txt b/src/stitch_pyramid/README.txt new file mode 100644 index 00000000000..a5bd9bee703 --- /dev/null +++ b/src/stitch_pyramid/README.txt @@ -0,0 +1,29 @@ + + + +This is Forrest's hack to do the following... + +1. Input: image filename from PASCAL VOC detection challenge +2. sample multiscale +3. Output: stich multiscale onto same-sized planes. + (TODO: add a text file that explains where the images were placed in planes!) + + + saves something like this: + inputFilename_plane0.jpg + inputFilename_plane1.jpg + ... + +DONE: + find/replace NbFeatures for NbChannels. + set NbChannels=3 + + in Patchwork.{cpp, h}, change the definition of 'Plane' to JPEGImage + + in stitch_pyramid.cpp, call Patchwork(), with MaxRows_ and MaxCols_ as 'biggest pyra scale, rounded up to a factor of 16' + + add a JPEGImage::pad() function that creates a padded copy. + + in stitch_pyramid.cpp, replace {hog, HOG, Hog} to JPEG + + diff --git a/src/stitch_pyramid/Rectangle.cpp b/src/stitch_pyramid/Rectangle.cpp new file mode 100644 index 00000000000..ad2a3238fd1 --- /dev/null +++ b/src/stitch_pyramid/Rectangle.cpp @@ -0,0 +1,151 @@ +//-------------------------------------------------------------------------------------------------- +// Implementation of the paper "Exact Acceleration of Linear Object Detectors", 12th European +// Conference on Computer Vision, 2012. +// +// Copyright (c) 2012 Idiap Research Institute, +// Written by Charles Dubout +// +// This file is part of FFLD (the Fast Fourier Linear Detector) +// +// FFLD is free software: you can redistribute it and/or modify it under the terms of the GNU +// General Public License version 3 as published by the Free Software Foundation. +// +// FFLD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +// Public License for more details. +// +// You should have received a copy of the GNU General Public License along with FFLD. If not, see +// . +//-------------------------------------------------------------------------------------------------- + +#include "Rectangle.h" + +#include +#include + +using namespace FFLD; +using namespace std; + +Rectangle::Rectangle() : x_(0), y_(0), width_(0), height_(0) +{ +} + +Rectangle::Rectangle(int width, int height) : x_(0), y_(0), width_(width), height_(height) +{ +} + +Rectangle::Rectangle(int x, int y, int width, int height) : x_(x), y_(y), width_(width), +height_(height) +{ +} + +int Rectangle::x() const +{ + return x_; +} + +void Rectangle::setX(int x) +{ + x_ = x; +} + +int Rectangle::y() const +{ + return y_; +} + +void Rectangle::setY(int y) +{ + y_ = y; +} + +int Rectangle::width() const +{ + return width_; +} + +void Rectangle::setWidth(int width) +{ + width_ = width; +} + +int Rectangle::height() const +{ + return height_; +} + +void Rectangle::setHeight(int height) +{ + height_ = height; +} + +int Rectangle::left() const +{ + return x(); +} + +void Rectangle::setLeft(int left) +{ + setWidth(right() - left + 1); + setX(left); +} + +int Rectangle::top() const +{ + return y(); +} + +void Rectangle::setTop(int top) +{ + setHeight(bottom() - top + 1); + setY(top); +} + +int Rectangle::right() const +{ + return x() + width() - 1; +} + +void Rectangle::setRight(int right) +{ + setWidth(right - left() + 1); +} + +int Rectangle::bottom() const +{ + return y() + height() - 1; +} + +void Rectangle::setBottom(int bottom) +{ + setHeight(bottom - top() + 1); +} + +bool Rectangle::empty() const +{ + return (width() <= 0) || (height() <= 0); +} + +int Rectangle::area() const +{ + return max(width(), 0) * max(height(), 0); +} + +ostream & FFLD::operator<<(ostream & os, const Rectangle & rect) +{ + return os << rect.x() << ' ' << rect.y() << ' ' << rect.width() << ' ' << rect.height(); +} + +istream & FFLD::operator>>(istream & is, Rectangle & rect) +{ + int x, y, width, height; + + is >> x >> y >> width >> height; + + rect.setX(x); + rect.setY(y); + rect.setWidth(width); + rect.setHeight(height); + + return is; +} diff --git a/src/stitch_pyramid/Rectangle.h b/src/stitch_pyramid/Rectangle.h new file mode 100644 index 00000000000..404cac6d6c5 --- /dev/null +++ b/src/stitch_pyramid/Rectangle.h @@ -0,0 +1,121 @@ +//-------------------------------------------------------------------------------------------------- +// Implementation of the paper "Exact Acceleration of Linear Object Detectors", 12th European +// Conference on Computer Vision, 2012. +// +// Copyright (c) 2012 Idiap Research Institute, +// Written by Charles Dubout +// +// This file is part of FFLD (the Fast Fourier Linear Detector) +// +// FFLD is free software: you can redistribute it and/or modify it under the terms of the GNU +// General Public License version 3 as published by the Free Software Foundation. +// +// FFLD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +// Public License for more details. +// +// You should have received a copy of the GNU General Public License along with FFLD. If not, see +// . +//-------------------------------------------------------------------------------------------------- + +#ifndef FFLD_RECTANGLE_H +#define FFLD_RECTANGLE_H + +#include + +namespace FFLD +{ +/// The Rectangle class defines a rectangle in the plane using integer precision. If the coordinates +/// of the top left corner of the rectangle are (x, y), the coordinates of the bottom right corner +/// are (x + width - 1, y + height - 1), where width and height are the dimensions of the rectangle. +/// The corners are thus understood as the extremal points still inside the rectangle. +class Rectangle +{ +public: + /// Constructs an empty rectangle. An empty rectangle has no area. + Rectangle(); + + /// Constructs a rectangle with the given @p width and @p height. + Rectangle(int width, int height); + + /// Constructs a rectangle with coordinates (@p x, @p y) and the given @p width and @p height. + Rectangle(int x, int y, int width, int height); + + /// Returns the x-coordinate of the rectangle. + int x() const; + + /// Sets the x coordinate of the rectangle to @p x. + void setX(int x); + + /// Returns the y-coordinate of the rectangle. + int y() const; + + /// Sets the y coordinate of the rectangle to @p y. + void setY(int y); + + /// Returns the width of the rectangle. + int width() const; + + /// Sets the height of the rectangle to the given @p width. + void setWidth(int width); + + /// Returns the height of the rectangle. + int height() const; + + /// Sets the height of the rectangle to the given @p height. + void setHeight(int height); + + /// Returns the left side of the rectangle. + /// @note Equivalent to x(). + int left() const; + + /// Sets the left side of the rectangle to @p left. + /// @note The right side of the rectangle is not modified. + void setLeft(int left); + + /// Returns the top side of the rectangle. + /// @note Equivalent to y(). + int top() const; + + /// Sets the top side of the rectangle to @p top. + /// @note The bottom side of the rectangle is not modified. + void setTop(int top); + + /// Returns the right side of the rectangle. + /// @note Equivalent to x() + width() - 1. + int right() const; + + /// Sets the right side of the rectangle to @p right. + /// @note The left side of the rectangle is not modified. + void setRight(int right); + + /// Returns the bottom side of the rectangle. + /// @note Equivalent to y() + height() - 1. + int bottom() const; + + /// Sets the bottom side of the rectangle to @p bottom. + /// @note The top side of the rectangle is not modified. + void setBottom(int bottom); + + /// Returns whether the rectangle is empty. An empty rectangle has no area. + bool empty() const; + + /// Returns the area of the rectangle. + /// @note Equivalent to max(width(), 0) * max(height(), 0). + int area() const; + +private: + int x_; + int y_; + int width_; + int height_; +}; + +/// Serializes a rectangle to a stream. +std::ostream & operator<<(std::ostream & os, const Rectangle & rect); + +/// Unserializes a rectangle from a stream. +std::istream & operator>>(std::istream & is, Rectangle & rect); +} + +#endif diff --git a/src/stitch_pyramid/SimpleOpt.h b/src/stitch_pyramid/SimpleOpt.h new file mode 100644 index 00000000000..bc8d5525831 --- /dev/null +++ b/src/stitch_pyramid/SimpleOpt.h @@ -0,0 +1,1060 @@ +/*! @file SimpleOpt.h + + @version 3.5 + + @brief A cross-platform command line library which can parse almost any + of the standard command line formats in use today. It is designed + explicitly to be portable to any platform and has been tested on Windows + and Linux. See CSimpleOptTempl for the class definition. + + @section features FEATURES + + - MIT Licence allows free use in all software (including GPL + and commercial) + - multi-platform (Windows 95/98/ME/NT/2K/XP, Linux, Unix) + - supports all lengths of option names: + +
- + switch character only (e.g. use stdin for input) +
-o + short (single character) +
-long + long (multiple character, single switch character) +
--longer + long (multiple character, multiple switch characters) +
+ - supports all types of arguments for options: + +
--option + short/long option flag (no argument) +
--option ARG + short/long option with separate required argument +
--option=ARG + short/long option with combined required argument +
--option[=ARG] + short/long option with combined optional argument +
-oARG + short option with combined required argument +
-o[ARG] + short option with combined optional argument +
+ - supports options with multiple or variable numbers of arguments: + +
--multi ARG1 ARG2 + Multiple arguments +
--multi N ARG-1 ARG-2 ... ARG-N + Variable number of arguments +
+ - supports case-insensitive option matching on short, long and/or + word arguments. + - supports options which do not use a switch character. i.e. a special + word which is construed as an option. + e.g. "foo.exe open /directory/file.txt" + - supports clumping of multiple short options (no arguments) in a string + e.g. "foo.exe -abcdef file1" <==> "foo.exe -a -b -c -d -e -f file1" + - automatic recognition of a single slash as equivalent to a single + hyphen on Windows, e.g. "/f FILE" is equivalent to "-f FILE". + - file arguments can appear anywhere in the argument list: + "foo.exe file1.txt -a ARG file2.txt --flag file3.txt file4.txt" + files will be returned to the application in the same order they were + supplied on the command line + - short-circuit option matching: "--man" will match "--mandate" + invalid options can be handled while continuing to parse the command + line valid options list can be changed dynamically during command line + processing, i.e. accept different options depending on an option + supplied earlier in the command line. + - implemented with only a single C++ header file + - optionally use no C runtime or OS functions + - char, wchar_t and Windows TCHAR in the same program + - complete working examples included + - compiles cleanly at warning level 4 (Windows/VC.NET 2003), warning + level 3 (Windows/VC6) and -Wall (Linux/gcc) + + @section usage USAGE + + The SimpleOpt class is used by following these steps: + +
    +
  1. Include the SimpleOpt.h header file + +
    +        \#include "SimpleOpt.h"
    +        
    + +
  2. Define an array of valid options for your program. + +
    +@link CSimpleOptTempl::SOption CSimpleOpt::SOption @endlink g_rgOptions[] = {
    +    { OPT_FLAG, _T("-a"),     SO_NONE    }, // "-a"
    +    { OPT_FLAG, _T("-b"),     SO_NONE    }, // "-b"
    +    { OPT_ARG,  _T("-f"),     SO_REQ_SEP }, // "-f ARG"
    +    { OPT_HELP, _T("-?"),     SO_NONE    }, // "-?"
    +    { OPT_HELP, _T("--help"), SO_NONE    }, // "--help"
    +    SO_END_OF_OPTIONS                       // END
    +};
    +
    + + Note that all options must start with a hyphen even if the slash will + be accepted. This is because the slash character is automatically + converted into a hyphen to test against the list of options. + For example, the following line matches both "-?" and "/?" + (on Windows). + +
    +        { OPT_HELP, _T("-?"),     SO_NONE    }, // "-?"
    +        
    + +
  3. Instantiate a CSimpleOpt object supplying argc, argv and the option + table + +
    +@link CSimpleOptTempl CSimpleOpt @endlink args(argc, argv, g_rgOptions);
    +
    + +
  4. Process the arguments by calling Next() until it returns false. + On each call, first check for an error by calling LastError(), then + either handle the error or process the argument. + +
    +while (args.Next()) {
    +    if (args.LastError() == SO_SUCCESS) {
    +        handle option: use OptionId(), OptionText() and OptionArg()
    +    }
    +    else {
    +        handle error: see ESOError enums
    +    }
    +}
    +
    + +
  5. Process all non-option arguments with File(), Files() and FileCount() + +
    +ShowFiles(args.FileCount(), args.Files());
    +
    + +
+ + @section notes NOTES + + - In MBCS mode, this library is guaranteed to work correctly only when + all option names use only ASCII characters. + - Note that if case-insensitive matching is being used then the first + matching option in the argument list will be returned. + + @section licence MIT LICENCE + + The licence text below is the boilerplate "MIT Licence" used from: + http://www.opensource.org/licenses/mit-license.php + + Copyright (c) 2006-2007, Brodie Thiesfield + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/*! @mainpage + + +
Library SimpleOpt +
Author Brodie Thiesfield [code at jellycan dot com] +
Source http://code.jellycan.com/simpleopt/ +
+ + @section SimpleOpt SimpleOpt + + A cross-platform library providing a simple method to parse almost any of + the standard command-line formats in use today. + + See the @link SimpleOpt.h SimpleOpt @endlink documentation for full + details. + + @section SimpleGlob SimpleGlob + + A cross-platform file globbing library providing the ability to + expand wildcards in command-line arguments to a list of all matching + files. + + See the @link SimpleGlob.h SimpleGlob @endlink documentation for full + details. +*/ + +#ifndef INCLUDED_SimpleOpt +#define INCLUDED_SimpleOpt + +// Default the max arguments to a fixed value. If you want to be able to +// handle any number of arguments, then predefine this to 0 and it will +// use an internal dynamically allocated buffer instead. +#ifdef SO_MAX_ARGS +# define SO_STATICBUF SO_MAX_ARGS +#else +# include // malloc, free +# include // memcpy +# define SO_STATICBUF 50 +#endif + +//! Error values +typedef enum _ESOError +{ + //! No error + SO_SUCCESS = 0, + + /*! It looks like an option (it starts with a switch character), but + it isn't registered in the option table. */ + SO_OPT_INVALID = -1, + + /*! Multiple options matched the supplied option text. + Only returned when NOT using SO_O_EXACT. */ + SO_OPT_MULTIPLE = -2, + + /*! Option doesn't take an argument, but a combined argument was + supplied. */ + SO_ARG_INVALID = -3, + + /*! SO_REQ_CMB style-argument was supplied to a SO_REQ_SEP option + Only returned when using SO_O_PEDANTIC. */ + SO_ARG_INVALID_TYPE = -4, + + //! Required argument was not supplied + SO_ARG_MISSING = -5, + + /*! Option argument looks like another option. + Only returned when NOT using SO_O_NOERR. */ + SO_ARG_INVALID_DATA = -6 +} ESOError; + +//! Option flags +enum _ESOFlags +{ + /*! Disallow partial matching of option names */ + SO_O_EXACT = 0x0001, + + /*! Disallow use of slash as an option marker on Windows. + Un*x only ever recognizes a hyphen. */ + SO_O_NOSLASH = 0x0002, + + /*! Permit arguments on single letter options with no equals sign. + e.g. -oARG or -o[ARG] */ + SO_O_SHORTARG = 0x0004, + + /*! Permit single character options to be clumped into a single + option string. e.g. "-a -b -c" <==> "-abc" */ + SO_O_CLUMP = 0x0008, + + /*! Process the entire argv array for options, including the + argv[0] entry. */ + SO_O_USEALL = 0x0010, + + /*! Do not generate an error for invalid options. errors for missing + arguments will still be generated. invalid options will be + treated as files. invalid options in clumps will be silently + ignored. */ + SO_O_NOERR = 0x0020, + + /*! Validate argument type pedantically. Return an error when a + separated argument "-opt arg" is supplied by the user as a + combined argument "-opt=arg". By default this is not considered + an error. */ + SO_O_PEDANTIC = 0x0040, + + /*! Case-insensitive comparisons for short arguments */ + SO_O_ICASE_SHORT = 0x0100, + + /*! Case-insensitive comparisons for long arguments */ + SO_O_ICASE_LONG = 0x0200, + + /*! Case-insensitive comparisons for word arguments + i.e. arguments without any hyphens at the start. */ + SO_O_ICASE_WORD = 0x0400, + + /*! Case-insensitive comparisons for all arg types */ + SO_O_ICASE = 0x0700 +}; + +/*! Types of arguments that options may have. Note that some of the _ESOFlags + are not compatible with all argument types. SO_O_SHORTARG requires that + relevant options use either SO_REQ_CMB or SO_OPT. SO_O_CLUMP requires + that relevant options use only SO_NONE. + */ +typedef enum _ESOArgType { + /*! No argument. Just the option flags. + e.g. -o --opt */ + SO_NONE, + + /*! Required separate argument. + e.g. -o ARG --opt ARG */ + SO_REQ_SEP, + + /*! Required combined argument. + e.g. -oARG -o=ARG --opt=ARG */ + SO_REQ_CMB, + + /*! Optional combined argument. + e.g. -o[ARG] -o[=ARG] --opt[=ARG] */ + SO_OPT, + + /*! Multiple separate arguments. The actual number of arguments is + determined programatically at the time the argument is processed. + e.g. -o N ARG1 ARG2 ... ARGN --opt N ARG1 ARG2 ... ARGN */ + SO_MULTI +} ESOArgType; + +//! this option definition must be the last entry in the table +#define SO_END_OF_OPTIONS { -1, NULL, SO_NONE } + +#ifdef _DEBUG +# ifdef _MSC_VER +# include +# define SO_ASSERT(b) _ASSERTE(b) +# else +# include +# define SO_ASSERT(b) assert(b) +# endif +#else +# define SO_ASSERT(b) //!< assertion used to test input data +#endif + +// --------------------------------------------------------------------------- +// MAIN TEMPLATE CLASS +// --------------------------------------------------------------------------- + +/*! @brief Implementation of the SimpleOpt class */ +template +class CSimpleOptTempl +{ +public: + /*! @brief Structure used to define all known options. */ + struct SOption { + /*! ID to return for this flag. Optional but must be >= 0 */ + int nId; + + /*! arg string to search for, e.g. "open", "-", "-f", "--file" + Note that on Windows the slash option marker will be converted + to a hyphen so that "-f" will also match "/f". */ + const SOCHAR * pszArg; + + /*! type of argument accepted by this option */ + ESOArgType nArgType; + }; + + /*! @brief Initialize the class. Init() must be called later. */ + CSimpleOptTempl() + : m_rgShuffleBuf(NULL) + { + Init(0, NULL, NULL, 0); + } + + /*! @brief Initialize the class in preparation for use. */ + CSimpleOptTempl( + int argc, + SOCHAR * argv[], + const SOption * a_rgOptions, + int a_nFlags = 0 + ) + : m_rgShuffleBuf(NULL) + { + Init(argc, argv, a_rgOptions, a_nFlags); + } + +#ifndef SO_MAX_ARGS + /*! @brief Deallocate any allocated memory. */ + ~CSimpleOptTempl() { if (m_rgShuffleBuf) free(m_rgShuffleBuf); } +#endif + + /*! @brief Initialize the class in preparation for calling Next. + + The table of options pointed to by a_rgOptions does not need to be + valid at the time that Init() is called. However on every call to + Next() the table pointed to must be a valid options table with the + last valid entry set to SO_END_OF_OPTIONS. + + NOTE: the array pointed to by a_argv will be modified by this + class and must not be used or modified outside of member calls to + this class. + + @param a_argc Argument array size + @param a_argv Argument array + @param a_rgOptions Valid option array + @param a_nFlags Optional flags to modify the processing of + the arguments + + @return true Successful + @return false if SO_MAX_ARGC > 0: Too many arguments + if SO_MAX_ARGC == 0: Memory allocation failure + */ + bool Init( + int a_argc, + SOCHAR * a_argv[], + const SOption * a_rgOptions, + int a_nFlags = 0 + ); + + /*! @brief Change the current options table during option parsing. + + @param a_rgOptions Valid option array + */ + inline void SetOptions(const SOption * a_rgOptions) { + m_rgOptions = a_rgOptions; + } + + /*! @brief Change the current flags during option parsing. + + Note that changing the SO_O_USEALL flag here will have no affect. + It must be set using Init() or the constructor. + + @param a_nFlags Flags to modify the processing of the arguments + */ + inline void SetFlags(int a_nFlags) { m_nFlags = a_nFlags; } + + /*! @brief Query if a particular flag is set */ + inline bool HasFlag(int a_nFlag) const { + return (m_nFlags & a_nFlag) == a_nFlag; + } + + /*! @brief Advance to the next option if available. + + When all options have been processed it will return false. When true + has been returned, you must check for an invalid or unrecognized + option using the LastError() method. This will be return an error + value other than SO_SUCCESS on an error. All standard data + (e.g. OptionText(), OptionArg(), OptionId(), etc) will be available + depending on the error. + + After all options have been processed, the remaining files from the + command line can be processed in same order as they were passed to + the program. + + @return true option or error available for processing + @return false all options have been processed + */ + bool Next(); + + /*! Stops processing of the command line and returns all remaining + arguments as files. The next call to Next() will return false. + */ + void Stop(); + + /*! @brief Return the last error that occurred. + + This function must always be called before processing the current + option. This function is available only when Next() has returned true. + */ + inline ESOError LastError() const { return m_nLastError; } + + /*! @brief Return the nId value from the options array for the current + option. + + This function is available only when Next() has returned true. + */ + inline int OptionId() const { return m_nOptionId; } + + /*! @brief Return the pszArg from the options array for the current + option. + + This function is available only when Next() has returned true. + */ + inline const SOCHAR * OptionText() const { return m_pszOptionText; } + + /*! @brief Return the argument for the current option where one exists. + + If there is no argument for the option, this will return NULL. + This function is available only when Next() has returned true. + */ + inline SOCHAR * OptionArg() const { return m_pszOptionArg; } + + /*! @brief Validate and return the desired number of arguments. + + This is only valid when OptionId() has return the ID of an option + that is registered as SO_MULTI. It may be called multiple times + each time returning the desired number of arguments. Previously + returned argument pointers are remain valid. + + If an error occurs during processing, NULL will be returned and + the error will be available via LastError(). + + @param n Number of arguments to return. + */ + SOCHAR ** MultiArg(int n); + + /*! @brief Returned the number of entries in the Files() array. + + After Next() has returned false, this will be the list of files (or + otherwise unprocessed arguments). + */ + inline int FileCount() const { return m_argc - m_nLastArg; } + + /*! @brief Return the specified file argument. + + @param n Index of the file to return. This must be between 0 + and FileCount() - 1; + */ + inline SOCHAR * File(int n) const { + SO_ASSERT(n >= 0 && n < FileCount()); + return m_argv[m_nLastArg + n]; + } + + /*! @brief Return the array of files. */ + inline SOCHAR ** Files() const { return &m_argv[m_nLastArg]; } + +private: + CSimpleOptTempl(const CSimpleOptTempl &); // disabled + CSimpleOptTempl & operator=(const CSimpleOptTempl &); // disabled + + SOCHAR PrepareArg(SOCHAR * a_pszString) const; + bool NextClumped(); + void ShuffleArg(int a_nStartIdx, int a_nCount); + int LookupOption(const SOCHAR * a_pszOption) const; + int CalcMatch(const SOCHAR *a_pszSource, const SOCHAR *a_pszTest) const; + + // Find the '=' character within a string. + inline SOCHAR * FindEquals(SOCHAR *s) const { + while (*s && *s != (SOCHAR)'=') ++s; + return *s ? s : NULL; + } + bool IsEqual(SOCHAR a_cLeft, SOCHAR a_cRight, int a_nArgType) const; + + inline void Copy(SOCHAR ** ppDst, SOCHAR ** ppSrc, int nCount) const { +#ifdef SO_MAX_ARGS + // keep our promise of no CLIB usage + while (nCount-- > 0) *ppDst++ = *ppSrc++; +#else + memcpy(ppDst, ppSrc, nCount * sizeof(SOCHAR*)); +#endif + } + +private: + const SOption * m_rgOptions; //!< pointer to options table + int m_nFlags; //!< flags + int m_nOptionIdx; //!< current argv option index + int m_nOptionId; //!< id of current option (-1 = invalid) + int m_nNextOption; //!< index of next option + int m_nLastArg; //!< last argument, after this are files + int m_argc; //!< argc to process + SOCHAR ** m_argv; //!< argv + const SOCHAR * m_pszOptionText; //!< curr option text, e.g. "-f" + SOCHAR * m_pszOptionArg; //!< curr option arg, e.g. "c:\file.txt" + SOCHAR * m_pszClump; //!< clumped single character options + SOCHAR m_szShort[3]; //!< temp for clump and combined args + ESOError m_nLastError; //!< error status from the last call + SOCHAR ** m_rgShuffleBuf; //!< shuffle buffer for large argc +}; + +// --------------------------------------------------------------------------- +// IMPLEMENTATION +// --------------------------------------------------------------------------- + +template +bool +CSimpleOptTempl::Init( + int a_argc, + SOCHAR * a_argv[], + const SOption * a_rgOptions, + int a_nFlags + ) +{ + m_argc = a_argc; + m_nLastArg = a_argc; + m_argv = a_argv; + m_rgOptions = a_rgOptions; + m_nLastError = SO_SUCCESS; + m_nOptionIdx = 0; + m_nOptionId = -1; + m_pszOptionText = NULL; + m_pszOptionArg = NULL; + m_nNextOption = (a_nFlags & SO_O_USEALL) ? 0 : 1; + m_szShort[0] = (SOCHAR)'-'; + m_szShort[2] = (SOCHAR)'\0'; + m_nFlags = a_nFlags; + m_pszClump = NULL; + +#ifdef SO_MAX_ARGS + if (m_argc > SO_MAX_ARGS) { + m_nLastError = SO_ARG_INVALID_DATA; + m_nLastArg = 0; + return false; + } +#else + if (m_rgShuffleBuf) { + free(m_rgShuffleBuf); + } + if (m_argc > SO_STATICBUF) { + m_rgShuffleBuf = (SOCHAR**) malloc(sizeof(SOCHAR*) * m_argc); + if (!m_rgShuffleBuf) { + return false; + } + } +#endif + + return true; +} + +template +bool +CSimpleOptTempl::Next() +{ +#ifdef SO_MAX_ARGS + if (m_argc > SO_MAX_ARGS) { + SO_ASSERT(!"Too many args! Check the return value of Init()!"); + return false; + } +#endif + + // process a clumped option string if appropriate + if (m_pszClump && *m_pszClump) { + // silently discard invalid clumped option + bool bIsValid = NextClumped(); + while (*m_pszClump && !bIsValid && HasFlag(SO_O_NOERR)) { + bIsValid = NextClumped(); + } + + // return this option if valid or we are returning errors + if (bIsValid || !HasFlag(SO_O_NOERR)) { + return true; + } + } + SO_ASSERT(!m_pszClump || !*m_pszClump); + m_pszClump = NULL; + + // init for the next option + m_nOptionIdx = m_nNextOption; + m_nOptionId = -1; + m_pszOptionText = NULL; + m_pszOptionArg = NULL; + m_nLastError = SO_SUCCESS; + + // find the next option + SOCHAR cFirst; + int nTableIdx = -1; + int nOptIdx = m_nOptionIdx; + while (nTableIdx < 0 && nOptIdx < m_nLastArg) { + SOCHAR * pszArg = m_argv[nOptIdx]; + m_pszOptionArg = NULL; + + // find this option in the options table + cFirst = PrepareArg(pszArg); + if (pszArg[0] == (SOCHAR)'-') { + // find any combined argument string and remove equals sign + m_pszOptionArg = FindEquals(pszArg); + if (m_pszOptionArg) { + *m_pszOptionArg++ = (SOCHAR)'\0'; + } + } + nTableIdx = LookupOption(pszArg); + + // if we didn't find this option but if it is a short form + // option then we try the alternative forms + if (nTableIdx < 0 + && !m_pszOptionArg + && pszArg[0] == (SOCHAR)'-' + && pszArg[1] + && pszArg[1] != (SOCHAR)'-' + && pszArg[2]) + { + // test for a short-form with argument if appropriate + if (HasFlag(SO_O_SHORTARG)) { + m_szShort[1] = pszArg[1]; + int nIdx = LookupOption(m_szShort); + if (nIdx >= 0 + && (m_rgOptions[nIdx].nArgType == SO_REQ_CMB + || m_rgOptions[nIdx].nArgType == SO_OPT)) + { + m_pszOptionArg = &pszArg[2]; + pszArg = m_szShort; + nTableIdx = nIdx; + } + } + + // test for a clumped short-form option string and we didn't + // match on the short-form argument above + if (nTableIdx < 0 && HasFlag(SO_O_CLUMP)) { + m_pszClump = &pszArg[1]; + ++m_nNextOption; + if (nOptIdx > m_nOptionIdx) { + ShuffleArg(m_nOptionIdx, nOptIdx - m_nOptionIdx); + } + return Next(); + } + } + + // The option wasn't found. If it starts with a switch character + // and we are not suppressing errors for invalid options then it + // is reported as an error, otherwise it is data. + if (nTableIdx < 0) { + if (!HasFlag(SO_O_NOERR) && pszArg[0] == (SOCHAR)'-') { + m_pszOptionText = pszArg; + break; + } + + pszArg[0] = cFirst; + ++nOptIdx; + if (m_pszOptionArg) { + *(--m_pszOptionArg) = (SOCHAR)'='; + } + } + } + + // end of options + if (nOptIdx >= m_nLastArg) { + if (nOptIdx > m_nOptionIdx) { + ShuffleArg(m_nOptionIdx, nOptIdx - m_nOptionIdx); + } + return false; + } + ++m_nNextOption; + + // get the option id + ESOArgType nArgType = SO_NONE; + if (nTableIdx < 0) { + m_nLastError = (ESOError) nTableIdx; // error code + } + else { + m_nOptionId = m_rgOptions[nTableIdx].nId; + m_pszOptionText = m_rgOptions[nTableIdx].pszArg; + + // ensure that the arg type is valid + nArgType = m_rgOptions[nTableIdx].nArgType; + switch (nArgType) { + case SO_NONE: + if (m_pszOptionArg) { + m_nLastError = SO_ARG_INVALID; + } + break; + + case SO_REQ_SEP: + if (m_pszOptionArg) { + // they wanted separate args, but we got a combined one, + // unless we are pedantic, just accept it. + if (HasFlag(SO_O_PEDANTIC)) { + m_nLastError = SO_ARG_INVALID_TYPE; + } + } + // more processing after we shuffle + break; + + case SO_REQ_CMB: + if (!m_pszOptionArg) { + m_nLastError = SO_ARG_MISSING; + } + break; + + case SO_OPT: + // nothing to do + break; + + case SO_MULTI: + // nothing to do. Caller must now check for valid arguments + // using GetMultiArg() + break; + } + } + + // shuffle the files out of the way + if (nOptIdx > m_nOptionIdx) { + ShuffleArg(m_nOptionIdx, nOptIdx - m_nOptionIdx); + } + + // we need to return the separate arg if required, just re-use the + // multi-arg code because it all does the same thing + if ( nArgType == SO_REQ_SEP + && !m_pszOptionArg + && m_nLastError == SO_SUCCESS) + { + SOCHAR ** ppArgs = MultiArg(1); + if (ppArgs) { + m_pszOptionArg = *ppArgs; + } + } + + return true; +} + +template +void +CSimpleOptTempl::Stop() +{ + if (m_nNextOption < m_nLastArg) { + ShuffleArg(m_nNextOption, m_nLastArg - m_nNextOption); + } +} + +template +SOCHAR +CSimpleOptTempl::PrepareArg( + SOCHAR * a_pszString + ) const +{ +#ifdef _WIN32 + // On Windows we can accept the forward slash as a single character + // option delimiter, but it cannot replace the '-' option used to + // denote stdin. On Un*x paths may start with slash so it may not + // be used to start an option. + if (!HasFlag(SO_O_NOSLASH) + && a_pszString[0] == (SOCHAR)'/' + && a_pszString[1] + && a_pszString[1] != (SOCHAR)'-') + { + a_pszString[0] = (SOCHAR)'-'; + return (SOCHAR)'/'; + } +#endif + return a_pszString[0]; +} + +template +bool +CSimpleOptTempl::NextClumped() +{ + // prepare for the next clumped option + m_szShort[1] = *m_pszClump++; + m_nOptionId = -1; + m_pszOptionText = NULL; + m_pszOptionArg = NULL; + m_nLastError = SO_SUCCESS; + + // lookup this option, ensure that we are using exact matching + int nSavedFlags = m_nFlags; + m_nFlags = SO_O_EXACT; + int nTableIdx = LookupOption(m_szShort); + m_nFlags = nSavedFlags; + + // unknown option + if (nTableIdx < 0) { + m_nLastError = (ESOError) nTableIdx; // error code + return false; + } + + // valid option + m_pszOptionText = m_rgOptions[nTableIdx].pszArg; + ESOArgType nArgType = m_rgOptions[nTableIdx].nArgType; + if (nArgType == SO_NONE) { + m_nOptionId = m_rgOptions[nTableIdx].nId; + return true; + } + + if (nArgType == SO_REQ_CMB && *m_pszClump) { + m_nOptionId = m_rgOptions[nTableIdx].nId; + m_pszOptionArg = m_pszClump; + while (*m_pszClump) ++m_pszClump; // must point to an empty string + return true; + } + + // invalid option as it requires an argument + m_nLastError = SO_ARG_MISSING; + return true; +} + +// Shuffle arguments to the end of the argv array. +// +// For example: +// argv[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8" }; +// +// ShuffleArg(1, 1) = { "0", "2", "3", "4", "5", "6", "7", "8", "1" }; +// ShuffleArg(5, 2) = { "0", "1", "2", "3", "4", "7", "8", "5", "6" }; +// ShuffleArg(2, 4) = { "0", "1", "6", "7", "8", "2", "3", "4", "5" }; +template +void +CSimpleOptTempl::ShuffleArg( + int a_nStartIdx, + int a_nCount + ) +{ + SOCHAR * staticBuf[SO_STATICBUF]; + SOCHAR ** buf = m_rgShuffleBuf ? m_rgShuffleBuf : staticBuf; + int nTail = m_argc - a_nStartIdx - a_nCount; + + // make a copy of the elements to be moved + Copy(buf, m_argv + a_nStartIdx, a_nCount); + + // move the tail down + Copy(m_argv + a_nStartIdx, m_argv + a_nStartIdx + a_nCount, nTail); + + // append the moved elements to the tail + Copy(m_argv + a_nStartIdx + nTail, buf, a_nCount); + + // update the index of the last unshuffled arg + m_nLastArg -= a_nCount; +} + +// match on the long format strings. partial matches will be +// accepted only if that feature is enabled. +template +int +CSimpleOptTempl::LookupOption( + const SOCHAR * a_pszOption + ) const +{ + int nBestMatch = -1; // index of best match so far + int nBestMatchLen = 0; // matching characters of best match + int nLastMatchLen = 0; // matching characters of last best match + + for (int n = 0; m_rgOptions[n].nId >= 0; ++n) { + // the option table must use hyphens as the option character, + // the slash character is converted to a hyphen for testing. + SO_ASSERT(m_rgOptions[n].pszArg[0] != (SOCHAR)'/'); + + int nMatchLen = CalcMatch(m_rgOptions[n].pszArg, a_pszOption); + if (nMatchLen == -1) { + return n; + } + if (nMatchLen > 0 && nMatchLen >= nBestMatchLen) { + nLastMatchLen = nBestMatchLen; + nBestMatchLen = nMatchLen; + nBestMatch = n; + } + } + + // only partial matches or no match gets to here, ensure that we + // don't return a partial match unless it is a clear winner + if (HasFlag(SO_O_EXACT) || nBestMatch == -1) { + return SO_OPT_INVALID; + } + return (nBestMatchLen > nLastMatchLen) ? nBestMatch : SO_OPT_MULTIPLE; +} + +// calculate the number of characters that match (case-sensitive) +// 0 = no match, > 0 == number of characters, -1 == perfect match +template +int +CSimpleOptTempl::CalcMatch( + const SOCHAR * a_pszSource, + const SOCHAR * a_pszTest + ) const +{ + if (!a_pszSource || !a_pszTest) { + return 0; + } + + // determine the argument type + int nArgType = SO_O_ICASE_LONG; + if (a_pszSource[0] != '-') { + nArgType = SO_O_ICASE_WORD; + } + else if (a_pszSource[1] != '-' && !a_pszSource[2]) { + nArgType = SO_O_ICASE_SHORT; + } + + // match and skip leading hyphens + while (*a_pszSource == (SOCHAR)'-' && *a_pszSource == *a_pszTest) { + ++a_pszSource; + ++a_pszTest; + } + if (*a_pszSource == (SOCHAR)'-' || *a_pszTest == (SOCHAR)'-') { + return 0; + } + + // find matching number of characters in the strings + int nLen = 0; + while (*a_pszSource && IsEqual(*a_pszSource, *a_pszTest, nArgType)) { + ++a_pszSource; + ++a_pszTest; + ++nLen; + } + + // if we have exhausted the source... + if (!*a_pszSource) { + // and the test strings, then it's a perfect match + if (!*a_pszTest) { + return -1; + } + + // otherwise the match failed as the test is longer than + // the source. i.e. "--mant" will not match the option "--man". + return 0; + } + + // if we haven't exhausted the test string then it is not a match + // i.e. "--mantle" will not best-fit match to "--mandate" at all. + if (*a_pszTest) { + return 0; + } + + // partial match to the current length of the test string + return nLen; +} + +template +bool +CSimpleOptTempl::IsEqual( + SOCHAR a_cLeft, + SOCHAR a_cRight, + int a_nArgType + ) const +{ + // if this matches then we are doing case-insensitive matching + if (m_nFlags & a_nArgType) { + if (a_cLeft >= 'A' && a_cLeft <= 'Z') a_cLeft += 'a' - 'A'; + if (a_cRight >= 'A' && a_cRight <= 'Z') a_cRight += 'a' - 'A'; + } + return a_cLeft == a_cRight; +} + +// calculate the number of characters that match (case-sensitive) +// 0 = no match, > 0 == number of characters, -1 == perfect match +template +SOCHAR ** +CSimpleOptTempl::MultiArg( + int a_nCount + ) +{ + // ensure we have enough arguments + if (m_nNextOption + a_nCount > m_nLastArg) { + m_nLastError = SO_ARG_MISSING; + return NULL; + } + + // our argument array + SOCHAR ** rgpszArg = &m_argv[m_nNextOption]; + + // Ensure that each of the following don't start with an switch character. + // Only make this check if we are returning errors for unknown arguments. + if (!HasFlag(SO_O_NOERR)) { + for (int n = 0; n < a_nCount; ++n) { + SOCHAR ch = PrepareArg(rgpszArg[n]); + if (rgpszArg[n][0] == (SOCHAR)'-') { + rgpszArg[n][0] = ch; + m_nLastError = SO_ARG_INVALID_DATA; + return NULL; + } + rgpszArg[n][0] = ch; + } + } + + // all good + m_nNextOption += a_nCount; + return rgpszArg; +} + + +// --------------------------------------------------------------------------- +// TYPE DEFINITIONS +// --------------------------------------------------------------------------- + +/*! @brief ASCII/MBCS version of CSimpleOpt */ +typedef CSimpleOptTempl CSimpleOptA; + +/*! @brief wchar_t version of CSimpleOpt */ +typedef CSimpleOptTempl CSimpleOptW; + +#if defined(_UNICODE) +/*! @brief TCHAR version dependent on if _UNICODE is defined */ +# define CSimpleOpt CSimpleOptW +#else +/*! @brief TCHAR version dependent on if _UNICODE is defined */ +# define CSimpleOpt CSimpleOptA +#endif + +#endif // INCLUDED_SimpleOpt diff --git a/src/stitch_pyramid/build/Makefile b/src/stitch_pyramid/build/Makefile new file mode 100644 index 00000000000..0d672bbd1ba --- /dev/null +++ b/src/stitch_pyramid/build/Makefile @@ -0,0 +1,50 @@ +CXX = g++ +CFLAGS = -g -fopenmp -O3 -fPIC -I/usr/local/include/ -I.. +LDLIBS = -g -lgomp -ljpeg +#OBJS = JPEGPyramid.o JPEGImage.o Patchwork.o Rectangle.o PyramidStitcher.o test_stitch_pyramid.o +OBJS = JPEGPyramid.o JPEGImage.o Patchwork.o Rectangle.o PyramidStitcher.o +all: libPyramidStitcher.so test_stitch_pyramid +#all: libPyramidStitcher.so libPyramidStitcher.a test_stitch_pyramid + +# *** test suite *** + +# dynamic link option +test_stitch_pyramid: test_stitch_pyramid.o libPyramidStitcher.so + $(CXX) -o test_stitch_pyramid test_stitch_pyramid.o -L. -lPyramidStitcher $(LDLIBS) + +# static link option (doesn't like static build w/ openmp) +#test_stitch_pyramid: test_stitch_pyramid.o libPyramidStitcher.a +# $(CXX) -o test_stitch_pyramid test_stitch_pyramid.o -lPyramidStitcher $(LDLIBS) + +# OLD: link directly with .o files instead of linking with PyramidStitcher.so +#test_stitch_pyramid: $(OBJS) +# $(CXX) -o test_stitch_pyramid $(OBJS) $(LDLIBS) + +test_stitch_pyramid.o: ../test_stitch_pyramid.cpp ../PyramidStitcher.h ../JPEGPyramid.h ../JPEGImage.h ../Patchwork.h + $(CXX) $(CFLAGS) -c ../test_stitch_pyramid.cpp + +# *** build deployable shared object binary *** +libPyramidStitcher.so: $(OBJS) + $(CXX) $(OBJS) -shared -o libPyramidStitcher.so $(LDLIBS) + +libPyramidStitcher.a: $(OBJS) + $(CXX) $(OBJS) -static -o libPyramidStitcher.a $(LDLIBS) + +PyramidStitcher.o: ../PyramidStitcher.cpp ../PyramidStitcher.h ../JPEGPyramid.h ../JPEGImage.h ../Patchwork.h + $(CXX) $(CFLAGS) -c ../PyramidStitcher.cpp + +JPEGPyramid.o: ../JPEGPyramid.cpp ../JPEGPyramid.h ../JPEGImage.h + $(CXX) $(CFLAGS) -c ../JPEGPyramid.cpp + +JPEGImage.o: ../JPEGImage.cpp ../JPEGImage.h + $(CXX) $(CFLAGS) -c ../JPEGImage.cpp + +Patchwork.o: ../Patchwork.cpp ../Patchwork.h ../JPEGPyramid.h ../Rectangle.h + $(CXX) $(CFLAGS) -c ../Patchwork.cpp + +Rectangle.o: ../Rectangle.cpp ../Rectangle.h + $(CXX) $(CFLAGS) -c ../Rectangle.cpp + +clean: + rm -f *~ *.so *.o *.mex* *.obj + diff --git a/src/stitch_pyramid/build/demo.sh b/src/stitch_pyramid/build/demo.sh new file mode 100755 index 00000000000..fb66ff63071 --- /dev/null +++ b/src/stitch_pyramid/build/demo.sh @@ -0,0 +1,9 @@ +#./stitch_pyramid ../../../images_640x480/carsgraz_001.image.jpg +#./stitch_pyramid --padding 8 ../../images_640x480/carsgraz_001.image.jpg + +./test_stitch_pyramid --padding 8 --output-stitched-dir ./stitched_results ../../../python/caffe/imagenet/pascal_009959.jpg + +#for paper figs: +#./test_stitch_pyramid --padding 16 --output-stitched-dir ~/paper-writing/ICML14_dense_convnet/figures/featpyramid_figs/stitched_img ~/paper-writing/ICML14_dense_convnet/figures/bicycle.jpg + + diff --git a/src/stitch_pyramid/build/stitch_pyramid_pascal.sh b/src/stitch_pyramid/build/stitch_pyramid_pascal.sh new file mode 100755 index 00000000000..d4675d437da --- /dev/null +++ b/src/stitch_pyramid/build/stitch_pyramid_pascal.sh @@ -0,0 +1,21 @@ +#./stitch_pyramid ../../../images_640x480/carsgraz_001.image.jpg +#./stitch_pyramid --padding 8 ../../images_640x480/carsgraz_001.image.jpg + +VOC_DIR=/media/big_disk/VOC2007/VOCdevkit/VOC2007 +INPUT_DIR=$VOC_DIR/JPEGImages +OUTPUT_DIR=$VOC_DIR/JPEGImages_stitched_pyramid + +#example... +#./stitch_pyramid --padding 8 --output-stitched-dir $OUTPUT_DIR ../../images_640x480/carsgraz_001.image.jpg + +for input_img in $INPUT_DIR/*jpg +do + + #padding=8 + #output-stitched-dir=OUTPUT_DIR + #input=input_img + ./stitch_pyramid --padding 8 --output-stitched-dir $OUTPUT_DIR $input_img + +done + + diff --git a/src/stitch_pyramid/imagenet_mean.hpp b/src/stitch_pyramid/imagenet_mean.hpp new file mode 120000 index 00000000000..09012688a67 --- /dev/null +++ b/src/stitch_pyramid/imagenet_mean.hpp @@ -0,0 +1 @@ +../../include/caffe/imagenet_mean.hpp \ No newline at end of file diff --git a/src/stitch_pyramid/test_stitch_pyramid.cpp b/src/stitch_pyramid/test_stitch_pyramid.cpp new file mode 100644 index 00000000000..d896f986f59 --- /dev/null +++ b/src/stitch_pyramid/test_stitch_pyramid.cpp @@ -0,0 +1,251 @@ + +#include "SimpleOpt.h" +#include "JPEGPyramid.h" +#include "JPEGImage.h" +#include "Patchwork.h" +#include "PyramidStitcher.h" + +#include +#include +#include +#include +#include + +using namespace FFLD; +using namespace std; + +// SimpleOpt array of valid options +enum +{ + OPT_HELP, OPT_PADDING, OPT_INTERVAL, OPT_OUTPUT_STITCHED_DIR +}; + +CSimpleOpt::SOption SOptions[] = +{ + { OPT_HELP, "-h", SO_NONE }, + { OPT_HELP, "--help", SO_NONE }, + { OPT_PADDING, "-p", SO_REQ_SEP }, + { OPT_PADDING, "--padding", SO_REQ_SEP }, + { OPT_INTERVAL, "-e", SO_REQ_SEP }, + { OPT_INTERVAL, "--interval", SO_REQ_SEP }, + { OPT_OUTPUT_STITCHED_DIR, "--output-stitched-dir", SO_REQ_SEP }, + SO_END_OF_OPTIONS +}; + +void showUsage(){ + cout << "Usage: test [options] image.jpg, or\n test [options] image_set.txt\n\n" + "Options:\n" + " -h,--help Display this information\n" + " -p,--padding Amount of zero padding in JPEG images (default 8)\n" + " -e,--interval Number of levels per octave in the JPEG pyramid (default 10)\n" + " --output-stitched-dir Where to save stitched pyramids (default ../stitched_results)\n" + << endl; +} + +// Parse command line parameters +// put the appropriate values in (padding, interval, file) based on cmd-line args +void parseArgs(int &padding, int &interval, string &file, string &output_stitched_dir, int argc, char * argv[]){ + CSimpleOpt args(argc, argv, SOptions); + + while (args.Next()) { + if (args.LastError() == SO_SUCCESS) { + if (args.OptionId() == OPT_HELP) { + showUsage(); + exit(0); + } + else if (args.OptionId() == OPT_PADDING) { + padding = atoi(args.OptionArg()); + + // Error checking + if (padding <= 1) { + showUsage(); + cerr << "\nInvalid padding arg " << args.OptionArg() << endl; + exit(1); + } + } + else if (args.OptionId() == OPT_INTERVAL) { + interval = atoi(args.OptionArg()); + + // Error checking + if (interval <= 0) { + showUsage(); + cerr << "\nInvalid interval arg " << args.OptionArg() << endl; + exit(1); + } + } + else if (args.OptionId() == OPT_OUTPUT_STITCHED_DIR) { + output_stitched_dir = args.OptionArg(); + } + } + else { + showUsage(); + cerr << "\nUnknown option " << args.OptionText() << endl; + exit(1); + } + } + if (!args.FileCount()) { + showUsage(); + cerr << "\nNo image/dataset provided" << endl; + exit(1); + } + else if (args.FileCount() > 1) { + showUsage(); + cerr << "\nMore than one image/dataset provided" << endl; + exit(1); + } + + // The image/dataset + file = args.File(0); + const size_t lastDot = file.find_last_of('.'); + if ((lastDot == string::npos) || + ((file.substr(lastDot) != ".jpg") && (file.substr(lastDot) != ".txt"))) { + showUsage(); + cerr << "\nInvalid file " << file << ", should be .jpg or .txt" << endl; + exit(1); + } + + // Try to load the image + if (file.substr(lastDot) != ".jpg") { + cout << "need to input a JPG image" << endl; + exit(1); + } +} + +//e.g. file = ../../images_640x480/carsgraz_001.image.jpg +void TEST_file_parsing(string file){ + size_t lastSlash = file.find_last_of("/\\"); + size_t lastDot = file.find_last_of('.'); + cout << " file.substr(lastDot) = " << file.substr(lastDot) << endl; // .jpg + cout << " file.substr(lastSlash) = " << file.substr(lastSlash) << endl; // /carsgraz_001.image.jpg + cout << " file.substr(lastSlash, lastDot) = " << file.substr(lastSlash, lastDot-lastSlash) << endl; // /carsgraz_001.image +} + +//e.g. file = ../../images_640x480/carsgraz_001.image.jpg +string parse_base_filename(string file){ + size_t lastSlash = file.find_last_of("/\\"); + size_t lastDot = file.find_last_of('.'); + + string base_filename = file.substr(lastSlash, lastDot-lastSlash); // /carsgraz_001.image + return base_filename; +} + +void printScaleSizes(JPEGPyramid pyramid); +void writePyraToJPG(JPEGPyramid pyramid); +void writePatchworkToJPG(Patchwork patchwork, string output_stitched_dir, string base_filename); +void print_scaleLocations(vector scaleLocations); +void print_scales(Patchwork patchwork); +void test_linear_interp(); + +//TODO: split this test into its own function, e.g. test_stitch_pyramid() +int main(int argc, char * argv[]){ + + // Default parameters + string file; + string output_stitched_dir = "../stitched_results"; + int padding = 8; + int interval = 10; + + //parseArgs params are passed by reference, so they get updated here + parseArgs(padding, interval, file, output_stitched_dir, argc, argv); //update parameters with any command-line inputs + string base_filename = parse_base_filename(file); + + printf(" padding = %d \n", padding); + printf(" interval = %d \n", interval); + printf(" file = %s \n", file.c_str()); + printf(" base_filename = %s \n", base_filename.c_str()); + printf(" output_stitched_dir = %s \n", output_stitched_dir.c_str()); + +#if 0 //just for generating paper figs... the call to JPEGPyramid is now contained in stitch_pyramid. + JPEGImage image(file); + int upsampleFactor = 2; + JPEGPyramid pyramid(image, padding, padding, interval, upsampleFactor); + writePyraToJPG(pyramid); +#endif + + int img_minWidth = 200; //just a test + int img_minHeight = 200; + Patchwork patchwork = stitch_pyramid(file, img_minWidth, img_minHeight, padding, interval, 2000); + //Patchwork patchwork = stitch_pyramid(file, img_minWidth, img_minHeight, padding, interval, -1); //planeDim = -1 (use defaults) + //printScaleSizes(pyramid); + writePatchworkToJPG(patchwork, output_stitched_dir, base_filename); //outputs to output_stitched_dir/base_filename_[planeID].jpg + + int sbin = 1; // we're not actually computing convnet features in this test, + // so there's no feature downsampling. + vector scaleLocations = unstitch_pyramid_locations(patchwork, sbin); + //print_scaleLocations(scaleLocations); + print_scales(patchwork); + + test_linear_interp(); + + return EXIT_SUCCESS; +} + +void printScaleSizes(JPEGPyramid pyramid){ + int nlevels = pyramid.levels().size(); + + for(int level = 0; level < nlevels; level++){ + int width = pyramid.levels()[level].width(); + int height = pyramid.levels()[level].height(); + int depth = pyramid.NbChannels; + printf(" level %d: width=%d, height=%d, depth=%d \n", level, width, height, depth); + } +} + +void print_scaleLocations(vector scaleLocations){ + printf("scaleLocations: \n"); + for(int i=0; i