mirror of https://github.com/opencv/opencv.git
commit
0f298a4203
64 changed files with 2845 additions and 1253 deletions
@ -1,145 +0,0 @@ |
|||||||
// This file is part of OpenCV project.
|
|
||||||
// It is subject to the license terms in the LICENSE file found in the top-level directory
|
|
||||||
// of this distribution and at http://opencv.org/license.html.
|
|
||||||
|
|
||||||
// Copyright (C) 2016, Intel Corporation, all rights reserved.
|
|
||||||
// Third party copyrights are property of their respective owners.
|
|
||||||
|
|
||||||
/*
|
|
||||||
Implementation of shift layer, which adds up const values to blob. |
|
||||||
*/ |
|
||||||
|
|
||||||
#include "../precomp.hpp" |
|
||||||
#include "../op_inf_engine.hpp" |
|
||||||
#include <opencv2/dnn/shape_utils.hpp> |
|
||||||
|
|
||||||
namespace cv |
|
||||||
{ |
|
||||||
namespace dnn |
|
||||||
{ |
|
||||||
|
|
||||||
class ShiftLayerImpl CV_FINAL : public ShiftLayer |
|
||||||
{ |
|
||||||
public: |
|
||||||
ShiftLayerImpl(const LayerParams ¶ms) |
|
||||||
{ |
|
||||||
setParamsFrom(params); |
|
||||||
CV_Assert(blobs.size() == 1); |
|
||||||
} |
|
||||||
|
|
||||||
virtual bool supportBackend(int backendId) CV_OVERRIDE |
|
||||||
{ |
|
||||||
return backendId == DNN_BACKEND_DEFAULT || |
|
||||||
backendId == DNN_BACKEND_INFERENCE_ENGINE && haveInfEngine(); |
|
||||||
} |
|
||||||
|
|
||||||
bool getMemoryShapes(const std::vector<MatShape> &inputs, |
|
||||||
const int requiredOutputs, |
|
||||||
std::vector<MatShape> &outputs, |
|
||||||
std::vector<MatShape> &internals) const CV_OVERRIDE |
|
||||||
{ |
|
||||||
Layer::getMemoryShapes(inputs, requiredOutputs, outputs, internals); |
|
||||||
internals.assign(1, shape(1, total(inputs[0], 2))); |
|
||||||
return true; |
|
||||||
} |
|
||||||
|
|
||||||
void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE |
|
||||||
{ |
|
||||||
CV_TRACE_FUNCTION(); |
|
||||||
CV_TRACE_ARG_VALUE(name, "name", name.c_str()); |
|
||||||
|
|
||||||
Layer::forward_fallback(inputs_arr, outputs_arr, internals_arr); |
|
||||||
} |
|
||||||
|
|
||||||
virtual void forward(std::vector<Mat*> &inputs, std::vector<Mat> &outputs, std::vector<Mat> &internals) CV_OVERRIDE |
|
||||||
{ |
|
||||||
CV_TRACE_FUNCTION(); |
|
||||||
CV_TRACE_ARG_VALUE(name, "name", name.c_str()); |
|
||||||
|
|
||||||
CV_Assert(inputs.size() > 0); |
|
||||||
CV_Assert(blobs.size() > 0); |
|
||||||
|
|
||||||
if(inputs[0]->dims == blobs[0].dims) |
|
||||||
{ |
|
||||||
for (size_t ii = 0; ii < outputs.size(); ii++) |
|
||||||
{ |
|
||||||
Mat &inpBlob = *inputs[ii]; |
|
||||||
Mat &outBlob = outputs[ii]; |
|
||||||
|
|
||||||
outBlob = inpBlob + blobs[0]; |
|
||||||
} |
|
||||||
} |
|
||||||
else |
|
||||||
{ |
|
||||||
Mat biasOnesMat = internals[0]; |
|
||||||
biasOnesMat.setTo(1); |
|
||||||
for (size_t ii = 0; ii < outputs.size(); ii++) |
|
||||||
{ |
|
||||||
Mat &inpBlob = *inputs[ii]; |
|
||||||
Mat &outBlob = outputs[ii]; |
|
||||||
|
|
||||||
inpBlob.copyTo(outBlob); |
|
||||||
|
|
||||||
for (int n = 0; n < inpBlob.size[0]; n++) |
|
||||||
{ |
|
||||||
Mat dstMat(inpBlob.size[1], inpBlob.size[2] * inpBlob.size[3], |
|
||||||
outBlob.type(), outBlob.ptr(n)); |
|
||||||
gemm(blobs[0], biasOnesMat, 1, dstMat, 1, dstMat); //TODO: gemv
|
|
||||||
} |
|
||||||
} |
|
||||||
} |
|
||||||
} |
|
||||||
|
|
||||||
virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> >&) CV_OVERRIDE |
|
||||||
{ |
|
||||||
#ifdef HAVE_INF_ENGINE |
|
||||||
// Inference Engine has no layer just for biases. Create a linear
|
|
||||||
// transformation layer with ones weights.
|
|
||||||
InferenceEngine::LayerParams lp; |
|
||||||
lp.name = name; |
|
||||||
lp.type = "ScaleShift"; |
|
||||||
lp.precision = InferenceEngine::Precision::FP32; |
|
||||||
std::shared_ptr<InferenceEngine::ScaleShiftLayer> ieLayer(new InferenceEngine::ScaleShiftLayer(lp)); |
|
||||||
|
|
||||||
auto weights = InferenceEngine::make_shared_blob<float>(InferenceEngine::Precision::FP32, |
|
||||||
{blobs[0].total()}); |
|
||||||
weights->allocate(); |
|
||||||
|
|
||||||
std::vector<float> ones(blobs[0].total(), 1); |
|
||||||
weights->set(ones); |
|
||||||
ieLayer->_weights = weights; |
|
||||||
|
|
||||||
ieLayer->_biases = wrapToInfEngineBlob(blobs[0]); |
|
||||||
return Ptr<BackendNode>(new InfEngineBackendNode(ieLayer)); |
|
||||||
#endif // HAVE_INF_ENGINE
|
|
||||||
return Ptr<BackendNode>(); |
|
||||||
} |
|
||||||
|
|
||||||
void getScaleShift(Mat& scale, Mat& shift) const CV_OVERRIDE |
|
||||||
{ |
|
||||||
scale = Mat(); |
|
||||||
shift = blobs[0]; |
|
||||||
} |
|
||||||
|
|
||||||
virtual int64 getFLOPS(const std::vector<MatShape> &inputs, |
|
||||||
const std::vector<MatShape> &outputs) const CV_OVERRIDE |
|
||||||
{ |
|
||||||
(void)outputs; // suppress unused variable warning
|
|
||||||
long flops = 0; |
|
||||||
|
|
||||||
for(int i= 0; i < inputs.size(); i++) |
|
||||||
{ |
|
||||||
flops += total(inputs[i]); |
|
||||||
} |
|
||||||
|
|
||||||
return flops; |
|
||||||
} |
|
||||||
}; |
|
||||||
|
|
||||||
Ptr<ShiftLayer> ShiftLayer::create(const LayerParams& params) |
|
||||||
{ |
|
||||||
return Ptr<ShiftLayer>(new ShiftLayerImpl(params)); |
|
||||||
} |
|
||||||
|
|
||||||
} |
|
||||||
} |
|
@ -0,0 +1,173 @@ |
|||||||
|
import java.awt.BorderLayout; |
||||||
|
import java.awt.Container; |
||||||
|
import java.awt.Image; |
||||||
|
import java.util.Arrays; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
import javax.swing.BoxLayout; |
||||||
|
import javax.swing.ImageIcon; |
||||||
|
import javax.swing.JFrame; |
||||||
|
import javax.swing.JLabel; |
||||||
|
import javax.swing.JPanel; |
||||||
|
import javax.swing.JSlider; |
||||||
|
import javax.swing.event.ChangeEvent; |
||||||
|
import javax.swing.event.ChangeListener; |
||||||
|
|
||||||
|
import org.opencv.core.Core; |
||||||
|
import org.opencv.core.CvType; |
||||||
|
import org.opencv.core.Mat; |
||||||
|
import org.opencv.core.MatOfFloat; |
||||||
|
import org.opencv.core.MatOfInt; |
||||||
|
import org.opencv.core.Point; |
||||||
|
import org.opencv.core.Scalar; |
||||||
|
import org.opencv.highgui.HighGui; |
||||||
|
import org.opencv.imgcodecs.Imgcodecs; |
||||||
|
import org.opencv.imgproc.Imgproc; |
||||||
|
|
||||||
|
class CalcBackProject1 { |
||||||
|
private Mat hue; |
||||||
|
private Mat histImg = new Mat(); |
||||||
|
private JFrame frame; |
||||||
|
private JLabel imgLabel; |
||||||
|
private JLabel backprojLabel; |
||||||
|
private JLabel histImgLabel; |
||||||
|
private static final int MAX_SLIDER = 180; |
||||||
|
private int bins = 25; |
||||||
|
|
||||||
|
public CalcBackProject1(String[] args) { |
||||||
|
//! [Read the image]
|
||||||
|
if (args.length != 1) { |
||||||
|
System.err.println("You must supply one argument that corresponds to the path to the image."); |
||||||
|
System.exit(0); |
||||||
|
} |
||||||
|
|
||||||
|
Mat src = Imgcodecs.imread(args[0]); |
||||||
|
if (src.empty()) { |
||||||
|
System.err.println("Empty image: " + args[0]); |
||||||
|
System.exit(0); |
||||||
|
} |
||||||
|
//! [Read the image]
|
||||||
|
|
||||||
|
//! [Transform it to HSV]
|
||||||
|
Mat hsv = new Mat(); |
||||||
|
Imgproc.cvtColor(src, hsv, Imgproc.COLOR_BGR2HSV); |
||||||
|
//! [Transform it to HSV]
|
||||||
|
|
||||||
|
//! [Use only the Hue value]
|
||||||
|
hue = new Mat(hsv.size(), hsv.depth()); |
||||||
|
Core.mixChannels(Arrays.asList(hsv), Arrays.asList(hue), new MatOfInt(0, 0)); |
||||||
|
//! [Use only the Hue value]
|
||||||
|
|
||||||
|
// Create and set up the window.
|
||||||
|
frame = new JFrame("Back Projection 1 demo"); |
||||||
|
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
||||||
|
// Set up the content pane.
|
||||||
|
Image img = HighGui.toBufferedImage(src); |
||||||
|
addComponentsToPane(frame.getContentPane(), img); |
||||||
|
//! [Show the image]
|
||||||
|
// Use the content pane's default BorderLayout. No need for
|
||||||
|
// setLayout(new BorderLayout());
|
||||||
|
// Display the window.
|
||||||
|
frame.pack(); |
||||||
|
frame.setVisible(true); |
||||||
|
//! [Show the image]
|
||||||
|
} |
||||||
|
|
||||||
|
private void addComponentsToPane(Container pane, Image img) { |
||||||
|
if (!(pane.getLayout() instanceof BorderLayout)) { |
||||||
|
pane.add(new JLabel("Container doesn't use BorderLayout!")); |
||||||
|
return; |
||||||
|
} |
||||||
|
|
||||||
|
//! [Create Trackbar to enter the number of bins]
|
||||||
|
JPanel sliderPanel = new JPanel(); |
||||||
|
sliderPanel.setLayout(new BoxLayout(sliderPanel, BoxLayout.PAGE_AXIS)); |
||||||
|
|
||||||
|
sliderPanel.add(new JLabel("* Hue bins: ")); |
||||||
|
JSlider slider = new JSlider(0, MAX_SLIDER, bins); |
||||||
|
slider.setMajorTickSpacing(25); |
||||||
|
slider.setMinorTickSpacing(5); |
||||||
|
slider.setPaintTicks(true); |
||||||
|
slider.setPaintLabels(true); |
||||||
|
slider.addChangeListener(new ChangeListener() { |
||||||
|
@Override |
||||||
|
public void stateChanged(ChangeEvent e) { |
||||||
|
JSlider source = (JSlider) e.getSource(); |
||||||
|
bins = source.getValue(); |
||||||
|
update(); |
||||||
|
} |
||||||
|
}); |
||||||
|
sliderPanel.add(slider); |
||||||
|
pane.add(sliderPanel, BorderLayout.PAGE_START); |
||||||
|
//! [Create Trackbar to enter the number of bins]
|
||||||
|
|
||||||
|
JPanel imgPanel = new JPanel(); |
||||||
|
imgLabel = new JLabel(new ImageIcon(img)); |
||||||
|
imgPanel.add(imgLabel); |
||||||
|
|
||||||
|
backprojLabel = new JLabel(); |
||||||
|
imgPanel.add(backprojLabel); |
||||||
|
|
||||||
|
histImgLabel = new JLabel(); |
||||||
|
imgPanel.add(histImgLabel); |
||||||
|
pane.add(imgPanel, BorderLayout.CENTER); |
||||||
|
} |
||||||
|
|
||||||
|
private void update() { |
||||||
|
//! [initialize]
|
||||||
|
int histSize = Math.max(bins, 2); |
||||||
|
float[] hueRange = {0, 180}; |
||||||
|
//! [initialize]
|
||||||
|
|
||||||
|
//! [Get the Histogram and normalize it]
|
||||||
|
Mat hist = new Mat(); |
||||||
|
List<Mat> hueList = Arrays.asList(hue); |
||||||
|
Imgproc.calcHist(hueList, new MatOfInt(0), new Mat(), hist, new MatOfInt(histSize), new MatOfFloat(hueRange), false); |
||||||
|
Core.normalize(hist, hist, 0, 255, Core.NORM_MINMAX); |
||||||
|
//! [Get the Histogram and normalize it]
|
||||||
|
|
||||||
|
//! [Get Backprojection]
|
||||||
|
Mat backproj = new Mat(); |
||||||
|
Imgproc.calcBackProject(hueList, new MatOfInt(0), hist, backproj, new MatOfFloat(hueRange), 1); |
||||||
|
//! [Get Backprojection]
|
||||||
|
|
||||||
|
//! [Draw the backproj]
|
||||||
|
Image backprojImg = HighGui.toBufferedImage(backproj); |
||||||
|
backprojLabel.setIcon(new ImageIcon(backprojImg)); |
||||||
|
//! [Draw the backproj]
|
||||||
|
|
||||||
|
//! [Draw the histogram]
|
||||||
|
int w = 400, h = 400; |
||||||
|
int binW = (int) Math.round((double) w / histSize); |
||||||
|
histImg = Mat.zeros(h, w, CvType.CV_8UC3); |
||||||
|
|
||||||
|
float[] histData = new float[(int) (hist.total() * hist.channels())]; |
||||||
|
hist.get(0, 0, histData); |
||||||
|
for (int i = 0; i < bins; i++) { |
||||||
|
Imgproc.rectangle(histImg, new Point(i * binW, h), |
||||||
|
new Point((i + 1) * binW, h - Math.round(histData[i] * h / 255.0)), new Scalar(0, 0, 255), Core.FILLED); |
||||||
|
} |
||||||
|
Image histImage = HighGui.toBufferedImage(histImg); |
||||||
|
histImgLabel.setIcon(new ImageIcon(histImage)); |
||||||
|
//! [Draw the histogram]
|
||||||
|
|
||||||
|
frame.repaint(); |
||||||
|
frame.pack(); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
public class CalcBackProjectDemo1 { |
||||||
|
public static void main(String[] args) { |
||||||
|
// Load the native OpenCV library
|
||||||
|
System.loadLibrary(Core.NATIVE_LIBRARY_NAME); |
||||||
|
|
||||||
|
// Schedule a job for the event dispatch thread:
|
||||||
|
// creating and showing this application's GUI.
|
||||||
|
javax.swing.SwingUtilities.invokeLater(new Runnable() { |
||||||
|
@Override |
||||||
|
public void run() { |
||||||
|
new CalcBackProject1(args); |
||||||
|
} |
||||||
|
}); |
||||||
|
} |
||||||
|
} |
@ -0,0 +1,189 @@ |
|||||||
|
import java.awt.BorderLayout; |
||||||
|
import java.awt.Container; |
||||||
|
import java.awt.Image; |
||||||
|
import java.awt.event.MouseAdapter; |
||||||
|
import java.awt.event.MouseEvent; |
||||||
|
import java.util.Arrays; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
import javax.swing.BoxLayout; |
||||||
|
import javax.swing.ImageIcon; |
||||||
|
import javax.swing.JFrame; |
||||||
|
import javax.swing.JLabel; |
||||||
|
import javax.swing.JPanel; |
||||||
|
import javax.swing.JSlider; |
||||||
|
import javax.swing.event.ChangeEvent; |
||||||
|
import javax.swing.event.ChangeListener; |
||||||
|
|
||||||
|
import org.opencv.core.Core; |
||||||
|
import org.opencv.core.CvType; |
||||||
|
import org.opencv.core.Mat; |
||||||
|
import org.opencv.core.MatOfFloat; |
||||||
|
import org.opencv.core.MatOfInt; |
||||||
|
import org.opencv.core.Point; |
||||||
|
import org.opencv.core.Range; |
||||||
|
import org.opencv.core.Rect; |
||||||
|
import org.opencv.core.Scalar; |
||||||
|
import org.opencv.highgui.HighGui; |
||||||
|
import org.opencv.imgcodecs.Imgcodecs; |
||||||
|
import org.opencv.imgproc.Imgproc; |
||||||
|
|
||||||
|
class CalcBackProject2 { |
||||||
|
private Mat src; |
||||||
|
private Mat hsv = new Mat(); |
||||||
|
private Mat mask = new Mat(); |
||||||
|
private JFrame frame; |
||||||
|
private JLabel imgLabel; |
||||||
|
private JLabel backprojLabel; |
||||||
|
private JLabel maskImgLabel; |
||||||
|
private static final int MAX_SLIDER = 255; |
||||||
|
private int low = 20; |
||||||
|
private int up = 20; |
||||||
|
|
||||||
|
public CalcBackProject2(String[] args) { |
||||||
|
/// Read the image
|
||||||
|
if (args.length != 1) { |
||||||
|
System.err.println("You must supply one argument that corresponds to the path to the image."); |
||||||
|
System.exit(0); |
||||||
|
} |
||||||
|
|
||||||
|
src = Imgcodecs.imread(args[0]); |
||||||
|
if (src.empty()) { |
||||||
|
System.err.println("Empty image: " + args[0]); |
||||||
|
System.exit(0); |
||||||
|
} |
||||||
|
|
||||||
|
/// Transform it to HSV
|
||||||
|
Imgproc.cvtColor(src, hsv, Imgproc.COLOR_BGR2HSV); |
||||||
|
|
||||||
|
// Create and set up the window.
|
||||||
|
frame = new JFrame("Back Projection 2 demo"); |
||||||
|
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
||||||
|
// Set up the content pane.
|
||||||
|
Image img = HighGui.toBufferedImage(src); |
||||||
|
addComponentsToPane(frame.getContentPane(), img); |
||||||
|
// Use the content pane's default BorderLayout. No need for
|
||||||
|
// setLayout(new BorderLayout());
|
||||||
|
// Display the window.
|
||||||
|
frame.pack(); |
||||||
|
frame.setVisible(true); |
||||||
|
} |
||||||
|
|
||||||
|
private void addComponentsToPane(Container pane, Image img) { |
||||||
|
if (!(pane.getLayout() instanceof BorderLayout)) { |
||||||
|
pane.add(new JLabel("Container doesn't use BorderLayout!")); |
||||||
|
return; |
||||||
|
} |
||||||
|
|
||||||
|
/// Set Trackbars for floodfill thresholds
|
||||||
|
JPanel sliderPanel = new JPanel(); |
||||||
|
sliderPanel.setLayout(new BoxLayout(sliderPanel, BoxLayout.PAGE_AXIS)); |
||||||
|
|
||||||
|
sliderPanel.add(new JLabel("Low thresh")); |
||||||
|
JSlider slider = new JSlider(0, MAX_SLIDER, low); |
||||||
|
slider.setMajorTickSpacing(20); |
||||||
|
slider.setMinorTickSpacing(10); |
||||||
|
slider.setPaintTicks(true); |
||||||
|
slider.setPaintLabels(true); |
||||||
|
slider.addChangeListener(new ChangeListener() { |
||||||
|
@Override |
||||||
|
public void stateChanged(ChangeEvent e) { |
||||||
|
JSlider source = (JSlider) e.getSource(); |
||||||
|
low = source.getValue(); |
||||||
|
} |
||||||
|
}); |
||||||
|
sliderPanel.add(slider); |
||||||
|
pane.add(sliderPanel, BorderLayout.PAGE_START); |
||||||
|
|
||||||
|
sliderPanel.add(new JLabel("High thresh")); |
||||||
|
slider = new JSlider(0, MAX_SLIDER, up); |
||||||
|
slider.setMajorTickSpacing(20); |
||||||
|
slider.setMinorTickSpacing(10); |
||||||
|
slider.setPaintTicks(true); |
||||||
|
slider.setPaintLabels(true); |
||||||
|
slider.addChangeListener(new ChangeListener() { |
||||||
|
@Override |
||||||
|
public void stateChanged(ChangeEvent e) { |
||||||
|
JSlider source = (JSlider) e.getSource(); |
||||||
|
up = source.getValue(); |
||||||
|
} |
||||||
|
}); |
||||||
|
sliderPanel.add(slider); |
||||||
|
pane.add(sliderPanel, BorderLayout.PAGE_START); |
||||||
|
|
||||||
|
JPanel imgPanel = new JPanel(); |
||||||
|
imgLabel = new JLabel(new ImageIcon(img)); |
||||||
|
/// Set a Mouse Callback
|
||||||
|
imgLabel.addMouseListener(new MouseAdapter() { |
||||||
|
@Override |
||||||
|
public void mousePressed(MouseEvent e) { |
||||||
|
update(e.getX(), e.getY()); |
||||||
|
} |
||||||
|
}); |
||||||
|
imgPanel.add(imgLabel); |
||||||
|
|
||||||
|
maskImgLabel = new JLabel(); |
||||||
|
imgPanel.add(maskImgLabel); |
||||||
|
|
||||||
|
backprojLabel = new JLabel(); |
||||||
|
imgPanel.add(backprojLabel); |
||||||
|
|
||||||
|
pane.add(imgPanel, BorderLayout.CENTER); |
||||||
|
} |
||||||
|
|
||||||
|
private void update(int x, int y) { |
||||||
|
// Fill and get the mask
|
||||||
|
Point seed = new Point(x, y); |
||||||
|
|
||||||
|
int newMaskVal = 255; |
||||||
|
Scalar newVal = new Scalar(120, 120, 120); |
||||||
|
|
||||||
|
int connectivity = 8; |
||||||
|
int flags = connectivity + (newMaskVal << 8) + Imgproc.FLOODFILL_FIXED_RANGE + Imgproc.FLOODFILL_MASK_ONLY; |
||||||
|
|
||||||
|
Mat mask2 = Mat.zeros(src.rows() + 2, src.cols() + 2, CvType.CV_8U); |
||||||
|
Imgproc.floodFill(src, mask2, seed, newVal, new Rect(), new Scalar(low, low, low), new Scalar(up, up, up), flags); |
||||||
|
mask = mask2.submat(new Range(1, mask2.rows() - 1), new Range(1, mask2.cols() - 1)); |
||||||
|
|
||||||
|
Image maskImg = HighGui.toBufferedImage(mask); |
||||||
|
maskImgLabel.setIcon(new ImageIcon(maskImg)); |
||||||
|
|
||||||
|
int hBins = 30, sBins = 32; |
||||||
|
int[] histSize = { hBins, sBins }; |
||||||
|
float[] ranges = { 0, 180, 0, 256 }; |
||||||
|
int[] channels = { 0, 1 }; |
||||||
|
|
||||||
|
/// Get the Histogram and normalize it
|
||||||
|
Mat hist = new Mat(); |
||||||
|
List<Mat> hsvList = Arrays.asList(hsv); |
||||||
|
Imgproc.calcHist(hsvList, new MatOfInt(channels), mask, hist, new MatOfInt(histSize), new MatOfFloat(ranges), false ); |
||||||
|
|
||||||
|
Core.normalize(hist, hist, 0, 255, Core.NORM_MINMAX); |
||||||
|
|
||||||
|
/// Get Backprojection
|
||||||
|
Mat backproj = new Mat(); |
||||||
|
Imgproc.calcBackProject(hsvList, new MatOfInt(channels), hist, backproj, new MatOfFloat(ranges), 1); |
||||||
|
|
||||||
|
Image backprojImg = HighGui.toBufferedImage(backproj); |
||||||
|
backprojLabel.setIcon(new ImageIcon(backprojImg)); |
||||||
|
|
||||||
|
frame.repaint(); |
||||||
|
frame.pack(); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
public class CalcBackProjectDemo2 { |
||||||
|
public static void main(String[] args) { |
||||||
|
// Load the native OpenCV library
|
||||||
|
System.loadLibrary(Core.NATIVE_LIBRARY_NAME); |
||||||
|
|
||||||
|
// Schedule a job for the event dispatch thread:
|
||||||
|
// creating and showing this application's GUI.
|
||||||
|
javax.swing.SwingUtilities.invokeLater(new Runnable() { |
||||||
|
@Override |
||||||
|
public void run() { |
||||||
|
new CalcBackProject2(args); |
||||||
|
} |
||||||
|
}); |
||||||
|
} |
||||||
|
} |
@ -0,0 +1,99 @@ |
|||||||
|
import java.util.ArrayList; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
import org.opencv.core.Core; |
||||||
|
import org.opencv.core.CvType; |
||||||
|
import org.opencv.core.Mat; |
||||||
|
import org.opencv.core.MatOfFloat; |
||||||
|
import org.opencv.core.MatOfInt; |
||||||
|
import org.opencv.core.Point; |
||||||
|
import org.opencv.core.Scalar; |
||||||
|
import org.opencv.highgui.HighGui; |
||||||
|
import org.opencv.imgcodecs.Imgcodecs; |
||||||
|
import org.opencv.imgproc.Imgproc; |
||||||
|
|
||||||
|
class CalcHist { |
||||||
|
public void run(String[] args) { |
||||||
|
//! [Load image]
|
||||||
|
String filename = args.length > 0 ? args[0] : "../data/lena.jpg"; |
||||||
|
Mat src = Imgcodecs.imread(filename); |
||||||
|
if (src.empty()) { |
||||||
|
System.err.println("Cannot read image: " + filename); |
||||||
|
System.exit(0); |
||||||
|
} |
||||||
|
//! [Load image]
|
||||||
|
|
||||||
|
//! [Separate the image in 3 places ( B, G and R )]
|
||||||
|
List<Mat> bgrPlanes = new ArrayList<>(); |
||||||
|
Core.split(src, bgrPlanes); |
||||||
|
//! [Separate the image in 3 places ( B, G and R )]
|
||||||
|
|
||||||
|
//! [Establish the number of bins]
|
||||||
|
int histSize = 256; |
||||||
|
//! [Establish the number of bins]
|
||||||
|
|
||||||
|
//! [Set the ranges ( for B,G,R) )]
|
||||||
|
float[] range = {0, 256}; //the upper boundary is exclusive
|
||||||
|
MatOfFloat histRange = new MatOfFloat(range); |
||||||
|
//! [Set the ranges ( for B,G,R) )]
|
||||||
|
|
||||||
|
//! [Set histogram param]
|
||||||
|
boolean accumulate = false; |
||||||
|
//! [Set histogram param]
|
||||||
|
|
||||||
|
//! [Compute the histograms]
|
||||||
|
Mat bHist = new Mat(), gHist = new Mat(), rHist = new Mat(); |
||||||
|
Imgproc.calcHist(bgrPlanes, new MatOfInt(0), new Mat(), bHist, new MatOfInt(histSize), histRange, accumulate); |
||||||
|
Imgproc.calcHist(bgrPlanes, new MatOfInt(1), new Mat(), gHist, new MatOfInt(histSize), histRange, accumulate); |
||||||
|
Imgproc.calcHist(bgrPlanes, new MatOfInt(2), new Mat(), rHist, new MatOfInt(histSize), histRange, accumulate); |
||||||
|
//! [Compute the histograms]
|
||||||
|
|
||||||
|
//! [Draw the histograms for B, G and R]
|
||||||
|
int histW = 512, histH = 400; |
||||||
|
int binW = (int) Math.round((double) histW / histSize); |
||||||
|
|
||||||
|
Mat histImage = new Mat( histH, histW, CvType.CV_8UC3, new Scalar( 0,0,0) ); |
||||||
|
//! [Draw the histograms for B, G and R]
|
||||||
|
|
||||||
|
//! [Normalize the result to ( 0, histImage.rows )]
|
||||||
|
Core.normalize(bHist, bHist, 0, histImage.rows(), Core.NORM_MINMAX); |
||||||
|
Core.normalize(gHist, gHist, 0, histImage.rows(), Core.NORM_MINMAX); |
||||||
|
Core.normalize(rHist, rHist, 0, histImage.rows(), Core.NORM_MINMAX); |
||||||
|
//! [Normalize the result to ( 0, histImage.rows )]
|
||||||
|
|
||||||
|
//! [Draw for each channel]
|
||||||
|
float[] bHistData = new float[(int) (bHist.total() * bHist.channels())]; |
||||||
|
bHist.get(0, 0, bHistData); |
||||||
|
float[] gHistData = new float[(int) (gHist.total() * gHist.channels())]; |
||||||
|
gHist.get(0, 0, gHistData); |
||||||
|
float[] rHistData = new float[(int) (rHist.total() * rHist.channels())]; |
||||||
|
rHist.get(0, 0, rHistData); |
||||||
|
|
||||||
|
for( int i = 1; i < histSize; i++ ) { |
||||||
|
Imgproc.line(histImage, new Point(binW * (i - 1), histH - Math.round(bHistData[i - 1])), |
||||||
|
new Point(binW * (i), histH - Math.round(bHistData[i])), new Scalar(255, 0, 0), 2); |
||||||
|
Imgproc.line(histImage, new Point(binW * (i - 1), histH - Math.round(gHistData[i - 1])), |
||||||
|
new Point(binW * (i), histH - Math.round(gHistData[i])), new Scalar(0, 255, 0), 2); |
||||||
|
Imgproc.line(histImage, new Point(binW * (i - 1), histH - Math.round(rHistData[i - 1])), |
||||||
|
new Point(binW * (i), histH - Math.round(rHistData[i])), new Scalar(0, 0, 255), 2); |
||||||
|
} |
||||||
|
//! [Draw for each channel]
|
||||||
|
|
||||||
|
//! [Display]
|
||||||
|
HighGui.imshow( "Source image", src ); |
||||||
|
HighGui.imshow( "calcHist Demo", histImage ); |
||||||
|
HighGui.waitKey(0); |
||||||
|
//! [Display]
|
||||||
|
|
||||||
|
System.exit(0); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
public class CalcHistDemo { |
||||||
|
public static void main(String[] args) { |
||||||
|
// Load the native OpenCV library
|
||||||
|
System.loadLibrary(Core.NATIVE_LIBRARY_NAME); |
||||||
|
|
||||||
|
new CalcHist().run(args); |
||||||
|
} |
||||||
|
} |
@ -0,0 +1,91 @@ |
|||||||
|
import java.util.Arrays; |
||||||
|
import java.util.List; |
||||||
|
|
||||||
|
import org.opencv.core.Core; |
||||||
|
import org.opencv.core.Mat; |
||||||
|
import org.opencv.core.MatOfFloat; |
||||||
|
import org.opencv.core.MatOfInt; |
||||||
|
import org.opencv.core.Range; |
||||||
|
import org.opencv.imgcodecs.Imgcodecs; |
||||||
|
import org.opencv.imgproc.Imgproc; |
||||||
|
|
||||||
|
class CompareHist { |
||||||
|
public void run(String[] args) { |
||||||
|
//! [Load three images with different environment settings]
|
||||||
|
if (args.length != 3) { |
||||||
|
System.err.println("You must supply 3 arguments that correspond to the paths to 3 images."); |
||||||
|
System.exit(0); |
||||||
|
} |
||||||
|
Mat srcBase = Imgcodecs.imread(args[0]); |
||||||
|
Mat srcTest1 = Imgcodecs.imread(args[1]); |
||||||
|
Mat srcTest2 = Imgcodecs.imread(args[2]); |
||||||
|
if (srcBase.empty() || srcTest1.empty() || srcTest2.empty()) { |
||||||
|
System.err.println("Cannot read the images"); |
||||||
|
System.exit(0); |
||||||
|
} |
||||||
|
//! [Load three images with different environment settings]
|
||||||
|
|
||||||
|
//! [Convert to HSV]
|
||||||
|
Mat hsvBase = new Mat(), hsvTest1 = new Mat(), hsvTest2 = new Mat(); |
||||||
|
Imgproc.cvtColor( srcBase, hsvBase, Imgproc.COLOR_BGR2HSV ); |
||||||
|
Imgproc.cvtColor( srcTest1, hsvTest1, Imgproc.COLOR_BGR2HSV ); |
||||||
|
Imgproc.cvtColor( srcTest2, hsvTest2, Imgproc.COLOR_BGR2HSV ); |
||||||
|
//! [Convert to HSV]
|
||||||
|
|
||||||
|
//! [Convert to HSV half]
|
||||||
|
Mat hsvHalfDown = hsvBase.submat( new Range( hsvBase.rows()/2, hsvBase.rows() - 1 ), new Range( 0, hsvBase.cols() - 1 ) ); |
||||||
|
//! [Convert to HSV half]
|
||||||
|
|
||||||
|
//! [Using 50 bins for hue and 60 for saturation]
|
||||||
|
int hBins = 50, sBins = 60; |
||||||
|
int[] histSize = { hBins, sBins }; |
||||||
|
|
||||||
|
// hue varies from 0 to 179, saturation from 0 to 255
|
||||||
|
float[] ranges = { 0, 180, 0, 256 }; |
||||||
|
|
||||||
|
// Use the 0-th and 1-st channels
|
||||||
|
int[] channels = { 0, 1 }; |
||||||
|
//! [Using 50 bins for hue and 60 for saturation]
|
||||||
|
|
||||||
|
//! [Calculate the histograms for the HSV images]
|
||||||
|
Mat histBase = new Mat(), histHalfDown = new Mat(), histTest1 = new Mat(), histTest2 = new Mat(); |
||||||
|
|
||||||
|
List<Mat> hsvBaseList = Arrays.asList(hsvBase); |
||||||
|
Imgproc.calcHist(hsvBaseList, new MatOfInt(channels), new Mat(), histBase, new MatOfInt(histSize), new MatOfFloat(ranges), false); |
||||||
|
Core.normalize(histBase, histBase, 0, 1, Core.NORM_MINMAX); |
||||||
|
|
||||||
|
List<Mat> hsvHalfDownList = Arrays.asList(hsvHalfDown); |
||||||
|
Imgproc.calcHist(hsvHalfDownList, new MatOfInt(channels), new Mat(), histHalfDown, new MatOfInt(histSize), new MatOfFloat(ranges), false); |
||||||
|
Core.normalize(histHalfDown, histHalfDown, 0, 1, Core.NORM_MINMAX); |
||||||
|
|
||||||
|
List<Mat> hsvTest1List = Arrays.asList(hsvTest1); |
||||||
|
Imgproc.calcHist(hsvTest1List, new MatOfInt(channels), new Mat(), histTest1, new MatOfInt(histSize), new MatOfFloat(ranges), false); |
||||||
|
Core.normalize(histTest1, histTest1, 0, 1, Core.NORM_MINMAX); |
||||||
|
|
||||||
|
List<Mat> hsvTest2List = Arrays.asList(hsvTest2); |
||||||
|
Imgproc.calcHist(hsvTest2List, new MatOfInt(channels), new Mat(), histTest2, new MatOfInt(histSize), new MatOfFloat(ranges), false); |
||||||
|
Core.normalize(histTest2, histTest2, 0, 1, Core.NORM_MINMAX); |
||||||
|
//! [Calculate the histograms for the HSV images]
|
||||||
|
|
||||||
|
//! [Apply the histogram comparison methods]
|
||||||
|
for( int compareMethod = 0; compareMethod < 4; compareMethod++ ) { |
||||||
|
double baseBase = Imgproc.compareHist( histBase, histBase, compareMethod ); |
||||||
|
double baseHalf = Imgproc.compareHist( histBase, histHalfDown, compareMethod ); |
||||||
|
double baseTest1 = Imgproc.compareHist( histBase, histTest1, compareMethod ); |
||||||
|
double baseTest2 = Imgproc.compareHist( histBase, histTest2, compareMethod ); |
||||||
|
|
||||||
|
System.out.println("Method " + compareMethod + " Perfect, Base-Half, Base-Test(1), Base-Test(2) : " + baseBase + " / " + baseHalf |
||||||
|
+ " / " + baseTest1 + " / " + baseTest2); |
||||||
|
} |
||||||
|
//! [Apply the histogram comparison methods]
|
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
public class CompareHistDemo { |
||||||
|
public static void main(String[] args) { |
||||||
|
// Load the native OpenCV library
|
||||||
|
System.loadLibrary(Core.NATIVE_LIBRARY_NAME); |
||||||
|
|
||||||
|
new CompareHist().run(args); |
||||||
|
} |
||||||
|
} |
@ -0,0 +1,49 @@ |
|||||||
|
import org.opencv.core.Core; |
||||||
|
import org.opencv.core.Mat; |
||||||
|
import org.opencv.highgui.HighGui; |
||||||
|
import org.opencv.imgcodecs.Imgcodecs; |
||||||
|
import org.opencv.imgproc.Imgproc; |
||||||
|
|
||||||
|
class EqualizeHist { |
||||||
|
public void run(String[] args) { |
||||||
|
//! [Load image]
|
||||||
|
String filename = args.length > 0 ? args[0] : "../data/lena.jpg"; |
||||||
|
Mat src = Imgcodecs.imread(filename); |
||||||
|
if (src.empty()) { |
||||||
|
System.err.println("Cannot read image: " + filename); |
||||||
|
System.exit(0); |
||||||
|
} |
||||||
|
//! [Load image]
|
||||||
|
|
||||||
|
//! [Convert to grayscale]
|
||||||
|
Imgproc.cvtColor(src, src, Imgproc.COLOR_BGR2GRAY); |
||||||
|
//! [Convert to grayscale]
|
||||||
|
|
||||||
|
//! [Apply Histogram Equalization]
|
||||||
|
Mat dst = new Mat(); |
||||||
|
Imgproc.equalizeHist( src, dst ); |
||||||
|
//! [Apply Histogram Equalization]
|
||||||
|
|
||||||
|
//! [Display results]
|
||||||
|
HighGui.imshow( "Source image", src ); |
||||||
|
HighGui.imshow( "Equalized Image", dst ); |
||||||
|
//! [Display results]
|
||||||
|
|
||||||
|
//! [Wait until user exits the program]
|
||||||
|
HighGui.waitKey(0); |
||||||
|
//! [Wait until user exits the program]
|
||||||
|
|
||||||
|
System.exit(0); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
public class EqualizeHistDemo { |
||||||
|
|
||||||
|
public static void main(String[] args) { |
||||||
|
// Load the native OpenCV library
|
||||||
|
System.loadLibrary(Core.NATIVE_LIBRARY_NAME); |
||||||
|
|
||||||
|
new EqualizeHist().run(args); |
||||||
|
} |
||||||
|
|
||||||
|
} |
@ -0,0 +1,80 @@ |
|||||||
|
import org.opencv.core.Core; |
||||||
|
import org.opencv.core.Mat; |
||||||
|
import org.opencv.core.MatOfPoint2f; |
||||||
|
import org.opencv.core.Point; |
||||||
|
import org.opencv.highgui.HighGui; |
||||||
|
import org.opencv.imgcodecs.Imgcodecs; |
||||||
|
import org.opencv.imgproc.Imgproc; |
||||||
|
|
||||||
|
class GeometricTransforms { |
||||||
|
public void run(String[] args) { |
||||||
|
//! [Load the image]
|
||||||
|
String filename = args.length > 0 ? args[0] : "../data/lena.jpg"; |
||||||
|
Mat src = Imgcodecs.imread(filename); |
||||||
|
if (src.empty()) { |
||||||
|
System.err.println("Cannot read image: " + filename); |
||||||
|
System.exit(0); |
||||||
|
} |
||||||
|
//! [Load the image]
|
||||||
|
|
||||||
|
//! [Set your 3 points to calculate the Affine Transform]
|
||||||
|
Point[] srcTri = new Point[3]; |
||||||
|
srcTri[0] = new Point( 0, 0 ); |
||||||
|
srcTri[1] = new Point( src.cols() - 1, 0 ); |
||||||
|
srcTri[2] = new Point( 0, src.rows() - 1 ); |
||||||
|
|
||||||
|
Point[] dstTri = new Point[3]; |
||||||
|
dstTri[0] = new Point( 0, src.rows()*0.33 ); |
||||||
|
dstTri[1] = new Point( src.cols()*0.85, src.rows()*0.25 ); |
||||||
|
dstTri[2] = new Point( src.cols()*0.15, src.rows()*0.7 ); |
||||||
|
//! [Set your 3 points to calculate the Affine Transform]
|
||||||
|
|
||||||
|
//! [Get the Affine Transform]
|
||||||
|
Mat warpMat = Imgproc.getAffineTransform( new MatOfPoint2f(srcTri), new MatOfPoint2f(dstTri) ); |
||||||
|
//! [Get the Affine Transform]
|
||||||
|
|
||||||
|
//! [Apply the Affine Transform just found to the src image]
|
||||||
|
Mat warpDst = Mat.zeros( src.rows(), src.cols(), src.type() ); |
||||||
|
|
||||||
|
Imgproc.warpAffine( src, warpDst, warpMat, warpDst.size() ); |
||||||
|
//! [Apply the Affine Transform just found to the src image]
|
||||||
|
|
||||||
|
/** Rotating the image after Warp */ |
||||||
|
|
||||||
|
//! [Compute a rotation matrix with respect to the center of the image]
|
||||||
|
Point center = new Point(warpDst.cols() / 2, warpDst.rows() / 2); |
||||||
|
double angle = -50.0; |
||||||
|
double scale = 0.6; |
||||||
|
//! [Compute a rotation matrix with respect to the center of the image]
|
||||||
|
|
||||||
|
//! [Get the rotation matrix with the specifications above]
|
||||||
|
Mat rotMat = Imgproc.getRotationMatrix2D( center, angle, scale ); |
||||||
|
//! [Get the rotation matrix with the specifications above]
|
||||||
|
|
||||||
|
//! [Rotate the warped image]
|
||||||
|
Mat warpRotateDst = new Mat(); |
||||||
|
Imgproc.warpAffine( warpDst, warpRotateDst, rotMat, warpDst.size() ); |
||||||
|
//! [Rotate the warped image]
|
||||||
|
|
||||||
|
//! [Show what you got]
|
||||||
|
HighGui.imshow( "Source image", src ); |
||||||
|
HighGui.imshow( "Warp", warpDst ); |
||||||
|
HighGui.imshow( "Warp + Rotate", warpRotateDst ); |
||||||
|
//! [Show what you got]
|
||||||
|
|
||||||
|
//! [Wait until user exits the program]
|
||||||
|
HighGui.waitKey(0); |
||||||
|
//! [Wait until user exits the program]
|
||||||
|
|
||||||
|
System.exit(0); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
public class GeometricTransformsDemo { |
||||||
|
public static void main(String[] args) { |
||||||
|
// Load the native OpenCV library
|
||||||
|
System.loadLibrary(Core.NATIVE_LIBRARY_NAME); |
||||||
|
|
||||||
|
new GeometricTransforms().run(args); |
||||||
|
} |
||||||
|
} |
@ -0,0 +1,71 @@ |
|||||||
|
from __future__ import print_function |
||||||
|
from __future__ import division |
||||||
|
import cv2 as cv |
||||||
|
import numpy as np |
||||||
|
import argparse |
||||||
|
|
||||||
|
def Hist_and_Backproj(val): |
||||||
|
## [initialize] |
||||||
|
bins = val |
||||||
|
histSize = max(bins, 2) |
||||||
|
ranges = [0, 180] # hue_range |
||||||
|
## [initialize] |
||||||
|
|
||||||
|
## [Get the Histogram and normalize it] |
||||||
|
hist = cv.calcHist([hue], [0], None, [histSize], ranges, accumulate=False) |
||||||
|
cv.normalize(hist, hist, alpha=0, beta=255, norm_type=cv.NORM_MINMAX) |
||||||
|
## [Get the Histogram and normalize it] |
||||||
|
|
||||||
|
## [Get Backprojection] |
||||||
|
backproj = cv.calcBackProject([hue], [0], hist, ranges, scale=1) |
||||||
|
## [Get Backprojection] |
||||||
|
|
||||||
|
## [Draw the backproj] |
||||||
|
cv.imshow('BackProj', backproj) |
||||||
|
## [Draw the backproj] |
||||||
|
|
||||||
|
## [Draw the histogram] |
||||||
|
w = 400 |
||||||
|
h = 400 |
||||||
|
bin_w = int(round(w / histSize)) |
||||||
|
histImg = np.zeros((h, w, 3), dtype=np.uint8) |
||||||
|
|
||||||
|
for i in range(bins): |
||||||
|
cv.rectangle(histImg, (i*bin_w, h), ( (i+1)*bin_w, h - int(round( hist[i]*h/255.0 )) ), (0, 0, 255), cv.FILLED) |
||||||
|
|
||||||
|
cv.imshow('Histogram', histImg) |
||||||
|
## [Draw the histogram] |
||||||
|
|
||||||
|
## [Read the image] |
||||||
|
parser = argparse.ArgumentParser(description='Code for Back Projection tutorial.') |
||||||
|
parser.add_argument('--input', help='Path to input image.') |
||||||
|
args = parser.parse_args() |
||||||
|
|
||||||
|
src = cv.imread(args.input) |
||||||
|
if src is None: |
||||||
|
print('Could not open or find the image:', args.input) |
||||||
|
exit(0) |
||||||
|
## [Read the image] |
||||||
|
|
||||||
|
## [Transform it to HSV] |
||||||
|
hsv = cv.cvtColor(src, cv.COLOR_BGR2HSV) |
||||||
|
## [Transform it to HSV] |
||||||
|
|
||||||
|
## [Use only the Hue value] |
||||||
|
ch = (0, 0) |
||||||
|
hue = np.empty(hsv.shape, hsv.dtype) |
||||||
|
cv.mixChannels([hsv], [hue], ch) |
||||||
|
## [Use only the Hue value] |
||||||
|
|
||||||
|
## [Create Trackbar to enter the number of bins] |
||||||
|
window_image = 'Source image' |
||||||
|
cv.namedWindow(window_image) |
||||||
|
bins = 25 |
||||||
|
cv.createTrackbar('* Hue bins: ', window_image, bins, 180, Hist_and_Backproj ) |
||||||
|
Hist_and_Backproj(bins) |
||||||
|
## [Create Trackbar to enter the number of bins] |
||||||
|
|
||||||
|
## [Show the image] |
||||||
|
cv.imshow(window_image, src) |
||||||
|
cv.waitKey() |
||||||
|
## [Show the image] |
@ -0,0 +1,79 @@ |
|||||||
|
from __future__ import print_function |
||||||
|
import cv2 as cv |
||||||
|
import numpy as np |
||||||
|
import argparse |
||||||
|
|
||||||
|
low = 20 |
||||||
|
up = 20 |
||||||
|
|
||||||
|
def callback_low(val): |
||||||
|
global low |
||||||
|
low = val |
||||||
|
|
||||||
|
def callback_up(val): |
||||||
|
global up |
||||||
|
up = val |
||||||
|
|
||||||
|
def pickPoint(event, x, y, flags, param): |
||||||
|
if event != cv.EVENT_LBUTTONDOWN: |
||||||
|
return |
||||||
|
|
||||||
|
# Fill and get the mask |
||||||
|
seed = (x, y) |
||||||
|
newMaskVal = 255 |
||||||
|
newVal = (120, 120, 120) |
||||||
|
connectivity = 8 |
||||||
|
flags = connectivity + (newMaskVal << 8 ) + cv.FLOODFILL_FIXED_RANGE + cv.FLOODFILL_MASK_ONLY |
||||||
|
|
||||||
|
mask2 = np.zeros((src.shape[0] + 2, src.shape[1] + 2), dtype=np.uint8) |
||||||
|
print('low:', low, 'up:', up) |
||||||
|
cv.floodFill(src, mask2, seed, newVal, (low, low, low), (up, up, up), flags) |
||||||
|
mask = mask2[1:-1,1:-1] |
||||||
|
|
||||||
|
cv.imshow('Mask', mask) |
||||||
|
Hist_and_Backproj(mask) |
||||||
|
|
||||||
|
def Hist_and_Backproj(mask): |
||||||
|
h_bins = 30 |
||||||
|
s_bins = 32 |
||||||
|
histSize = [h_bins, s_bins] |
||||||
|
h_range = [0, 180] |
||||||
|
s_range = [0, 256] |
||||||
|
ranges = h_range + s_range # Concat list |
||||||
|
channels = [0, 1] |
||||||
|
|
||||||
|
# Get the Histogram and normalize it |
||||||
|
hist = cv.calcHist([hsv], channels, mask, histSize, ranges, accumulate=False) |
||||||
|
cv.normalize(hist, hist, alpha=0, beta=255, norm_type=cv.NORM_MINMAX) |
||||||
|
|
||||||
|
# Get Backprojection |
||||||
|
backproj = cv.calcBackProject([hsv], channels, hist, ranges, scale=1) |
||||||
|
|
||||||
|
# Draw the backproj |
||||||
|
cv.imshow('BackProj', backproj) |
||||||
|
|
||||||
|
# Read the image |
||||||
|
parser = argparse.ArgumentParser(description='Code for Back Projection tutorial.') |
||||||
|
parser.add_argument('--input', help='Path to input image.') |
||||||
|
args = parser.parse_args() |
||||||
|
|
||||||
|
src = cv.imread(args.input) |
||||||
|
if src is None: |
||||||
|
print('Could not open or find the image:', args.input) |
||||||
|
exit(0) |
||||||
|
|
||||||
|
# Transform it to HSV |
||||||
|
hsv = cv.cvtColor(src, cv.COLOR_BGR2HSV) |
||||||
|
|
||||||
|
# Show the image |
||||||
|
window_image = 'Source image' |
||||||
|
cv.namedWindow(window_image) |
||||||
|
cv.imshow(window_image, src) |
||||||
|
|
||||||
|
# Set Trackbars for floodfill thresholds |
||||||
|
cv.createTrackbar('Low thresh', window_image, low, 255, callback_low) |
||||||
|
cv.createTrackbar('High thresh', window_image, up, 255, callback_up) |
||||||
|
# Set a Mouse Callback |
||||||
|
cv.setMouseCallback(window_image, pickPoint) |
||||||
|
|
||||||
|
cv.waitKey() |
@ -0,0 +1,71 @@ |
|||||||
|
from __future__ import print_function |
||||||
|
from __future__ import division |
||||||
|
import cv2 as cv |
||||||
|
import numpy as np |
||||||
|
import argparse |
||||||
|
|
||||||
|
## [Load image] |
||||||
|
parser = argparse.ArgumentParser(description='Code for Histogram Calculation tutorial.') |
||||||
|
parser.add_argument('--input', help='Path to input image.', default='../data/lena.jpg') |
||||||
|
args = parser.parse_args() |
||||||
|
|
||||||
|
src = cv.imread(args.input) |
||||||
|
if src is None: |
||||||
|
print('Could not open or find the image:', args.input) |
||||||
|
exit(0) |
||||||
|
## [Load image] |
||||||
|
|
||||||
|
## [Separate the image in 3 places ( B, G and R )] |
||||||
|
bgr_planes = cv.split(src) |
||||||
|
## [Separate the image in 3 places ( B, G and R )] |
||||||
|
|
||||||
|
## [Establish the number of bins] |
||||||
|
histSize = 256 |
||||||
|
## [Establish the number of bins] |
||||||
|
|
||||||
|
## [Set the ranges ( for B,G,R) )] |
||||||
|
histRange = (0, 256) # the upper boundary is exclusive |
||||||
|
## [Set the ranges ( for B,G,R) )] |
||||||
|
|
||||||
|
## [Set histogram param] |
||||||
|
accumulate = False |
||||||
|
## [Set histogram param] |
||||||
|
|
||||||
|
## [Compute the histograms] |
||||||
|
b_hist = cv.calcHist(bgr_planes, [0], None, [histSize], histRange, accumulate=accumulate) |
||||||
|
g_hist = cv.calcHist(bgr_planes, [1], None, [histSize], histRange, accumulate=accumulate) |
||||||
|
r_hist = cv.calcHist(bgr_planes, [2], None, [histSize], histRange, accumulate=accumulate) |
||||||
|
## [Compute the histograms] |
||||||
|
|
||||||
|
## [Draw the histograms for B, G and R] |
||||||
|
hist_w = 512 |
||||||
|
hist_h = 400 |
||||||
|
bin_w = int(round( hist_w/histSize )) |
||||||
|
|
||||||
|
histImage = np.zeros((hist_h, hist_w, 3), dtype=np.uint8) |
||||||
|
## [Draw the histograms for B, G and R] |
||||||
|
|
||||||
|
## [Normalize the result to ( 0, histImage.rows )] |
||||||
|
cv.normalize(b_hist, b_hist, alpha=0, beta=hist_h, norm_type=cv.NORM_MINMAX) |
||||||
|
cv.normalize(g_hist, g_hist, alpha=0, beta=hist_h, norm_type=cv.NORM_MINMAX) |
||||||
|
cv.normalize(r_hist, r_hist, alpha=0, beta=hist_h, norm_type=cv.NORM_MINMAX) |
||||||
|
## [Normalize the result to ( 0, histImage.rows )] |
||||||
|
|
||||||
|
## [Draw for each channel] |
||||||
|
for i in range(1, histSize): |
||||||
|
cv.line(histImage, ( bin_w*(i-1), hist_h - int(round(b_hist[i-1])) ), |
||||||
|
( bin_w*(i), hist_h - int(round(b_hist[i])) ), |
||||||
|
( 255, 0, 0), thickness=2) |
||||||
|
cv.line(histImage, ( bin_w*(i-1), hist_h - int(round(g_hist[i-1])) ), |
||||||
|
( bin_w*(i), hist_h - int(round(g_hist[i])) ), |
||||||
|
( 0, 255, 0), thickness=2) |
||||||
|
cv.line(histImage, ( bin_w*(i-1), hist_h - int(round(r_hist[i-1])) ), |
||||||
|
( bin_w*(i), hist_h - int(round(r_hist[i])) ), |
||||||
|
( 0, 0, 255), thickness=2) |
||||||
|
## [Draw for each channel] |
||||||
|
|
||||||
|
## [Display] |
||||||
|
cv.imshow('Source image', src) |
||||||
|
cv.imshow('calcHist Demo', histImage) |
||||||
|
cv.waitKey() |
||||||
|
## [Display] |
@ -0,0 +1,69 @@ |
|||||||
|
from __future__ import print_function |
||||||
|
from __future__ import division |
||||||
|
import cv2 as cv |
||||||
|
import numpy as np |
||||||
|
import argparse |
||||||
|
|
||||||
|
## [Load three images with different environment settings] |
||||||
|
parser = argparse.ArgumentParser(description='Code for Histogram Comparison tutorial.') |
||||||
|
parser.add_argument('--input1', help='Path to input image 1.') |
||||||
|
parser.add_argument('--input2', help='Path to input image 2.') |
||||||
|
parser.add_argument('--input3', help='Path to input image 3.') |
||||||
|
args = parser.parse_args() |
||||||
|
|
||||||
|
src_base = cv.imread(args.input1) |
||||||
|
src_test1 = cv.imread(args.input2) |
||||||
|
src_test2 = cv.imread(args.input3) |
||||||
|
if src_base is None or src_test1 is None or src_test2 is None: |
||||||
|
print('Could not open or find the images!') |
||||||
|
exit(0) |
||||||
|
## [Load three images with different environment settings] |
||||||
|
|
||||||
|
## [Convert to HSV] |
||||||
|
hsv_base = cv.cvtColor(src_base, cv.COLOR_BGR2HSV) |
||||||
|
hsv_test1 = cv.cvtColor(src_test1, cv.COLOR_BGR2HSV) |
||||||
|
hsv_test2 = cv.cvtColor(src_test2, cv.COLOR_BGR2HSV) |
||||||
|
## [Convert to HSV] |
||||||
|
|
||||||
|
## [Convert to HSV half] |
||||||
|
hsv_half_down = hsv_base[hsv_base.shape[0]//2:,:] |
||||||
|
## [Convert to HSV half] |
||||||
|
|
||||||
|
## [Using 50 bins for hue and 60 for saturation] |
||||||
|
h_bins = 50 |
||||||
|
s_bins = 60 |
||||||
|
histSize = [h_bins, s_bins] |
||||||
|
|
||||||
|
# hue varies from 0 to 179, saturation from 0 to 255 |
||||||
|
h_ranges = [0, 180] |
||||||
|
s_ranges = [0, 256] |
||||||
|
ranges = h_ranges + s_ranges # concat lists |
||||||
|
|
||||||
|
# Use the 0-th and 1-st channels |
||||||
|
channels = [0, 1] |
||||||
|
## [Using 50 bins for hue and 60 for saturation] |
||||||
|
|
||||||
|
## [Calculate the histograms for the HSV images] |
||||||
|
hist_base = cv.calcHist([hsv_base], channels, None, histSize, ranges, accumulate=False) |
||||||
|
cv.normalize(hist_base, hist_base, alpha=0, beta=1, norm_type=cv.NORM_MINMAX) |
||||||
|
|
||||||
|
hist_half_down = cv.calcHist([hsv_half_down], channels, None, histSize, ranges, accumulate=False) |
||||||
|
cv.normalize(hist_half_down, hist_half_down, alpha=0, beta=1, norm_type=cv.NORM_MINMAX) |
||||||
|
|
||||||
|
hist_test1 = cv.calcHist([hsv_test1], channels, None, histSize, ranges, accumulate=False) |
||||||
|
cv.normalize(hist_test1, hist_test1, alpha=0, beta=1, norm_type=cv.NORM_MINMAX) |
||||||
|
|
||||||
|
hist_test2 = cv.calcHist([hsv_test2], channels, None, histSize, ranges, accumulate=False) |
||||||
|
cv.normalize(hist_test2, hist_test2, alpha=0, beta=1, norm_type=cv.NORM_MINMAX) |
||||||
|
## [Calculate the histograms for the HSV images] |
||||||
|
|
||||||
|
## [Apply the histogram comparison methods] |
||||||
|
for compare_method in range(4): |
||||||
|
base_base = cv.compareHist(hist_base, hist_base, compare_method) |
||||||
|
base_half = cv.compareHist(hist_base, hist_half_down, compare_method) |
||||||
|
base_test1 = cv.compareHist(hist_base, hist_test1, compare_method) |
||||||
|
base_test2 = cv.compareHist(hist_base, hist_test2, compare_method) |
||||||
|
|
||||||
|
print('Method:', compare_method, 'Perfect, Base-Half, Base-Test(1), Base-Test(2) :',\ |
||||||
|
base_base, '/', base_half, '/', base_test1, '/', base_test2) |
||||||
|
## [Apply the histogram comparison methods] |
@ -0,0 +1,31 @@ |
|||||||
|
from __future__ import print_function |
||||||
|
import cv2 as cv |
||||||
|
import argparse |
||||||
|
|
||||||
|
## [Load image] |
||||||
|
parser = argparse.ArgumentParser(description='Code for Histogram Equalization tutorial.') |
||||||
|
parser.add_argument('--input', help='Path to input image.', default='../data/lena.jpg') |
||||||
|
args = parser.parse_args() |
||||||
|
|
||||||
|
src = cv.imread(args.input) |
||||||
|
if src is None: |
||||||
|
print('Could not open or find the image:', args.input) |
||||||
|
exit(0) |
||||||
|
## [Load image] |
||||||
|
|
||||||
|
## [Convert to grayscale] |
||||||
|
src = cv.cvtColor(src, cv.COLOR_BGR2GRAY) |
||||||
|
## [Convert to grayscale] |
||||||
|
|
||||||
|
## [Apply Histogram Equalization] |
||||||
|
dst = cv.equalizeHist(src); |
||||||
|
## [Apply Histogram Equalization] |
||||||
|
|
||||||
|
## [Display results] |
||||||
|
cv.imshow('Source image', src) |
||||||
|
cv.imshow('Equalized Image', dst) |
||||||
|
## [Display results] |
||||||
|
|
||||||
|
## [Wait until user exits the program] |
||||||
|
cv.waitKey() |
||||||
|
## [Wait until user exits the program] |
@ -0,0 +1,54 @@ |
|||||||
|
from __future__ import print_function |
||||||
|
import cv2 as cv |
||||||
|
import numpy as np |
||||||
|
import argparse |
||||||
|
|
||||||
|
## [Load the image] |
||||||
|
parser = argparse.ArgumentParser(description='Code for Affine Transformations tutorial.') |
||||||
|
parser.add_argument('--input', help='Path to input image.', default='../data/lena.jpg') |
||||||
|
args = parser.parse_args() |
||||||
|
|
||||||
|
src = cv.imread(args.input) |
||||||
|
if src is None: |
||||||
|
print('Could not open or find the image:', args.input) |
||||||
|
exit(0) |
||||||
|
## [Load the image] |
||||||
|
|
||||||
|
## [Set your 3 points to calculate the Affine Transform] |
||||||
|
srcTri = np.array( [[0, 0], [src.shape[1] - 1, 0], [0, src.shape[0] - 1]] ).astype(np.float32) |
||||||
|
dstTri = np.array( [[0, src.shape[1]*0.33], [src.shape[1]*0.85, src.shape[0]*0.25], [src.shape[1]*0.15, src.shape[0]*0.7]] ).astype(np.float32) |
||||||
|
## [Set your 3 points to calculate the Affine Transform] |
||||||
|
|
||||||
|
## [Get the Affine Transform] |
||||||
|
warp_mat = cv.getAffineTransform(srcTri, dstTri) |
||||||
|
## [Get the Affine Transform] |
||||||
|
|
||||||
|
## [Apply the Affine Transform just found to the src image] |
||||||
|
warp_dst = cv.warpAffine(src, warp_mat, (src.shape[1], src.shape[0])) |
||||||
|
## [Apply the Affine Transform just found to the src image] |
||||||
|
|
||||||
|
# Rotating the image after Warp |
||||||
|
|
||||||
|
## [Compute a rotation matrix with respect to the center of the image] |
||||||
|
center = (warp_dst.shape[1]//2, warp_dst.shape[0]//2) |
||||||
|
angle = -50 |
||||||
|
scale = 0.6 |
||||||
|
## [Compute a rotation matrix with respect to the center of the image] |
||||||
|
|
||||||
|
## [Get the rotation matrix with the specifications above] |
||||||
|
rot_mat = cv.getRotationMatrix2D( center, angle, scale ) |
||||||
|
## [Get the rotation matrix with the specifications above] |
||||||
|
|
||||||
|
## [Rotate the warped image] |
||||||
|
warp_rotate_dst = cv.warpAffine(warp_dst, rot_mat, (warp_dst.shape[1], warp_dst.shape[0])) |
||||||
|
## [Rotate the warped image] |
||||||
|
|
||||||
|
## [Show what you got] |
||||||
|
cv.imshow('Source image', src) |
||||||
|
cv.imshow('Warp', warp_dst) |
||||||
|
cv.imshow('Warp + Rotate', warp_rotate_dst) |
||||||
|
## [Show what you got] |
||||||
|
|
||||||
|
## [Wait until user exits the program] |
||||||
|
cv.waitKey() |
||||||
|
## [Wait until user exits the program] |
Loading…
Reference in new issue