The following issues were found

modules/video/misc/java/test/TrackerCreateTest.java
7 issues
JUnit 4 tests that set up tests should use the @Before annotation, JUnit5 tests should use @BeforeEach or @BeforeAll
Design

Line: 16

              
public class TrackerCreateTest extends OpenCVTestCase {

    @Override
    protected void setUp() throws Exception {
        super.setUp();
    }



            

Reported by PMD.

Overriding method merely calls super
Design

Line: 17

              public class TrackerCreateTest extends OpenCVTestCase {

    @Override
    protected void setUp() throws Exception {
        super.setUp();
    }


    public void testCreateTrackerGOTURN() {

            

Reported by PMD.

JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 22

                  }


    public void testCreateTrackerGOTURN() {
        try {
            Tracker tracker = TrackerGOTURN.create();
            assert(tracker != null);
        } catch (CvException e) {
            // expected, model files may be missing

            

Reported by PMD.

Avoid empty catch blocks
Error

Line: 26

                      try {
            Tracker tracker = TrackerGOTURN.create();
            assert(tracker != null);
        } catch (CvException e) {
            // expected, model files may be missing
        }
    }

    public void testCreateTrackerMIL() {

            

Reported by PMD.

JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 31

                      }
    }

    public void testCreateTrackerMIL() {
        Tracker tracker = TrackerMIL.create();
        assert(tracker != null);
        Mat mat = new Mat(100, 100, CvType.CV_8UC1);
        Rect rect = new Rect(10, 10, 30, 30);
        tracker.init(mat, rect);  // should not crash (https://github.com/opencv/opencv/issues/19915)

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 36

                      assert(tracker != null);
        Mat mat = new Mat(100, 100, CvType.CV_8UC1);
        Rect rect = new Rect(10, 10, 30, 30);
        tracker.init(mat, rect);  // should not crash (https://github.com/opencv/opencv/issues/19915)
    }

}

            

Reported by PMD.

Avoid unused imports such as 'org.opencv.core.Core'
Design

Line: 3

              package org.opencv.test.video;

import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.CvException;
import org.opencv.core.Mat;
import org.opencv.core.Rect;
import org.opencv.test.OpenCVTestCase;


            

Reported by PMD.

modules/ml/misc/python/test/test_knearest.py
7 issues
Unable to import 'cv2'
Error

Line: 2 Column: 1

              #!/usr/bin/env python
import cv2 as cv

from tests_common import NewOpenCVTests

class knearest_test(NewOpenCVTests):
    def test_load(self):
        k_nearest = cv.ml.KNearest_load(self.find_file("ml/opencv_ml_knn.xml"))
        self.assertFalse(k_nearest.empty())

            

Reported by Pylint.

Unable to import 'tests_common'
Error

Line: 4 Column: 1

              #!/usr/bin/env python
import cv2 as cv

from tests_common import NewOpenCVTests

class knearest_test(NewOpenCVTests):
    def test_load(self):
        k_nearest = cv.ml.KNearest_load(self.find_file("ml/opencv_ml_knn.xml"))
        self.assertFalse(k_nearest.empty())

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python
import cv2 as cv

from tests_common import NewOpenCVTests

class knearest_test(NewOpenCVTests):
    def test_load(self):
        k_nearest = cv.ml.KNearest_load(self.find_file("ml/opencv_ml_knn.xml"))
        self.assertFalse(k_nearest.empty())

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 6 Column: 1

              
from tests_common import NewOpenCVTests

class knearest_test(NewOpenCVTests):
    def test_load(self):
        k_nearest = cv.ml.KNearest_load(self.find_file("ml/opencv_ml_knn.xml"))
        self.assertFalse(k_nearest.empty())
        self.assertTrue(k_nearest.isTrained())


            

Reported by Pylint.

Missing class docstring
Error

Line: 6 Column: 1

              
from tests_common import NewOpenCVTests

class knearest_test(NewOpenCVTests):
    def test_load(self):
        k_nearest = cv.ml.KNearest_load(self.find_file("ml/opencv_ml_knn.xml"))
        self.assertFalse(k_nearest.empty())
        self.assertTrue(k_nearest.isTrained())


            

Reported by Pylint.

Class name "knearest_test" doesn't conform to PascalCase naming style
Error

Line: 6 Column: 1

              
from tests_common import NewOpenCVTests

class knearest_test(NewOpenCVTests):
    def test_load(self):
        k_nearest = cv.ml.KNearest_load(self.find_file("ml/opencv_ml_knn.xml"))
        self.assertFalse(k_nearest.empty())
        self.assertTrue(k_nearest.isTrained())


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 7 Column: 5

              from tests_common import NewOpenCVTests

class knearest_test(NewOpenCVTests):
    def test_load(self):
        k_nearest = cv.ml.KNearest_load(self.find_file("ml/opencv_ml_knn.xml"))
        self.assertFalse(k_nearest.empty())
        self.assertTrue(k_nearest.isTrained())

if __name__ == '__main__':

            

Reported by Pylint.

modules/java/test/pure_test/src/org/opencv/test/OpenCVTestRunner.java
7 issues
Avoid reassigning parameters such as 'extension'
Design

Line: 16

                  private static String TAG = "opencv_test_java";


    public static String getTempFileName(String extension)
    {
        if (!extension.startsWith("."))
            extension = "." + extension;
        try {
            File tmp = File.createTempFile("OpenCV", extension);

            

Reported by PMD.

System.out.println is used
Design

Line: 32

                  }

    static public void Log(String message) {
        System.out.println(TAG + " :: " +  message);
    }

    static public void Log(Mat m) {
        System.out.println(TAG + " :: " + m + "\n " + m.dump());
    }

            

Reported by PMD.

System.out.println is used
Design

Line: 36

                  }

    static public void Log(Mat m) {
        System.out.println(TAG + " :: " + m + "\n " + m.dump());
    }

    public static String getOutputFileName(String name)
    {
        return getTempFileName(name);

            

Reported by PMD.

All methods are static. Consider using a utility class instead. Alternatively, you could add a private constructor or make the class abstract to silence this warning.
Design

Line: 8

              
import org.opencv.core.Mat;

public class OpenCVTestRunner {
    public static String LENA_PATH = "";
    public static String CHESS_PATH = "";
    public static String LBPCASCADE_FRONTALFACE_PATH = "";

    private static String TAG = "opencv_test_java";

            

Reported by PMD.

This call to String.startsWith can be rewritten using String.charAt(0)
Performance

Line: 18

              
    public static String getTempFileName(String extension)
    {
        if (!extension.startsWith("."))
            extension = "." + extension;
        try {
            File tmp = File.createTempFile("OpenCV", extension);
            String path = tmp.getAbsolutePath();
            tmp.delete();

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 22

                          extension = "." + extension;
        try {
            File tmp = File.createTempFile("OpenCV", extension);
            String path = tmp.getAbsolutePath();
            tmp.delete();
            return path;
        } catch (IOException e) {
            Log("Failed to get temp file name. Exception is thrown: " + e);
        }

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 23

                      try {
            File tmp = File.createTempFile("OpenCV", extension);
            String path = tmp.getAbsolutePath();
            tmp.delete();
            return path;
        } catch (IOException e) {
            Log("Failed to get temp file name. Exception is thrown: " + e);
        }
        return null;

            

Reported by PMD.

samples/python/kmeans.py
6 issues
Unable to import 'cv2'
Error

Line: 17 Column: 1

              from __future__ import print_function

import numpy as np
import cv2 as cv

from gaussian_mix import make_gaussians

def main():
    cluster_n = 5

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 21 Column: 1

              
from gaussian_mix import make_gaussians

def main():
    cluster_n = 5
    img_size = 512

    # generating bright palette
    colors = np.zeros((1, cluster_n, 3), np.uint8)

            

Reported by Pylint.

Variable name "y" doesn't conform to snake_case naming style
Error

Line: 39 Column: 17

                      _ret, labels, _centers = cv.kmeans(points, cluster_n, None, term_crit, 10, 0)

        img = np.zeros((img_size, img_size, 3), np.uint8)
        for (x, y), label in zip(np.int32(points), labels.ravel()):
            c = list(map(int, colors[label]))

            cv.circle(img, (x, y), 1, c, -1)

        cv.imshow('kmeans', img)

            

Reported by Pylint.

Variable name "x" doesn't conform to snake_case naming style
Error

Line: 39 Column: 14

                      _ret, labels, _centers = cv.kmeans(points, cluster_n, None, term_crit, 10, 0)

        img = np.zeros((img_size, img_size, 3), np.uint8)
        for (x, y), label in zip(np.int32(points), labels.ravel()):
            c = list(map(int, colors[label]))

            cv.circle(img, (x, y), 1, c, -1)

        cv.imshow('kmeans', img)

            

Reported by Pylint.

Variable name "c" doesn't conform to snake_case naming style
Error

Line: 40 Column: 13

              
        img = np.zeros((img_size, img_size, 3), np.uint8)
        for (x, y), label in zip(np.int32(points), labels.ravel()):
            c = list(map(int, colors[label]))

            cv.circle(img, (x, y), 1, c, -1)

        cv.imshow('kmeans', img)
        ch = cv.waitKey(0)

            

Reported by Pylint.

Variable name "ch" doesn't conform to snake_case naming style
Error

Line: 45 Column: 9

                          cv.circle(img, (x, y), 1, c, -1)

        cv.imshow('kmeans', img)
        ch = cv.waitKey(0)
        if ch == 27:
            break

    print('Done')


            

Reported by Pylint.

samples/python/logpolar.py
6 issues
Unable to import 'cv2'
Error

Line: 17 Column: 1

              from __future__ import print_function

import numpy as np
import cv2 as cv

def main():
    import sys
    try:
        fn = sys.argv[1]

            

Reported by Pylint.

Unused numpy imported as np
Error

Line: 16 Column: 1

              # Python 2/3 compatibility
from __future__ import print_function

import numpy as np
import cv2 as cv

def main():
    import sys
    try:

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 19 Column: 1

              import numpy as np
import cv2 as cv

def main():
    import sys
    try:
        fn = sys.argv[1]
    except IndexError:
        fn = 'fruits.jpg'

            

Reported by Pylint.

Import outside toplevel (sys)
Error

Line: 20 Column: 5

              import cv2 as cv

def main():
    import sys
    try:
        fn = sys.argv[1]
    except IndexError:
        fn = 'fruits.jpg'


            

Reported by Pylint.

Variable name "fn" doesn't conform to snake_case naming style
Error

Line: 22 Column: 9

              def main():
    import sys
    try:
        fn = sys.argv[1]
    except IndexError:
        fn = 'fruits.jpg'

    img = cv.imread(cv.samples.findFile(fn))
    if img is None:

            

Reported by Pylint.

Variable name "fn" doesn't conform to snake_case naming style
Error

Line: 24 Column: 9

                  try:
        fn = sys.argv[1]
    except IndexError:
        fn = 'fruits.jpg'

    img = cv.imread(cv.samples.findFile(fn))
    if img is None:
        print('Failed to load image file:', fn)
        sys.exit(1)

            

Reported by Pylint.

samples/java/tutorial_code/Histograms_Matching/histogram_equalization/EqualizeHistDemo.java
6 issues
System.err.println is used
Design

Line: 13

                      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]

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 12

                      //! [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]


            

Reported by PMD.

System.exit() should not be used in J2EE/JEE apps
Error

Line: 14

                      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);

            

Reported by PMD.

System.exit() should not be used in J2EE/JEE apps
Error

Line: 36

                      HighGui.waitKey(0);
        //! [Wait until user exits the program]

        System.exit(0);
    }
}

public class EqualizeHistDemo {


            

Reported by PMD.

All methods are static. Consider using a utility class instead. Alternatively, you could add a private constructor or make the class abstract to silence this warning.
Design

Line: 40

                  }
}

public class EqualizeHistDemo {

    public static void main(String[] args) {
        // Load the native OpenCV library
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);


            

Reported by PMD.

Consider using varargs for methods or constructors which take an array the last parameter.
Design

Line: 8

              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);

            

Reported by PMD.

samples/dnn/dnn_model_runner/dnn_conversion/tf/detection/py_to_py_ssd_mobilenet.py
6 issues
Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.
Security blacklist

Line: 17
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b310-urllib-urlopen

                  tf_frozen_graph_name = 'frozen_inference_graph'

    try:
        urllib.request.urlretrieve(model_link, tf_model_tar)
    except Exception:
        print("TF {} was not retrieved: {}".format(model_name, model_link))
        return

    print("TF {} was retrieved.".format(model_name))

            

Reported by Bandit.

Catching too general exception Exception
Error

Line: 18 Column: 12

              
    try:
        urllib.request.urlretrieve(model_link, tf_model_tar)
    except Exception:
        print("TF {} was not retrieved: {}".format(model_name, model_link))
        return

    print("TF {} was retrieved.".format(model_name))


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import os
import tarfile
import urllib

DETECTION_MODELS_URL = 'http://download.tensorflow.org/models/object_detection/'


def extract_tf_frozen_graph(model_name, extracted_model_path):
    # define model archive name

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 8 Column: 1

              DETECTION_MODELS_URL = 'http://download.tensorflow.org/models/object_detection/'


def extract_tf_frozen_graph(model_name, extracted_model_path):
    # define model archive name
    tf_model_tar = model_name + '.tar.gz'
    # define link to retrieve model archive
    model_link = DETECTION_MODELS_URL + tf_model_tar


            

Reported by Pylint.

Either all return statements in a function should return an expression, or none of them should.
Error

Line: 8 Column: 1

              DETECTION_MODELS_URL = 'http://download.tensorflow.org/models/object_detection/'


def extract_tf_frozen_graph(model_name, extracted_model_path):
    # define model archive name
    tf_model_tar = model_name + '.tar.gz'
    # define link to retrieve model archive
    model_link = DETECTION_MODELS_URL + tf_model_tar


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 37 Column: 1

                  return frozen_graph_path


def main():
    tf_model_name = 'ssd_mobilenet_v1_coco_2017_11_17'
    graph_extraction_dir = "./"
    frozen_graph_path = extract_tf_frozen_graph(tf_model_name, graph_extraction_dir)
    print("Frozen graph path for {}: {}".format(tf_model_name, frozen_graph_path))


            

Reported by Pylint.

samples/python/tutorial_code/features2D/feature_detection/SURF_detection_Demo.py
6 issues
Unable to import 'cv2'
Error

Line: 2 Column: 1

              from __future__ import print_function
import cv2 as cv
import numpy as np
import argparse

parser = argparse.ArgumentParser(description='Code for Feature Detection tutorial.')
parser.add_argument('--input', help='Path to input image.', default='box.png')
args = parser.parse_args()


            

Reported by Pylint.

Module name "SURF_detection_Demo" doesn't conform to snake_case naming style
Error

Line: 1 Column: 1

              from __future__ import print_function
import cv2 as cv
import numpy as np
import argparse

parser = argparse.ArgumentParser(description='Code for Feature Detection tutorial.')
parser.add_argument('--input', help='Path to input image.', default='box.png')
args = parser.parse_args()


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from __future__ import print_function
import cv2 as cv
import numpy as np
import argparse

parser = argparse.ArgumentParser(description='Code for Feature Detection tutorial.')
parser.add_argument('--input', help='Path to input image.', default='box.png')
args = parser.parse_args()


            

Reported by Pylint.

standard import "import argparse" should be placed before "import cv2 as cv"
Error

Line: 4 Column: 1

              from __future__ import print_function
import cv2 as cv
import numpy as np
import argparse

parser = argparse.ArgumentParser(description='Code for Feature Detection tutorial.')
parser.add_argument('--input', help='Path to input image.', default='box.png')
args = parser.parse_args()


            

Reported by Pylint.

Consider using sys.exit()
Error

Line: 13 Column: 5

              src = cv.imread(cv.samples.findFile(args.input), cv.IMREAD_GRAYSCALE)
if src is None:
    print('Could not open or find the image:', args.input)
    exit(0)

#-- Step 1: Detect the keypoints using SURF Detector
minHessian = 400
detector = cv.xfeatures2d_SURF.create(hessianThreshold=minHessian)
keypoints = detector.detect(src)

            

Reported by Pylint.

Constant name "minHessian" doesn't conform to UPPER_CASE naming style
Error

Line: 16 Column: 1

                  exit(0)

#-- Step 1: Detect the keypoints using SURF Detector
minHessian = 400
detector = cv.xfeatures2d_SURF.create(hessianThreshold=minHessian)
keypoints = detector.detect(src)

#-- Draw keypoints
img_keypoints = np.empty((src.shape[0], src.shape[1], 3), dtype=np.uint8)

            

Reported by Pylint.

platforms/winpack_dldt/2020.1/patch.config.py
6 issues
Undefined variable 'applyPatch'
Error

Line: 1 Column: 1

              applyPatch('20200313-ngraph-disable-tests-examples.patch', 'ngraph')
applyPatch('20200313-dldt-disable-unused-targets.patch')
applyPatch('20200313-dldt-fix-binaries-location.patch')
applyPatch('20200318-dldt-pdb.patch')
applyPatch('20200319-dldt-fix-msvs2019-v16.5.0.patch')

            

Reported by Pylint.

Undefined variable 'applyPatch'
Error

Line: 2 Column: 1

              applyPatch('20200313-ngraph-disable-tests-examples.patch', 'ngraph')
applyPatch('20200313-dldt-disable-unused-targets.patch')
applyPatch('20200313-dldt-fix-binaries-location.patch')
applyPatch('20200318-dldt-pdb.patch')
applyPatch('20200319-dldt-fix-msvs2019-v16.5.0.patch')

            

Reported by Pylint.

Undefined variable 'applyPatch'
Error

Line: 3 Column: 1

              applyPatch('20200313-ngraph-disable-tests-examples.patch', 'ngraph')
applyPatch('20200313-dldt-disable-unused-targets.patch')
applyPatch('20200313-dldt-fix-binaries-location.patch')
applyPatch('20200318-dldt-pdb.patch')
applyPatch('20200319-dldt-fix-msvs2019-v16.5.0.patch')

            

Reported by Pylint.

Undefined variable 'applyPatch'
Error

Line: 4 Column: 1

              applyPatch('20200313-ngraph-disable-tests-examples.patch', 'ngraph')
applyPatch('20200313-dldt-disable-unused-targets.patch')
applyPatch('20200313-dldt-fix-binaries-location.patch')
applyPatch('20200318-dldt-pdb.patch')
applyPatch('20200319-dldt-fix-msvs2019-v16.5.0.patch')

            

Reported by Pylint.

Undefined variable 'applyPatch'
Error

Line: 5 Column: 1

              applyPatch('20200313-dldt-disable-unused-targets.patch')
applyPatch('20200313-dldt-fix-binaries-location.patch')
applyPatch('20200318-dldt-pdb.patch')
applyPatch('20200319-dldt-fix-msvs2019-v16.5.0.patch')

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              applyPatch('20200313-ngraph-disable-tests-examples.patch', 'ngraph')
applyPatch('20200313-dldt-disable-unused-targets.patch')
applyPatch('20200313-dldt-fix-binaries-location.patch')
applyPatch('20200318-dldt-pdb.patch')
applyPatch('20200319-dldt-fix-msvs2019-v16.5.0.patch')

            

Reported by Pylint.

modules/python/test/test_watershed.py
6 issues
Unable to import 'cv2'
Error

Line: 11 Column: 1

              from __future__ import print_function

import numpy as np
import cv2 as cv

from tests_common import NewOpenCVTests

class watershed_test(NewOpenCVTests):
    def test_watershed(self):

            

Reported by Pylint.

Missing class docstring
Error

Line: 15 Column: 1

              
from tests_common import NewOpenCVTests

class watershed_test(NewOpenCVTests):
    def test_watershed(self):

        img = self.get_sample('cv/inpaint/orig.png')
        markers = self.get_sample('cv/watershed/wshed_exp.png', 0)
        refSegments = self.get_sample('cv/watershed/wshed_segments.png')

            

Reported by Pylint.

Class name "watershed_test" doesn't conform to PascalCase naming style
Error

Line: 15 Column: 1

              
from tests_common import NewOpenCVTests

class watershed_test(NewOpenCVTests):
    def test_watershed(self):

        img = self.get_sample('cv/inpaint/orig.png')
        markers = self.get_sample('cv/watershed/wshed_exp.png', 0)
        refSegments = self.get_sample('cv/watershed/wshed_segments.png')

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 16 Column: 5

              from tests_common import NewOpenCVTests

class watershed_test(NewOpenCVTests):
    def test_watershed(self):

        img = self.get_sample('cv/inpaint/orig.png')
        markers = self.get_sample('cv/watershed/wshed_exp.png', 0)
        refSegments = self.get_sample('cv/watershed/wshed_segments.png')


            

Reported by Pylint.

Variable name "refSegments" doesn't conform to snake_case naming style
Error

Line: 20 Column: 9

              
        img = self.get_sample('cv/inpaint/orig.png')
        markers = self.get_sample('cv/watershed/wshed_exp.png', 0)
        refSegments = self.get_sample('cv/watershed/wshed_segments.png')

        if img is None or markers is None:
            self.assertEqual(0, 1, 'Missing test data')

        colors = np.int32( list(np.ndindex(3, 3, 3)) ) * 122

            

Reported by Pylint.

Variable name "refSegments" doesn't conform to snake_case naming style
Error

Line: 30 Column: 13

                      segments = colors[np.maximum(markers, 0)]

        if refSegments is None:
            refSegments = segments.copy()
            cv.imwrite(self.extraTestDataPath + '/cv/watershed/wshed_segments.png', refSegments)

        self.assertLess(cv.norm(segments - refSegments, cv.NORM_L1) / 255.0, 50)

if __name__ == '__main__':

            

Reported by Pylint.