The following issues were found

samples/python/tutorial_code/TrackingMotion/good_features_to_track/goodFeaturesToTrack_Demo.py
22 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
import random as rng

source_window = 'Image'
maxTrackbar = 100
rng.seed(12345)

            

Reported by Pylint.

Redefining name 'maxCorners' from outer scope (line 53)
Error

Line: 12 Column: 5

              rng.seed(12345)

def goodFeaturesToTrack_Demo(val):
    maxCorners = max(val, 1)

    # Parameters for Shi-Tomasi algorithm
    qualityLevel = 0.01
    minDistance = 10
    blockSize = 3

            

Reported by Pylint.

Module name "goodFeaturesToTrack_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
import random as rng

source_window = 'Image'
maxTrackbar = 100
rng.seed(12345)

            

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
import random as rng

source_window = 'Image'
maxTrackbar = 100
rng.seed(12345)

            

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
import random as rng

source_window = 'Image'
maxTrackbar = 100
rng.seed(12345)

            

Reported by Pylint.

standard import "import random as rng" should be placed before "import cv2 as cv"
Error

Line: 5 Column: 1

              import cv2 as cv
import numpy as np
import argparse
import random as rng

source_window = 'Image'
maxTrackbar = 100
rng.seed(12345)


            

Reported by Pylint.

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

Line: 7 Column: 1

              import argparse
import random as rng

source_window = 'Image'
maxTrackbar = 100
rng.seed(12345)

def goodFeaturesToTrack_Demo(val):
    maxCorners = max(val, 1)

            

Reported by Pylint.

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

Line: 8 Column: 1

              import random as rng

source_window = 'Image'
maxTrackbar = 100
rng.seed(12345)

def goodFeaturesToTrack_Demo(val):
    maxCorners = max(val, 1)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 11 Column: 1

              maxTrackbar = 100
rng.seed(12345)

def goodFeaturesToTrack_Demo(val):
    maxCorners = max(val, 1)

    # Parameters for Shi-Tomasi algorithm
    qualityLevel = 0.01
    minDistance = 10

            

Reported by Pylint.

Function name "goodFeaturesToTrack_Demo" doesn't conform to snake_case naming style
Error

Line: 11 Column: 1

              maxTrackbar = 100
rng.seed(12345)

def goodFeaturesToTrack_Demo(val):
    maxCorners = max(val, 1)

    # Parameters for Shi-Tomasi algorithm
    qualityLevel = 0.01
    minDistance = 10

            

Reported by Pylint.

platforms/osx/build_docs.py
22 issues
Unused import multiprocessing
Error

Line: 7 Column: 1

              """

from __future__ import print_function
import os, sys, multiprocessing, argparse, traceback
from subprocess import check_call, check_output, CalledProcessError, Popen

# import common code
sys.path.insert(0, os.path.abspath(os.path.abspath(os.path.dirname(__file__))+'/../ios'))
from build_docs import DocBuilder

            

Reported by Pylint.

Unused import traceback
Error

Line: 7 Column: 1

              """

from __future__ import print_function
import os, sys, multiprocessing, argparse, traceback
from subprocess import check_call, check_output, CalledProcessError, Popen

# import common code
sys.path.insert(0, os.path.abspath(os.path.abspath(os.path.dirname(__file__))+'/../ios'))
from build_docs import DocBuilder

            

Reported by Pylint.

Unused CalledProcessError imported from subprocess
Error

Line: 8 Column: 1

              
from __future__ import print_function
import os, sys, multiprocessing, argparse, traceback
from subprocess import check_call, check_output, CalledProcessError, Popen

# import common code
sys.path.insert(0, os.path.abspath(os.path.abspath(os.path.dirname(__file__))+'/../ios'))
from build_docs import DocBuilder


            

Reported by Pylint.

Unused check_call imported from subprocess
Error

Line: 8 Column: 1

              
from __future__ import print_function
import os, sys, multiprocessing, argparse, traceback
from subprocess import check_call, check_output, CalledProcessError, Popen

# import common code
sys.path.insert(0, os.path.abspath(os.path.abspath(os.path.dirname(__file__))+'/../ios'))
from build_docs import DocBuilder


            

Reported by Pylint.

Unused check_output imported from subprocess
Error

Line: 8 Column: 1

              
from __future__ import print_function
import os, sys, multiprocessing, argparse, traceback
from subprocess import check_call, check_output, CalledProcessError, Popen

# import common code
sys.path.insert(0, os.path.abspath(os.path.abspath(os.path.dirname(__file__))+'/../ios'))
from build_docs import DocBuilder


            

Reported by Pylint.

Unused Popen imported from subprocess
Error

Line: 8 Column: 1

              
from __future__ import print_function
import os, sys, multiprocessing, argparse, traceback
from subprocess import check_call, check_output, CalledProcessError, Popen

# import common code
sys.path.insert(0, os.path.abspath(os.path.abspath(os.path.dirname(__file__))+'/../ios'))
from build_docs import DocBuilder


            

Reported by Pylint.

Module import itself
Error

Line: 12 Column: 1

              
# import common code
sys.path.insert(0, os.path.abspath(os.path.abspath(os.path.dirname(__file__))+'/../ios'))
from build_docs import DocBuilder

class OSXDocBuilder(DocBuilder):

    def getToolchain(self):
        return None

            

Reported by Pylint.

Multiple imports on one line (os, sys, multiprocessing, argparse, traceback)
Error

Line: 7 Column: 1

              """

from __future__ import print_function
import os, sys, multiprocessing, argparse, traceback
from subprocess import check_call, check_output, CalledProcessError, Popen

# import common code
sys.path.insert(0, os.path.abspath(os.path.abspath(os.path.dirname(__file__))+'/../ios'))
from build_docs import DocBuilder

            

Reported by Pylint.

Consider possible security implications associated with check_call module.
Security blacklist

Line: 8
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b404-import-subprocess

              
from __future__ import print_function
import os, sys, multiprocessing, argparse, traceback
from subprocess import check_call, check_output, CalledProcessError, Popen

# import common code
sys.path.insert(0, os.path.abspath(os.path.abspath(os.path.dirname(__file__))+'/../ios'))
from build_docs import DocBuilder


            

Reported by Bandit.

Import "from build_docs import DocBuilder" should be placed at the top of the module
Error

Line: 12 Column: 1

              
# import common code
sys.path.insert(0, os.path.abspath(os.path.abspath(os.path.dirname(__file__))+'/../ios'))
from build_docs import DocBuilder

class OSXDocBuilder(DocBuilder):

    def getToolchain(self):
        return None

            

Reported by Pylint.

modules/objdetect/misc/java/test/CascadeClassifierTest.java
22 issues
This class has too many methods, consider refactoring it.
Design

Line: 12

              import org.opencv.test.OpenCVTestCase;
import org.opencv.test.OpenCVTestRunner;

public class CascadeClassifierTest extends OpenCVTestCase {

    private CascadeClassifier cc;

    @Override
    protected void setUp() throws Exception {

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 14

              
public class CascadeClassifierTest extends OpenCVTestCase {

    private CascadeClassifier cc;

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


            

Reported by PMD.

JUnit 4 tests that set up tests should use the @Before annotation, JUnit5 tests should use @BeforeEach or @BeforeAll
Design

Line: 16

              
    private CascadeClassifier cc;

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

        cc = null;
    }

            

Reported by PMD.

Assigning an Object to null is a code smell. Consider refactoring.
Error

Line: 20

                  protected void setUp() throws Exception {
        super.setUp();

        cc = null;
    }

    public void testCascadeClassifier() {
        cc = new CascadeClassifier();
        assertNotNull(cc);

            

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: 23

                      cc = null;
    }

    public void testCascadeClassifier() {
        cc = new CascadeClassifier();
        assertNotNull(cc);
    }

    public void testCascadeClassifierString() {

            

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: 28

                      assertNotNull(cc);
    }

    public void testCascadeClassifierString() {
        cc = new CascadeClassifier(OpenCVTestRunner.LBPCASCADE_FRONTALFACE_PATH);
        assertNotNull(cc);
    }

    public void testDetectMultiScaleMatListOfRect() {

            

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: 33

                      assertNotNull(cc);
    }

    public void testDetectMultiScaleMatListOfRect() {
        CascadeClassifier cc = new CascadeClassifier(OpenCVTestRunner.LBPCASCADE_FRONTALFACE_PATH);
        MatOfRect faces = new MatOfRect();

        Mat greyLena = new Mat();
        Imgproc.cvtColor(rgbLena, greyLena, Imgproc.COLOR_RGB2GRAY);

            

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: 45

                      assertEquals(1, faces.total());
    }

    public void testDetectMultiScaleMatListOfRectDouble() {
        fail("Not yet implemented");
    }

    public void testDetectMultiScaleMatListOfRectDoubleInt() {
        fail("Not yet implemented");

            

Reported by PMD.

The String literal 'Not yet implemented' appears 12 times in this file; the first occurrence is on line 46
Error

Line: 46

                  }

    public void testDetectMultiScaleMatListOfRectDouble() {
        fail("Not yet implemented");
    }

    public void testDetectMultiScaleMatListOfRectDoubleInt() {
        fail("Not yet implemented");
    }

            

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: 49

                      fail("Not yet implemented");
    }

    public void testDetectMultiScaleMatListOfRectDoubleInt() {
        fail("Not yet implemented");
    }

    public void testDetectMultiScaleMatListOfRectDoubleIntInt() {
        fail("Not yet implemented");

            

Reported by PMD.

modules/dnn/misc/java/test/DnnListRegressionTest.java
22 issues
Avoid throwing raw exception types.
Design

Line: 56

              
        String envTestDataPath = System.getenv(ENV_OPENCV_TEST_DATA_PATH);

        if(envTestDataPath == null) throw new Exception(ENV_OPENCV_TEST_DATA_PATH + " has to be defined!");

        File testDataPath = new File(envTestDataPath);

        File f = new File(testDataPath, "dnn/grace_hopper_227.png");
        sourceImageFile = f.toString();

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 62

              
        File f = new File(testDataPath, "dnn/grace_hopper_227.png");
        sourceImageFile = f.toString();
        if(!f.exists()) throw new Exception("Test image is missing: " + sourceImageFile);

        net = Dnn.readNetFromTensorflow(modelFileName);

        Mat image = Imgcodecs.imread(sourceImageFile);
        assertNotNull("Loading image from file failed!", image);

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 35

              
    private final static String ENV_OPENCV_TEST_DATA_PATH = "OPENCV_TEST_DATA_PATH";

    String modelFileName = "";
    String sourceImageFile = "";

    Net net;

    @Override

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 36

                  private final static String ENV_OPENCV_TEST_DATA_PATH = "OPENCV_TEST_DATA_PATH";

    String modelFileName = "";
    String sourceImageFile = "";

    Net net;

    @Override
    protected void setUp() throws Exception {

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 38

                  String modelFileName = "";
    String sourceImageFile = "";

    Net net;

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


            

Reported by PMD.

JUnit 4 tests that set up tests should use the @Before annotation, JUnit5 tests should use @BeforeEach or @BeforeAll
Design

Line: 40

              
    Net net;

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

        String envDnnTestDataPath = System.getenv(ENV_OPENCV_DNN_TEST_DATA_PATH);


            

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: 75

                      net.setInput(inputBlob, "input");
    }

    public void testSetInputsNames() {
        List<String> inputs = new ArrayList();
        inputs.add("input");
        try {
            net.setInputsNames(inputs);
        } catch(Exception e) {

            

Reported by PMD.

Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block
Design

Line: 80

                      inputs.add("input");
        try {
            net.setInputsNames(inputs);
        } catch(Exception e) {
            fail("Net setInputsNames failed: " + e.getMessage());
        }
    }

    public void testForward() {

            

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: 85

                      }
    }

    public void testForward() {
        List<Mat> outs = new ArrayList();
        List<String> outNames = new ArrayList();
        outNames.add("softmax2");
        try {
            net.forward(outs,outNames);

            

Reported by PMD.

Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block
Design

Line: 91

                      outNames.add("softmax2");
        try {
            net.forward(outs,outNames);
        } catch(Exception e) {
            fail("Net forward failed: " + e.getMessage());
        }
    }

    public void testGetMemoryConsumption() {

            

Reported by PMD.

modules/java/generator/android/java/org/opencv/android/Utils.java
22 issues
Avoid instantiating FileInputStream, FileOutputStream, FileReader, or FileWriter
Performance

Line: 31

                          File resDir = context.getDir(dirname, Context.MODE_PRIVATE);
            File resFile = new File(resDir, resName);

            FileOutputStream os = new FileOutputStream(resFile);

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);

            

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: 17

              import java.io.IOException;
import java.io.InputStream;

public class Utils {

    public static String exportResource(Context context, int resourceId) {
        return exportResource(context, resourceId, "OpenCV_data");
    }


            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 24

                  }

    public static String exportResource(Context context, int resourceId, String dirname) {
        String fullname = context.getResources().getString(resourceId);
        String resName = fullname.substring(fullname.lastIndexOf("/") + 1);
        try {
            InputStream is = context.getResources().openRawResource(resourceId);
            File resDir = context.getDir(dirname, Context.MODE_PRIVATE);
            File resFile = new File(resDir, resName);

            

Reported by PMD.

String.indexOf(char) is faster than String.indexOf(String).
Performance

Line: 25

              
    public static String exportResource(Context context, int resourceId, String dirname) {
        String fullname = context.getResources().getString(resourceId);
        String resName = fullname.substring(fullname.lastIndexOf("/") + 1);
        try {
            InputStream is = context.getResources().openRawResource(resourceId);
            File resDir = context.getDir(dirname, Context.MODE_PRIVATE);
            File resFile = new File(resDir, resName);


            

Reported by PMD.

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

Line: 25

              
    public static String exportResource(Context context, int resourceId, String dirname) {
        String fullname = context.getResources().getString(resourceId);
        String resName = fullname.substring(fullname.lastIndexOf("/") + 1);
        try {
            InputStream is = context.getResources().openRawResource(resourceId);
            File resDir = context.getDir(dirname, Context.MODE_PRIVATE);
            File resFile = new File(resDir, resName);


            

Reported by PMD.

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

Line: 25

              
    public static String exportResource(Context context, int resourceId, String dirname) {
        String fullname = context.getResources().getString(resourceId);
        String resName = fullname.substring(fullname.lastIndexOf("/") + 1);
        try {
            InputStream is = context.getResources().openRawResource(resourceId);
            File resDir = context.getDir(dirname, Context.MODE_PRIVATE);
            File resFile = new File(resDir, resName);


            

Reported by PMD.

Ensure that resources like this InputStream object are closed after use
Error

Line: 27

                      String fullname = context.getResources().getString(resourceId);
        String resName = fullname.substring(fullname.lastIndexOf("/") + 1);
        try {
            InputStream is = context.getResources().openRawResource(resourceId);
            File resDir = context.getDir(dirname, Context.MODE_PRIVATE);
            File resFile = new File(resDir, resName);

            FileOutputStream os = new FileOutputStream(resFile);


            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 27

                      String fullname = context.getResources().getString(resourceId);
        String resName = fullname.substring(fullname.lastIndexOf("/") + 1);
        try {
            InputStream is = context.getResources().openRawResource(resourceId);
            File resDir = context.getDir(dirname, Context.MODE_PRIVATE);
            File resFile = new File(resDir, resName);

            FileOutputStream os = new FileOutputStream(resFile);


            

Reported by PMD.

Ensure that resources like this FileOutputStream object are closed after use
Error

Line: 31

                          File resDir = context.getDir(dirname, Context.MODE_PRIVATE);
            File resFile = new File(resDir, resName);

            FileOutputStream os = new FileOutputStream(resFile);

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);

            

Reported by PMD.

Avoid assignments in operands
Error

Line: 35

              
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            is.close();
            os.close();


            

Reported by PMD.

doc/tools/add_signatures.py
22 issues
Unused pprint imported from pprint
Error

Line: 19 Column: 1

              sys.dont_write_bytecode = True  # Don't generate .pyc files / __pycache__ directories

import os
from pprint import pprint
import re
import logging
import json

import html_functions

            

Reported by Pylint.

Unused import re
Error

Line: 20 Column: 1

              
import os
from pprint import pprint
import re
import logging
import json

import html_functions
import doxygen_scan

            

Reported by Pylint.

Using xml.etree.ElementTree.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.ElementTree.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called
Security blacklist

Line: 46
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b313-b320-xml-bad-elementtree

                  print("Loaded Python signatures: %d" % len(python_signatures))

import xml.etree.ElementTree as ET
root = ET.parse(ROOT_DIR + 'opencv.tag')
files_dict = {}

# constants and function from opencv.tag
namespaces = root.findall("./compound[@kind='namespace']")
#print("Found {} namespaces".format(len(namespaces)))

            

Reported by Bandit.

Use lazy % formatting in logging functions
Error

Line: 89 Column: 9

              
    active_anchors_dict = {a.anchor: a for a in active_anchors}
    if len(active_anchors_dict) != len(active_anchors):
        logging.info('Duplicate entries detected: %s -> %s (%s)' % (len(active_anchors), len(active_anchors_dict), file))

    files_processed = files_processed + 1

    #pprint(active_anchors)
    symbols_processed = symbols_processed + len(active_anchors_dict)

            

Reported by Pylint.

Use lazy % formatting in logging functions
Error

Line: 96 Column: 5

                  #pprint(active_anchors)
    symbols_processed = symbols_processed + len(active_anchors_dict)

    logging.info('File: %r' % file)
    html_functions.insert_python_signatures(python_signatures, active_anchors_dict, ROOT_DIR + file)

print('Done (processed files %d, symbols %d, skipped %d files)' % (files_processed, symbols_processed, files_skipped))

            

Reported by Pylint.

Import "import os" should be placed at the top of the module
Error

Line: 18 Column: 1

              import sys
sys.dont_write_bytecode = True  # Don't generate .pyc files / __pycache__ directories

import os
from pprint import pprint
import re
import logging
import json


            

Reported by Pylint.

Import "from pprint import pprint" should be placed at the top of the module
Error

Line: 19 Column: 1

              sys.dont_write_bytecode = True  # Don't generate .pyc files / __pycache__ directories

import os
from pprint import pprint
import re
import logging
import json

import html_functions

            

Reported by Pylint.

Import "import re" should be placed at the top of the module
Error

Line: 20 Column: 1

              
import os
from pprint import pprint
import re
import logging
import json

import html_functions
import doxygen_scan

            

Reported by Pylint.

Import "import logging" should be placed at the top of the module
Error

Line: 21 Column: 1

              import os
from pprint import pprint
import re
import logging
import json

import html_functions
import doxygen_scan


            

Reported by Pylint.

Import "import json" should be placed at the top of the module
Error

Line: 22 Column: 1

              from pprint import pprint
import re
import logging
import json

import html_functions
import doxygen_scan

loglevel=os.environ.get("LOGLEVEL", None)

            

Reported by Pylint.

samples/python/tutorial_code/ml/introduction_to_pca/introduction_to_pca.py
22 issues
Unable to import 'cv2'
Error

Line: 3 Column: 1

              from __future__ import print_function
from __future__ import division
import cv2 as cv
import numpy as np
import argparse
from math import atan2, cos, sin, sqrt, pi

def drawAxis(img, p_, q_, colour, scale):
    p = list(p_)

            

Reported by Pylint.

Redefining name 'i' from outer scope (line 86)
Error

Line: 35 Column: 9

                  # Construct a buffer used by the pca analysis
    sz = len(pts)
    data_pts = np.empty((sz, 2), dtype=np.float64)
    for i in range(data_pts.shape[0]):
        data_pts[i,0] = pts[i,0,0]
        data_pts[i,1] = pts[i,0,1]

    # Perform PCA analysis
    mean = np.empty((0))

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from __future__ import print_function
from __future__ import division
import cv2 as cv
import numpy as np
import argparse
from math import atan2, cos, sin, sqrt, pi

def drawAxis(img, p_, q_, colour, scale):
    p = list(p_)

            

Reported by Pylint.

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

Line: 5 Column: 1

              from __future__ import division
import cv2 as cv
import numpy as np
import argparse
from math import atan2, cos, sin, sqrt, pi

def drawAxis(img, p_, q_, colour, scale):
    p = list(p_)
    q = list(q_)

            

Reported by Pylint.

standard import "from math import atan2, cos, sin, sqrt, pi" should be placed before "import cv2 as cv"
Error

Line: 6 Column: 1

              import cv2 as cv
import numpy as np
import argparse
from math import atan2, cos, sin, sqrt, pi

def drawAxis(img, p_, q_, colour, scale):
    p = list(p_)
    q = list(q_)
    ## [visualization1]

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 8 Column: 1

              import argparse
from math import atan2, cos, sin, sqrt, pi

def drawAxis(img, p_, q_, colour, scale):
    p = list(p_)
    q = list(q_)
    ## [visualization1]
    angle = atan2(p[1] - q[1], p[0] - q[0]) # angle in radians
    hypotenuse = sqrt((p[1] - q[1]) * (p[1] - q[1]) + (p[0] - q[0]) * (p[0] - q[0]))

            

Reported by Pylint.

Function name "drawAxis" doesn't conform to snake_case naming style
Error

Line: 8 Column: 1

              import argparse
from math import atan2, cos, sin, sqrt, pi

def drawAxis(img, p_, q_, colour, scale):
    p = list(p_)
    q = list(q_)
    ## [visualization1]
    angle = atan2(p[1] - q[1], p[0] - q[0]) # angle in radians
    hypotenuse = sqrt((p[1] - q[1]) * (p[1] - q[1]) + (p[0] - q[0]) * (p[0] - q[0]))

            

Reported by Pylint.

Argument name "p_" doesn't conform to snake_case naming style
Error

Line: 8 Column: 1

              import argparse
from math import atan2, cos, sin, sqrt, pi

def drawAxis(img, p_, q_, colour, scale):
    p = list(p_)
    q = list(q_)
    ## [visualization1]
    angle = atan2(p[1] - q[1], p[0] - q[0]) # angle in radians
    hypotenuse = sqrt((p[1] - q[1]) * (p[1] - q[1]) + (p[0] - q[0]) * (p[0] - q[0]))

            

Reported by Pylint.

Argument name "q_" doesn't conform to snake_case naming style
Error

Line: 8 Column: 1

              import argparse
from math import atan2, cos, sin, sqrt, pi

def drawAxis(img, p_, q_, colour, scale):
    p = list(p_)
    q = list(q_)
    ## [visualization1]
    angle = atan2(p[1] - q[1], p[0] - q[0]) # angle in radians
    hypotenuse = sqrt((p[1] - q[1]) * (p[1] - q[1]) + (p[0] - q[0]) * (p[0] - q[0]))

            

Reported by Pylint.

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

Line: 9 Column: 5

              from math import atan2, cos, sin, sqrt, pi

def drawAxis(img, p_, q_, colour, scale):
    p = list(p_)
    q = list(q_)
    ## [visualization1]
    angle = atan2(p[1] - q[1], p[0] - q[0]) # angle in radians
    hypotenuse = sqrt((p[1] - q[1]) * (p[1] - q[1]) + (p[0] - q[0]) * (p[0] - q[0]))


            

Reported by Pylint.

samples/java/tutorial_code/features2D/Homography/PerspectiveCorrection.java
21 issues
System.out.println is used
Design

Line: 25

                      //! [find-corners]

        if (!found1 || !found2) {
            System.out.println("Error, cannot find the chessboard corners in both images.");
            System.exit(-1);
        }

        //! [estimate-homography]
        Mat H = new Mat();

            

Reported by PMD.

System.out.println is used
Design

Line: 32

                      //! [estimate-homography]
        Mat H = new Mat();
        H = Calib3d.findHomography(corners1, corners2);
        System.out.println(H.dump());
        //! [estimate-homography]

        //! [warp-chessboard]
        Mat img1_warp = new Mat();
        Imgproc.warpPerspective(img1, img1_warp, H, img1.size());

            

Reported by PMD.

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

Line: 26

              
        if (!found1 || !found2) {
            System.out.println("Error, cannot find the chessboard corners in both images.");
            System.exit(-1);
        }

        //! [estimate-homography]
        Mat H = new Mat();
        H = Calib3d.findHomography(corners1, corners2);

            

Reported by PMD.

The initializer for variable 'H' is never used (overwritten on line 31)
Design

Line: 30

                      }

        //! [estimate-homography]
        Mat H = new Mat();
        H = Calib3d.findHomography(corners1, corners2);
        System.out.println(H.dump());
        //! [estimate-homography]

        //! [warp-chessboard]

            

Reported by PMD.

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

Line: 32

                      //! [estimate-homography]
        Mat H = new Mat();
        H = Calib3d.findHomography(corners1, corners2);
        System.out.println(H.dump());
        //! [estimate-homography]

        //! [warp-chessboard]
        Mat img1_warp = new Mat();
        Imgproc.warpPerspective(img1, img1_warp, H, img1.size());

            

Reported by PMD.

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

Line: 37

              
        //! [warp-chessboard]
        Mat img1_warp = new Mat();
        Imgproc.warpPerspective(img1, img1_warp, H, img1.size());
        //! [warp-chessboard]

        Mat img_draw_warp = new Mat();
        List<Mat> list1 = new ArrayList<>(), list2 = new ArrayList<>() ;
        list1.add(img2);

            

Reported by PMD.

This for loop can be replaced by a foreach loop
Design

Line: 54

                      Core.hconcat(list2, img_draw_matches);
        Point []corners1Arr = corners1.toArray();

        for (int i = 0 ; i < corners1Arr.length; i++) {
            Mat pt1 = new Mat(3, 1, CvType.CV_64FC1), pt2 = new Mat();
            pt1.put(0, 0, corners1Arr[i].x, corners1Arr[i].y, 1 );

            Core.gemm(H, pt1, 1, new Mat(), 0, pt2);
            double[] data = pt2.get(2, 0);

            

Reported by PMD.

Avoid instantiating new objects inside loops
Performance

Line: 55

                      Point []corners1Arr = corners1.toArray();

        for (int i = 0 ; i < corners1Arr.length; i++) {
            Mat pt1 = new Mat(3, 1, CvType.CV_64FC1), pt2 = new Mat();
            pt1.put(0, 0, corners1Arr[i].x, corners1Arr[i].y, 1 );

            Core.gemm(H, pt1, 1, new Mat(), 0, pt2);
            double[] data = pt2.get(2, 0);
            Core.divide(pt2, new Scalar(data[0]), pt2);

            

Reported by PMD.

Avoid instantiating new objects inside loops
Performance

Line: 55

                      Point []corners1Arr = corners1.toArray();

        for (int i = 0 ; i < corners1Arr.length; i++) {
            Mat pt1 = new Mat(3, 1, CvType.CV_64FC1), pt2 = new Mat();
            pt1.put(0, 0, corners1Arr[i].x, corners1Arr[i].y, 1 );

            Core.gemm(H, pt1, 1, new Mat(), 0, pt2);
            double[] data = pt2.get(2, 0);
            Core.divide(pt2, new Scalar(data[0]), pt2);

            

Reported by PMD.

Avoid instantiating new objects inside loops
Performance

Line: 58

                          Mat pt1 = new Mat(3, 1, CvType.CV_64FC1), pt2 = new Mat();
            pt1.put(0, 0, corners1Arr[i].x, corners1Arr[i].y, 1 );

            Core.gemm(H, pt1, 1, new Mat(), 0, pt2);
            double[] data = pt2.get(2, 0);
            Core.divide(pt2, new Scalar(data[0]), pt2);

            double[] data1 =pt2.get(0, 0);
            double[] data2 = pt2.get(1, 0);

            

Reported by PMD.

samples/java/tutorial_code/TrackingMotion/good_features_to_track/GoodFeaturesToTrackDemo.java
21 issues
System.err.println is used
Design

Line: 38

                      String filename = args.length > 0 ? args[0] : "../data/pic3.png";
        src = Imgcodecs.imread(filename);
        if (src.empty()) {
            System.err.println("Cannot read image: " + filename);
            System.exit(0);
        }

        Imgproc.cvtColor(src, srcGray, Imgproc.COLOR_BGR2GRAY);


            

Reported by PMD.

System.out.println is used
Design

Line: 106

                              blockSize, gradientSize, useHarrisDetector, k);

        /// Draw corners detected
        System.out.println("** Number of corners detected: " + corners.rows());
        int[] cornersData = new int[(int) (corners.total() * corners.channels())];
        corners.get(0, 0, cornersData);
        int radius = 4;
        for (int i = 0; i < corners.rows(); i++) {
            Imgproc.circle(copy, new Point(cornersData[i * 2], cornersData[i * 2 + 1]), radius,

            

Reported by PMD.

Private field 'src' could be made final; it is only initialized in the declaration or constructor.
Design

Line: 25

              import org.opencv.imgproc.Imgproc;

class GoodFeaturesToTrack {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private JFrame frame;
    private JLabel imgLabel;
    private static final int MAX_THRESHOLD = 100;
    private int maxCorners = 23;

            

Reported by PMD.

The field initializer for 'src' is never used (overwritten on line 36)
Design

Line: 25

              import org.opencv.imgproc.Imgproc;

class GoodFeaturesToTrack {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private JFrame frame;
    private JLabel imgLabel;
    private static final int MAX_THRESHOLD = 100;
    private int maxCorners = 23;

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 25

              import org.opencv.imgproc.Imgproc;

class GoodFeaturesToTrack {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private JFrame frame;
    private JLabel imgLabel;
    private static final int MAX_THRESHOLD = 100;
    private int maxCorners = 23;

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 26

              
class GoodFeaturesToTrack {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private JFrame frame;
    private JLabel imgLabel;
    private static final int MAX_THRESHOLD = 100;
    private int maxCorners = 23;
    private Random rng = new Random(12345);

            

Reported by PMD.

Private field 'srcGray' could be made final; it is only initialized in the declaration or constructor.
Design

Line: 26

              
class GoodFeaturesToTrack {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private JFrame frame;
    private JLabel imgLabel;
    private static final int MAX_THRESHOLD = 100;
    private int maxCorners = 23;
    private Random rng = new Random(12345);

            

Reported by PMD.

Private field 'frame' could be made final; it is only initialized in the declaration or constructor.
Design

Line: 27

              class GoodFeaturesToTrack {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private JFrame frame;
    private JLabel imgLabel;
    private static final int MAX_THRESHOLD = 100;
    private int maxCorners = 23;
    private Random rng = new Random(12345);


            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 27

              class GoodFeaturesToTrack {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private JFrame frame;
    private JLabel imgLabel;
    private static final int MAX_THRESHOLD = 100;
    private int maxCorners = 23;
    private Random rng = new Random(12345);


            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 28

                  private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private JFrame frame;
    private JLabel imgLabel;
    private static final int MAX_THRESHOLD = 100;
    private int maxCorners = 23;
    private Random rng = new Random(12345);

    public GoodFeaturesToTrack(String[] args) {

            

Reported by PMD.

samples/dnn/person_reid.py
21 issues
Unable to import 'cv2'
Error

Line: 19 Column: 1

              import argparse
import os.path
import numpy as np
import cv2 as cv

backends = (cv.dnn.DNN_BACKEND_DEFAULT,
    cv.dnn.DNN_BACKEND_INFERENCE_ENGINE,
    cv.dnn.DNN_BACKEND_OPENCV,
    cv.dnn.DNN_BACKEND_VKCOM,

            

Reported by Pylint.

Redefining built-in 'input'
Error

Line: 54 Column: 5

                  images = np.array(img_list)
    images = (images / 255.0 - MEAN) / STD

    input = cv.dnn.blobFromImages(images.astype(np.float32), ddepth = cv.CV_32F)
    return input

def extract_feature(img_dir, model_path, batch_size = 32, resize_h = 384, resize_w = 128, backend=cv.dnn.DNN_BACKEND_OPENCV, target=cv.dnn.DNN_TARGET_CPU):
    """
    Extract features from images in a target directory

            

Reported by Pylint.

Redefining name 'topk' from outer scope (line 139)
Error

Line: 139 Column: 36

                  dist = np.matmul(array1, array2.T)
    return dist

def topk(query_feat, gallery_feat, topk = 5):
    """
    Return the index of top K gallery images most similar to the query images
    :param query_feat: array of feature vectors of query images
    :param gallery_feat: array of feature vectors of gallery images
    :param topk: number of gallery images to return

            

Reported by Pylint.

Redefining name 'query_feat' from outer scope (line 236)
Error

Line: 139 Column: 10

                  dist = np.matmul(array1, array2.T)
    return dist

def topk(query_feat, gallery_feat, topk = 5):
    """
    Return the index of top K gallery images most similar to the query images
    :param query_feat: array of feature vectors of query images
    :param gallery_feat: array of feature vectors of gallery images
    :param topk: number of gallery images to return

            

Reported by Pylint.

Redefining name 'gallery_feat' from outer scope (line 237)
Error

Line: 139 Column: 22

                  dist = np.matmul(array1, array2.T)
    return dist

def topk(query_feat, gallery_feat, topk = 5):
    """
    Return the index of top K gallery images most similar to the query images
    :param query_feat: array of feature vectors of query images
    :param gallery_feat: array of feature vectors of gallery images
    :param topk: number of gallery images to return

            

Reported by Pylint.

Redefining name 'gallery_names' from outer scope (line 237)
Error

Line: 185 Column: 42

                  return ret


def visualization(topk_idx, query_names, gallery_names, output_dir = 'vis'):
    """
    Visualize the retrieval results with the person ReID model
    :param topk_idx: the index of ranked gallery images for each query image
    :param query_names: the list of paths of query images
    :param gallery_names: the list of paths of gallery images

            

Reported by Pylint.

Redefining name 'query_names' from outer scope (line 236)
Error

Line: 185 Column: 29

                  return ret


def visualization(topk_idx, query_names, gallery_names, output_dir = 'vis'):
    """
    Visualize the retrieval results with the person ReID model
    :param topk_idx: the index of ranked gallery images for each query image
    :param query_names: the list of paths of query images
    :param gallery_names: the list of paths of gallery images

            

Reported by Pylint.

Redefining name 'topk_idx' from outer scope (line 239)
Error

Line: 185 Column: 19

                  return ret


def visualization(topk_idx, query_names, gallery_names, output_dir = 'vis'):
    """
    Visualize the retrieval results with the person ReID model
    :param topk_idx: the index of ranked gallery images for each query image
    :param query_names: the list of paths of query images
    :param gallery_names: the list of paths of gallery images

            

Reported by Pylint.

Line too long (155/100)
Error

Line: 57 Column: 1

                  input = cv.dnn.blobFromImages(images.astype(np.float32), ddepth = cv.CV_32F)
    return input

def extract_feature(img_dir, model_path, batch_size = 32, resize_h = 384, resize_w = 128, backend=cv.dnn.DNN_BACKEND_OPENCV, target=cv.dnn.DNN_TARGET_CPU):
    """
    Extract features from images in a target directory
    :param img_dir: the input image directory
    :param model_path: path to ReID model
    :param batch_size: the batch size for each network inference iteration

            

Reported by Pylint.

Too many arguments (7/5)
Error

Line: 57 Column: 1

                  input = cv.dnn.blobFromImages(images.astype(np.float32), ddepth = cv.CV_32F)
    return input

def extract_feature(img_dir, model_path, batch_size = 32, resize_h = 384, resize_w = 128, backend=cv.dnn.DNN_BACKEND_OPENCV, target=cv.dnn.DNN_TARGET_CPU):
    """
    Extract features from images in a target directory
    :param img_dir: the input image directory
    :param model_path: path to ReID model
    :param batch_size: the batch size for each network inference iteration

            

Reported by Pylint.