The following issues were found

modules/python/test/test.py
11 issues
Unused import unittest
Error

Line: 14 Column: 1

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

import os
import unittest

# Python 3 moved urlopen to urllib.requests
try:
    from urllib.request import urlopen
except ImportError:

            

Reported by Pylint.

Unused urlopen imported from urllib.request
Error

Line: 18 Column: 5

              
# Python 3 moved urlopen to urllib.requests
try:
    from urllib.request import urlopen
except ImportError:
    from urllib import urlopen

from tests_common import NewOpenCVTests


            

Reported by Pylint.

Unused argument 'pattern'
Error

Line: 27 Column: 31

              
basedir = os.path.abspath(os.path.dirname(__file__))

def load_tests(loader, tests, pattern):
    cwd = os.getcwd()
    config_file = 'opencv_python_tests.cfg'
    locations = [cwd, basedir]
    if os.path.exists(config_file):
        with open(config_file, 'r') as f:

            

Reported by Pylint.

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

Line: 13 Column: 1

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

import os
import unittest

# Python 3 moved urlopen to urllib.requests
try:
    from urllib.request import urlopen

            

Reported by Pylint.

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

Line: 14 Column: 1

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

import os
import unittest

# Python 3 moved urlopen to urllib.requests
try:
    from urllib.request import urlopen
except ImportError:

            

Reported by Pylint.

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

Line: 22 Column: 1

              except ImportError:
    from urllib import urlopen

from tests_common import NewOpenCVTests


basedir = os.path.abspath(os.path.dirname(__file__))

def load_tests(loader, tests, pattern):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 27 Column: 1

              
basedir = os.path.abspath(os.path.dirname(__file__))

def load_tests(loader, tests, pattern):
    cwd = os.getcwd()
    config_file = 'opencv_python_tests.cfg'
    locations = [cwd, basedir]
    if os.path.exists(config_file):
        with open(config_file, 'r') as f:

            

Reported by Pylint.

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

Line: 32 Column: 40

                  config_file = 'opencv_python_tests.cfg'
    locations = [cwd, basedir]
    if os.path.exists(config_file):
        with open(config_file, 'r') as f:
            locations += [str(s).strip() for s in f.readlines()]
    else:
        print('WARNING: OpenCV tests config file ({}) is missing, running subset of tests'.format(config_file))

    tests_pattern = os.environ.get('OPENCV_PYTEST_FILTER', 'test_*') + '.py'

            

Reported by Pylint.

Line too long (111/100)
Error

Line: 35 Column: 1

                      with open(config_file, 'r') as f:
            locations += [str(s).strip() for s in f.readlines()]
    else:
        print('WARNING: OpenCV tests config file ({}) is missing, running subset of tests'.format(config_file))

    tests_pattern = os.environ.get('OPENCV_PYTEST_FILTER', 'test_*') + '.py'
    if tests_pattern != 'test_*.py':
        print('Tests filter: {}'.format(tests_pattern))


            

Reported by Pylint.

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

Line: 42 Column: 9

                      print('Tests filter: {}'.format(tests_pattern))

    processed = set()
    for l in locations:
        if not os.path.isabs(l):
            l = os.path.normpath(os.path.join(cwd, l))
        if l in processed:
            continue
        processed.add(l)

            

Reported by Pylint.

modules/objdetect/misc/python/test/test_qrcode_detect.py
11 issues
Unable to import 'cv2'
Error

Line: 9 Column: 1

              '''
import os
import numpy as np
import cv2 as cv

from tests_common import NewOpenCVTests

class qrcode_detector_test(NewOpenCVTests):


            

Reported by Pylint.

Unable to import 'tests_common'
Error

Line: 11 Column: 1

              import numpy as np
import cv2 as cv

from tests_common import NewOpenCVTests

class qrcode_detector_test(NewOpenCVTests):

    def test_detect(self):
        img = cv.imread(os.path.join(self.extraTestDataPath, 'cv/qrcode/link_ocv.jpg'))

            

Reported by Pylint.

Unused numpy imported as np
Error

Line: 8 Column: 1

              ===============================================================================
'''
import os
import numpy as np
import cv2 as cv

from tests_common import NewOpenCVTests

class qrcode_detector_test(NewOpenCVTests):

            

Reported by Pylint.

Unused variable 'straight_qrcode'
Error

Line: 27 Column: 25

                      img = cv.imread(os.path.join(self.extraTestDataPath, 'cv/qrcode/link_ocv.jpg'))
        self.assertFalse(img is None)
        detector = cv.QRCodeDetector()
        retval, points, straight_qrcode = detector.detectAndDecode(img)
        self.assertEqual(retval, "https://opencv.org/")
        self.assertEqual(points.shape, (1, 4, 2))

    def test_detect_multi(self):
        img = cv.imread(os.path.join(self.extraTestDataPath, 'cv/qrcode/multiple/6_qrcodes.png'))

            

Reported by Pylint.

Unused variable 'straight_qrcode'
Error

Line: 43 Column: 39

                      img = cv.imread(os.path.join(self.extraTestDataPath, 'cv/qrcode/multiple/6_qrcodes.png'))
        self.assertFalse(img is None)
        detector = cv.QRCodeDetector()
        retval, decoded_data, points, straight_qrcode = detector.detectAndDecodeMulti(img)
        self.assertTrue(retval)
        self.assertEqual(len(decoded_data), 6)
        self.assertEqual(decoded_data[0], "TWO STEPS FORWARD")
        self.assertEqual(decoded_data[1], "EXTRA")
        self.assertEqual(decoded_data[2], "SKIP")

            

Reported by Pylint.

Missing class docstring
Error

Line: 13 Column: 1

              
from tests_common import NewOpenCVTests

class qrcode_detector_test(NewOpenCVTests):

    def test_detect(self):
        img = cv.imread(os.path.join(self.extraTestDataPath, 'cv/qrcode/link_ocv.jpg'))
        self.assertFalse(img is None)
        detector = cv.QRCodeDetector()

            

Reported by Pylint.

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

Line: 13 Column: 1

              
from tests_common import NewOpenCVTests

class qrcode_detector_test(NewOpenCVTests):

    def test_detect(self):
        img = cv.imread(os.path.join(self.extraTestDataPath, 'cv/qrcode/link_ocv.jpg'))
        self.assertFalse(img is None)
        detector = cv.QRCodeDetector()

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 15 Column: 5

              
class qrcode_detector_test(NewOpenCVTests):

    def test_detect(self):
        img = cv.imread(os.path.join(self.extraTestDataPath, 'cv/qrcode/link_ocv.jpg'))
        self.assertFalse(img is None)
        detector = cv.QRCodeDetector()
        retval, points = detector.detect(img)
        self.assertTrue(retval)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 23 Column: 5

                      self.assertTrue(retval)
        self.assertEqual(points.shape, (1, 4, 2))

    def test_detect_and_decode(self):
        img = cv.imread(os.path.join(self.extraTestDataPath, 'cv/qrcode/link_ocv.jpg'))
        self.assertFalse(img is None)
        detector = cv.QRCodeDetector()
        retval, points, straight_qrcode = detector.detectAndDecode(img)
        self.assertEqual(retval, "https://opencv.org/")

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 31 Column: 5

                      self.assertEqual(retval, "https://opencv.org/")
        self.assertEqual(points.shape, (1, 4, 2))

    def test_detect_multi(self):
        img = cv.imread(os.path.join(self.extraTestDataPath, 'cv/qrcode/multiple/6_qrcodes.png'))
        self.assertFalse(img is None)
        detector = cv.QRCodeDetector()
        retval, points = detector.detectMulti(img)
        self.assertTrue(retval)

            

Reported by Pylint.

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

Line: 53

                      }
    };

    public static String getTempFileName(String extension)
    {
        File cache = context.getCacheDir();
        if (!extension.startsWith("."))
            extension = "." + extension;
        try {

            

Reported by PMD.

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

Line: 30

                  public static String LBPCASCADE_FRONTALFACE_PATH;
    public static Context context;

    private AndroidTestRunner androidTestRunner;
    private static String TAG = "opencv_test_java";

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(getContext()) {

        @Override

            

Reported by PMD.

Perhaps 'androidTestRunner' could be replaced by a local variable.
Design

Line: 30

                  public static String LBPCASCADE_FRONTALFACE_PATH;
    public static Context context;

    private AndroidTestRunner androidTestRunner;
    private static String TAG = "opencv_test_java";

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(getContext()) {

        @Override

            

Reported by PMD.

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

Line: 33

                  private AndroidTestRunner androidTestRunner;
    private static String TAG = "opencv_test_java";

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(getContext()) {

        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:

            

Reported by PMD.

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

Line: 33

                  private AndroidTestRunner androidTestRunner;
    private static String TAG = "opencv_test_java";

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(getContext()) {

        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:

            

Reported by PMD.

A switch with less than three branches is inefficient, use a if statement instead.
Performance

Line: 37

              
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                {
                    Log("OpenCV loaded successfully");
                    synchronized (this) {
                        notify();

            

Reported by PMD.

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

Line: 56

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

            

Reported by PMD.

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

Line: 60

                          extension = "." + extension;
        try {
            File tmp = File.createTempFile("OpenCV", extension, cache);
            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: 61

                      try {
            File tmp = File.createTempFile("OpenCV", extension, cache);
            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.

Avoid printStackTrace(); use a logger call instead.
Design

Line: 91

                              try {
                    wait(MANAGER_TIMEOUT);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Log("OpenCV library found inside test package. Using it!");
        }

            

Reported by PMD.

modules/java/generator/android/java/org/opencv/android/FpsMeter.java
11 issues
Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 17

                  private static final int    STEP              = 20;
    private static final DecimalFormat FPS_FORMAT = new DecimalFormat("0.00");

    private int                 mFramesCounter;
    private double              mFrequency;
    private long                mprevFrameTime;
    private String              mStrfps;
    Paint                       mPaint;
    boolean                     mIsInitialized = false;

            

Reported by PMD.

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

Line: 18

                  private static final DecimalFormat FPS_FORMAT = new DecimalFormat("0.00");

    private int                 mFramesCounter;
    private double              mFrequency;
    private long                mprevFrameTime;
    private String              mStrfps;
    Paint                       mPaint;
    boolean                     mIsInitialized = false;
    int                         mWidth = 0;

            

Reported by PMD.

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

Line: 19

              
    private int                 mFramesCounter;
    private double              mFrequency;
    private long                mprevFrameTime;
    private String              mStrfps;
    Paint                       mPaint;
    boolean                     mIsInitialized = false;
    int                         mWidth = 0;
    int                         mHeight = 0;

            

Reported by PMD.

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

Line: 20

                  private int                 mFramesCounter;
    private double              mFrequency;
    private long                mprevFrameTime;
    private String              mStrfps;
    Paint                       mPaint;
    boolean                     mIsInitialized = false;
    int                         mWidth = 0;
    int                         mHeight = 0;


            

Reported by PMD.

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

Line: 21

                  private double              mFrequency;
    private long                mprevFrameTime;
    private String              mStrfps;
    Paint                       mPaint;
    boolean                     mIsInitialized = false;
    int                         mWidth = 0;
    int                         mHeight = 0;

    public void init() {

            

Reported by PMD.

Avoid using redundant field initializer for 'mIsInitialized'
Performance

Line: 22

                  private long                mprevFrameTime;
    private String              mStrfps;
    Paint                       mPaint;
    boolean                     mIsInitialized = false;
    int                         mWidth = 0;
    int                         mHeight = 0;

    public void init() {
        mFramesCounter = 0;

            

Reported by PMD.

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

Line: 22

                  private long                mprevFrameTime;
    private String              mStrfps;
    Paint                       mPaint;
    boolean                     mIsInitialized = false;
    int                         mWidth = 0;
    int                         mHeight = 0;

    public void init() {
        mFramesCounter = 0;

            

Reported by PMD.

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

Line: 23

                  private String              mStrfps;
    Paint                       mPaint;
    boolean                     mIsInitialized = false;
    int                         mWidth = 0;
    int                         mHeight = 0;

    public void init() {
        mFramesCounter = 0;
        mFrequency = Core.getTickFrequency();

            

Reported by PMD.

Avoid using redundant field initializer for 'mWidth'
Performance

Line: 23

                  private String              mStrfps;
    Paint                       mPaint;
    boolean                     mIsInitialized = false;
    int                         mWidth = 0;
    int                         mHeight = 0;

    public void init() {
        mFramesCounter = 0;
        mFrequency = Core.getTickFrequency();

            

Reported by PMD.

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

Line: 24

                  Paint                       mPaint;
    boolean                     mIsInitialized = false;
    int                         mWidth = 0;
    int                         mHeight = 0;

    public void init() {
        mFramesCounter = 0;
        mFrequency = Core.getTickFrequency();
        mprevFrameTime = Core.getTickCount();

            

Reported by PMD.

samples/python/gabor_threads.py
11 issues
Unable to import 'cv2'
Error

Line: 21 Column: 1

              from __future__ import print_function

import numpy as np
import cv2 as cv

from multiprocessing.pool import ThreadPool


def build_filters():

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 57 Column: 5

              
    try:
        img_fn = sys.argv[1]
    except:
        img_fn = 'baboon.jpg'

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

            

Reported by Pylint.

Line too long (133/100)
Error

Line: 8 Column: 1

              =========

Sample demonstrates:
- use of multiple Gabor filter convolutions to get Fractalius-like image effect (http://www.redfieldplugins.com/filterFractalius.htm)
- use of python threading to accelerate the computation

Usage
-----
gabor_threads.py [image filename]

            

Reported by Pylint.

standard import "from multiprocessing.pool import ThreadPool" should be placed before "import numpy as np"
Error

Line: 23 Column: 1

              import numpy as np
import cv2 as cv

from multiprocessing.pool import ThreadPool


def build_filters():
    filters = []
    ksize = 31

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 26 Column: 1

              from multiprocessing.pool import ThreadPool


def build_filters():
    filters = []
    ksize = 31
    for theta in np.arange(0, np.pi, np.pi / 16):
        kern = cv.getGaborKernel((ksize, ksize), 4.0, theta, 10.0, 0.5, 0, ktype=cv.CV_32F)
        kern /= 1.5*kern.sum()

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 35 Column: 1

                      filters.append(kern)
    return filters

def process(img, filters):
    accum = np.zeros_like(img)
    for kern in filters:
        fimg = cv.filter2D(img, cv.CV_8UC3, kern)
        np.maximum(accum, fimg, accum)
    return accum

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 42 Column: 1

                      np.maximum(accum, fimg, accum)
    return accum

def process_threaded(img, filters, threadn = 8):
    accum = np.zeros_like(img)
    def f(kern):
        return cv.filter2D(img, cv.CV_8UC3, kern)
    pool = ThreadPool(processes=threadn)
    for fimg in pool.imap_unordered(f, filters):

            

Reported by Pylint.

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

Line: 44 Column: 5

              
def process_threaded(img, filters, threadn = 8):
    accum = np.zeros_like(img)
    def f(kern):
        return cv.filter2D(img, cv.CV_8UC3, kern)
    pool = ThreadPool(processes=threadn)
    for fimg in pool.imap_unordered(f, filters):
        np.maximum(accum, fimg, accum)
    return accum

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 51 Column: 1

                      np.maximum(accum, fimg, accum)
    return accum

def main():
    import sys
    from common import Timer

    try:
        img_fn = sys.argv[1]

            

Reported by Pylint.

Import outside toplevel (sys)
Error

Line: 52 Column: 5

                  return accum

def main():
    import sys
    from common import Timer

    try:
        img_fn = sys.argv[1]
    except:

            

Reported by Pylint.

samples/java/tutorial_code/ImgTrans/LaPlace/LaplaceDemo.java
10 issues
System.out.println is used
Design

Line: 31

              
        // Check if image is loaded fine
        if( src.empty() ) {
            System.out.println("Error opening image");
            System.out.println("Program Arguments: [image_name -- default ../data/lena.jpg] \n");
            System.exit(-1);
        }
        //! [load]


            

Reported by PMD.

System.out.println is used
Design

Line: 32

                      // Check if image is loaded fine
        if( src.empty() ) {
            System.out.println("Error opening image");
            System.out.println("Program Arguments: [image_name -- default ../data/lena.jpg] \n");
            System.exit(-1);
        }
        //! [load]

        //! [reduce_noise]

            

Reported by PMD.

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

Line: 30

                      src = Imgcodecs.imread(imageName, Imgcodecs.IMREAD_COLOR); // Load an image

        // Check if image is loaded fine
        if( src.empty() ) {
            System.out.println("Error opening image");
            System.out.println("Program Arguments: [image_name -- default ../data/lena.jpg] \n");
            System.exit(-1);
        }
        //! [load]

            

Reported by PMD.

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

Line: 33

                      if( src.empty() ) {
            System.out.println("Error opening image");
            System.out.println("Program Arguments: [image_name -- default ../data/lena.jpg] \n");
            System.exit(-1);
        }
        //! [load]

        //! [reduce_noise]
        // Reduce noise by blurring with a Gaussian filter ( kernel size = 3 )

            

Reported by PMD.

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

Line: 63

                      HighGui.waitKey(0);
        //! [display]

        System.exit(0);
    }
}

public class LaplaceDemo {
    public static void main(String[] args) {

            

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

                  }
}

public class LaplaceDemo {
    public static void main(String[] args) {
        // Load the native library.
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        new LaplaceDemoRun().run(args);
    }

            

Reported by PMD.

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

Line: 6

               * @brief Sample code showing how to detect edges using the Laplace operator
 */

import org.opencv.core.*;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

class LaplaceDemoRun {

            

Reported by PMD.

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

Line: 13

              
class LaplaceDemoRun {

    public void run(String[] args) {
        //! [variables]
        // Declare the variables we are going to use
        Mat src, src_gray = new Mat(), dst = new Mat();
        int kernel_size = 3;
        int scale = 1;

            

Reported by PMD.

Use one line for each declaration, it enhances code readability.
Design

Line: 16

                  public void run(String[] args) {
        //! [variables]
        // Declare the variables we are going to use
        Mat src, src_gray = new Mat(), dst = new Mat();
        int kernel_size = 3;
        int scale = 1;
        int delta = 0;
        int ddepth = CvType.CV_16S;
        String window_name = "Laplace Demo";

            

Reported by PMD.

Found 'DD'-anomaly for variable 'src' (lines '16'-'27').
Error

Line: 16

                  public void run(String[] args) {
        //! [variables]
        // Declare the variables we are going to use
        Mat src, src_gray = new Mat(), dst = new Mat();
        int kernel_size = 3;
        int scale = 1;
        int delta = 0;
        int ddepth = CvType.CV_16S;
        String window_name = "Laplace Demo";

            

Reported by PMD.

samples/python/tutorial_code/features2D/feature_homography/SURF_FLANN_matching_homography_Demo.py
10 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 Matching with FLANN tutorial.')
parser.add_argument('--input1', help='Path to input image 1.', default='box.png')
parser.add_argument('--input2', help='Path to input image 2.', default='box_in_scene.png')
args = parser.parse_args()

            

Reported by Pylint.

Module name "SURF_FLANN_matching_homography_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 Matching with FLANN tutorial.')
parser.add_argument('--input1', help='Path to input image 1.', default='box.png')
parser.add_argument('--input2', help='Path to input image 2.', default='box_in_scene.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 Matching with FLANN tutorial.')
parser.add_argument('--input1', help='Path to input image 1.', default='box.png')
parser.add_argument('--input2', help='Path to input image 2.', default='box_in_scene.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 Matching with FLANN tutorial.')
parser.add_argument('--input1', help='Path to input image 1.', default='box.png')
parser.add_argument('--input2', help='Path to input image 2.', default='box_in_scene.png')
args = parser.parse_args()

            

Reported by Pylint.

Consider using sys.exit()
Error

Line: 15 Column: 5

              img_scene = cv.imread(cv.samples.findFile(args.input2), cv.IMREAD_GRAYSCALE)
if img_object is None or img_scene is None:
    print('Could not open or find the images!')
    exit(0)

#-- Step 1: Detect the keypoints using SURF Detector, compute the descriptors
minHessian = 400
detector = cv.xfeatures2d_SURF.create(hessianThreshold=minHessian)
keypoints_obj, descriptors_obj = detector.detectAndCompute(img_object, None)

            

Reported by Pylint.

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

Line: 18 Column: 1

                  exit(0)

#-- Step 1: Detect the keypoints using SURF Detector, compute the descriptors
minHessian = 400
detector = cv.xfeatures2d_SURF.create(hessianThreshold=minHessian)
keypoints_obj, descriptors_obj = detector.detectAndCompute(img_object, None)
keypoints_scene, descriptors_scene = detector.detectAndCompute(img_scene, None)

#-- Step 2: Matching descriptor vectors with a FLANN based matcher

            

Reported by Pylint.

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

Line: 29 Column: 1

              knn_matches = matcher.knnMatch(descriptors_obj, descriptors_scene, 2)

#-- Filter matches using the Lowe's ratio test
ratio_thresh = 0.75
good_matches = []
for m,n in knn_matches:
    if m.distance < ratio_thresh * n.distance:
        good_matches.append(m)


            

Reported by Pylint.

Line too long (129/100)
Error

Line: 36 Column: 1

                      good_matches.append(m)

#-- Draw matches
img_matches = np.empty((max(img_object.shape[0], img_scene.shape[0]), img_object.shape[1]+img_scene.shape[1], 3), dtype=np.uint8)
cv.drawMatches(img_object, keypoints_obj, img_scene, keypoints_scene, good_matches, img_matches, flags=cv.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

#-- Localize the object
obj = np.empty((len(good_matches),2), dtype=np.float32)
scene = np.empty((len(good_matches),2), dtype=np.float32)

            

Reported by Pylint.

Line too long (146/100)
Error

Line: 37 Column: 1

              
#-- Draw matches
img_matches = np.empty((max(img_object.shape[0], img_scene.shape[0]), img_object.shape[1]+img_scene.shape[1], 3), dtype=np.uint8)
cv.drawMatches(img_object, keypoints_obj, img_scene, keypoints_scene, good_matches, img_matches, flags=cv.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

#-- Localize the object
obj = np.empty((len(good_matches),2), dtype=np.float32)
scene = np.empty((len(good_matches),2), dtype=np.float32)
for i in range(len(good_matches)):

            

Reported by Pylint.

Consider using enumerate instead of iterating with range and len
Error

Line: 42 Column: 1

              #-- Localize the object
obj = np.empty((len(good_matches),2), dtype=np.float32)
scene = np.empty((len(good_matches),2), dtype=np.float32)
for i in range(len(good_matches)):
    #-- Get the keypoints from the good matches
    obj[i,0] = keypoints_obj[good_matches[i].queryIdx].pt[0]
    obj[i,1] = keypoints_obj[good_matches[i].queryIdx].pt[1]
    scene[i,0] = keypoints_scene[good_matches[i].trainIdx].pt[0]
    scene[i,1] = keypoints_scene[good_matches[i].trainIdx].pt[1]

            

Reported by Pylint.

samples/dnn/dnn_model_runner/dnn_conversion/paddlepaddle/paddle_resnet50.py
10 issues
Unable to import 'paddle'
Error

Line: 1 Column: 1

              import paddle
import paddlehub as hub
import paddlehub.vision.transforms as T
import cv2 as cv
import numpy as np


def preprocess(image_path):
    ''' preprocess input image file to np.ndarray

            

Reported by Pylint.

Unable to import 'paddlehub'
Error

Line: 2 Column: 1

              import paddle
import paddlehub as hub
import paddlehub.vision.transforms as T
import cv2 as cv
import numpy as np


def preprocess(image_path):
    ''' preprocess input image file to np.ndarray

            

Reported by Pylint.

Unable to import 'paddlehub.vision.transforms'
Error

Line: 3 Column: 1

              import paddle
import paddlehub as hub
import paddlehub.vision.transforms as T
import cv2 as cv
import numpy as np


def preprocess(image_path):
    ''' preprocess input image file to np.ndarray

            

Reported by Pylint.

Unable to import 'cv2'
Error

Line: 4 Column: 1

              import paddle
import paddlehub as hub
import paddlehub.vision.transforms as T
import cv2 as cv
import numpy as np


def preprocess(image_path):
    ''' preprocess input image file to np.ndarray

            

Reported by Pylint.

Assigning result of a function call, where the function has no return
Error

Line: 48 Column: 5

                  save_path = './resnet50'
    image_file = './data/cat.jpg'
    labels = open('./data/labels.txt').read().strip().split('\n')
    model = export_onnx_mobilenetv2(save_path)

    # load mobilenetv2 use cv.dnn
    net = cv.dnn.readNetFromONNX(save_path + '.onnx')
    # read and preprocess image file
    im = preprocess(image_file)

            

Reported by Pylint.

Redefining name 'save_path' from outer scope (line 45)
Error

Line: 27 Column: 29

                  return np.expand_dims(transforms(image_path), axis=0)


def export_onnx_mobilenetv2(save_path):
    ''' export PaddlePaddle model to ONNX format

    Args:
        save_path(str): Path to save exported ONNX model


            

Reported by Pylint.

Redefining name 'model' from outer scope (line 48)
Error

Line: 36 Column: 5

                  Returns:
        None
    '''
    model = hub.Module(name="resnet50_vd_imagenet_ssld")
    input_spec = paddle.static.InputSpec(
            [1, 3, 224, 224], "float32", "image")
    paddle.onnx.export(model, save_path,
                       input_spec=[input_spec],
                       opset_version=10)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import paddle
import paddlehub as hub
import paddlehub.vision.transforms as T
import cv2 as cv
import numpy as np


def preprocess(image_path):
    ''' preprocess input image file to np.ndarray

            

Reported by Pylint.

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

Line: 45 Column: 5

              

if __name__ == '__main__':
    save_path = './resnet50'
    image_file = './data/cat.jpg'
    labels = open('./data/labels.txt').read().strip().split('\n')
    model = export_onnx_mobilenetv2(save_path)

    # load mobilenetv2 use cv.dnn

            

Reported by Pylint.

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

Line: 46 Column: 5

              
if __name__ == '__main__':
    save_path = './resnet50'
    image_file = './data/cat.jpg'
    labels = open('./data/labels.txt').read().strip().split('\n')
    model = export_onnx_mobilenetv2(save_path)

    # load mobilenetv2 use cv.dnn
    net = cv.dnn.readNetFromONNX(save_path + '.onnx')

            

Reported by Pylint.

samples/dnn/dnn_model_runner/dnn_conversion/common/test/cls_model_test_pipeline.py
10 issues
Attempted relative import beyond top-level package
Error

Line: 1 Column: 1

              from .configs.test_config import TestClsConfig, TestClsModuleConfig
from .model_test_pipeline import ModelTestPipeline
from ..evaluation.classification.cls_accuracy_evaluator import ClsAccEvaluation
from ..utils import get_test_module


class ClsModelTestPipeline(ModelTestPipeline):
    def __init__(
            self,

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 2 Column: 1

              from .configs.test_config import TestClsConfig, TestClsModuleConfig
from .model_test_pipeline import ModelTestPipeline
from ..evaluation.classification.cls_accuracy_evaluator import ClsAccEvaluation
from ..utils import get_test_module


class ClsModelTestPipeline(ModelTestPipeline):
    def __init__(
            self,

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 3 Column: 1

              from .configs.test_config import TestClsConfig, TestClsModuleConfig
from .model_test_pipeline import ModelTestPipeline
from ..evaluation.classification.cls_accuracy_evaluator import ClsAccEvaluation
from ..utils import get_test_module


class ClsModelTestPipeline(ModelTestPipeline):
    def __init__(
            self,

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 4 Column: 1

              from .configs.test_config import TestClsConfig, TestClsModuleConfig
from .model_test_pipeline import ModelTestPipeline
from ..evaluation.classification.cls_accuracy_evaluator import ClsAccEvaluation
from ..utils import get_test_module


class ClsModelTestPipeline(ModelTestPipeline):
    def __init__(
            self,

            

Reported by Pylint.

Attribute '_accuracy_evaluator' defined outside __init__
Error

Line: 56 Column: 9

                          ))

    def _configure_acc_eval(self, log_path):
        self._accuracy_evaluator = ClsAccEvaluation(
            log_path,
            self.test_config.img_cls_file,
            self.test_config.batch_size
        )

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from .configs.test_config import TestClsConfig, TestClsModuleConfig
from .model_test_pipeline import ModelTestPipeline
from ..evaluation.classification.cls_accuracy_evaluator import ClsAccEvaluation
from ..utils import get_test_module


class ClsModelTestPipeline(ModelTestPipeline):
    def __init__(
            self,

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 7 Column: 1

              from ..utils import get_test_module


class ClsModelTestPipeline(ModelTestPipeline):
    def __init__(
            self,
            network_model,
            model_processor,
            dnn_model_processor,

            

Reported by Pylint.

Missing class docstring
Error

Line: 7 Column: 1

              from ..utils import get_test_module


class ClsModelTestPipeline(ModelTestPipeline):
    def __init__(
            self,
            network_model,
            model_processor,
            dnn_model_processor,

            

Reported by Pylint.

Too many arguments (8/5)
Error

Line: 8 Column: 5

              

class ClsModelTestPipeline(ModelTestPipeline):
    def __init__(
            self,
            network_model,
            model_processor,
            dnn_model_processor,
            data_fetcher,

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 18 Column: 9

                          cls_args_parser=None,
            default_input_blob_preproc=None
    ):
        super(ClsModelTestPipeline, self).__init__(
            network_model,
            model_processor,
            dnn_model_processor
        )


            

Reported by Pylint.

samples/android/tutorial-1-camerapreview/src/org/opencv/samples/tutorial1/Tutorial1Activity.java
10 issues
Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 24

              public class Tutorial1Activity extends CameraActivity implements CvCameraViewListener2 {
    private static final String TAG = "OCVSample::Activity";

    private CameraBridgeViewBase mOpenCvCameraView;
    private boolean              mIsJavaCamera = true;
    private MenuItem             mItemSwitchCamera = null;

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override

            

Reported by PMD.

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

Line: 25

                  private static final String TAG = "OCVSample::Activity";

    private CameraBridgeViewBase mOpenCvCameraView;
    private boolean              mIsJavaCamera = true;
    private MenuItem             mItemSwitchCamera = null;

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {

            

Reported by PMD.

Avoid unused private fields such as 'mIsJavaCamera'.
Design

Line: 25

                  private static final String TAG = "OCVSample::Activity";

    private CameraBridgeViewBase mOpenCvCameraView;
    private boolean              mIsJavaCamera = true;
    private MenuItem             mItemSwitchCamera = null;

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {

            

Reported by PMD.

Avoid using redundant field initializer for 'mItemSwitchCamera'
Performance

Line: 26

              
    private CameraBridgeViewBase mOpenCvCameraView;
    private boolean              mIsJavaCamera = true;
    private MenuItem             mItemSwitchCamera = null;

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {

            

Reported by PMD.

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

Line: 26

              
    private CameraBridgeViewBase mOpenCvCameraView;
    private boolean              mIsJavaCamera = true;
    private MenuItem             mItemSwitchCamera = null;

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {

            

Reported by PMD.

Avoid unused private fields such as 'mItemSwitchCamera'.
Design

Line: 26

              
    private CameraBridgeViewBase mOpenCvCameraView;
    private boolean              mIsJavaCamera = true;
    private MenuItem             mItemSwitchCamera = null;

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {

            

Reported by PMD.

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

Line: 28

                  private boolean              mIsJavaCamera = true;
    private MenuItem             mItemSwitchCamera = null;

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                {

            

Reported by PMD.

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

Line: 28

                  private boolean              mIsJavaCamera = true;
    private MenuItem             mItemSwitchCamera = null;

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                {

            

Reported by PMD.

A switch with less than three branches is inefficient, use a if statement instead.
Performance

Line: 31

                  private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                {
                    Log.i(TAG, "OpenCV loaded successfully");
                    mOpenCvCameraView.enableView();
                } break;

            

Reported by PMD.

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

Line: 54

                  public void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "called onCreate");
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.tutorial1_surface_view);

        mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.tutorial1_activity_java_surface_view);


            

Reported by PMD.