Last active
June 12, 2019 10:45
-
-
Save dkurt/95c3fa778d6354ee92a88987407d2ccb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <opencv2/dnn.hpp> | |
#include <opencv2/imgproc.hpp> | |
#include <opencv2/highgui.hpp> | |
std::vector<Rect> boxes; std::vector<float> confidences; std::vector<int> classIds; | |
#include <opencv2/dnn/layer.details.hpp> | |
#include <iostream> | |
using namespace cv; | |
using namespace cv::dnn; | |
class CentralCrop : public Layer | |
{ | |
public: | |
static Ptr<Layer> create(LayerParams& params) | |
{ | |
return Ptr<Layer>(new CentralCrop()); | |
} | |
virtual bool getMemoryShapes(const std::vector<std::vector<int> > &inputs, | |
const int requiredOutputs, | |
std::vector<std::vector<int> > &outputs, | |
std::vector<std::vector<int> > &internals) const | |
{ | |
CV_Assert(inputs.size() == 2); | |
int batchSize = inputs[0][0]; | |
int numChannels = inputs[0][1]; | |
int outH = inputs[1][2]; | |
int outW = inputs[1][3]; | |
outputs.resize(1, {batchSize, numChannels, outH, outW}); | |
return false; // For not inplace layers | |
} | |
virtual void forward(InputArrayOfArrays inputs_vec, | |
OutputArrayOfArrays outputs_vec, | |
OutputArrayOfArrays internals) | |
{ | |
std::vector<Mat> inputs, outputs; | |
inputs_vec.getMatVector(inputs); | |
outputs_vec.getMatVector(outputs); | |
int outH = outputs[0].size[2]; | |
int outW = outputs[0].size[3]; | |
// Do central crop. | |
int y = (inputs[0].size[2] - outH) / 2; | |
int x = (inputs[0].size[3] - outW) / 2; | |
Range ranges[] = {Range::all(), Range::all(), | |
Range(y, y + outH), Range(x, x + outW)}; | |
inputs[0](ranges).copyTo(outputs[0]); | |
} | |
private: | |
int xstart, xend, ystart, yend; | |
}; | |
int main(int argc, char** argv) | |
{ | |
Net net = readNet("/home/dkurt/Downloads/hed_pretrained_bsds.ptorotxt", | |
"/home/dkurt/Downloads/hed_pretrained_bsds.caffemodel"); | |
net.setPreferableBackend(DNN_BACKEND_OPENCV); | |
Mat img = imread("/home/dkurt/opencv_extra/testdata/viz/lena.png"); | |
Mat blob = blobFromImage(img, 1.0, Size(500, 500), Scalar(104.00698793, 116.66876762, 122.67891434)); | |
net.setInput(blob); | |
CV_DNN_REGISTER_LAYER_CLASS(Crop, CentralCrop); | |
Mat out = net.forward().reshape(1, 500); | |
imshow("out", out); | |
out.convertTo(img, CV_8UC1, 255); | |
imwrite("central.jpg", img); | |
waitKey(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment