The following issues were found

modules/features2d/misc/java/test/BruteForceL1DescriptorMatcherTest.java
44 issues
This class has too many methods, consider refactoring it.
Design

Line: 20

              import org.opencv.imgproc.Imgproc;
import org.opencv.features2d.Feature2D;

public class BruteForceL1DescriptorMatcherTest extends OpenCVTestCase {

    DescriptorMatcher matcher;
    int matSize;
    DMatch[] truth;


            

Reported by PMD.

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

Line: 22

              
public class BruteForceL1DescriptorMatcherTest extends OpenCVTestCase {

    DescriptorMatcher matcher;
    int matSize;
    DMatch[] truth;

    private Mat getMaskImg() {
        return new Mat(5, 2, CvType.CV_8U, new Scalar(0)) {

            

Reported by PMD.

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

Line: 23

              public class BruteForceL1DescriptorMatcherTest extends OpenCVTestCase {

    DescriptorMatcher matcher;
    int matSize;
    DMatch[] truth;

    private Mat getMaskImg() {
        return new Mat(5, 2, CvType.CV_8U, new Scalar(0)) {
            {

            

Reported by PMD.

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

Line: 24

              
    DescriptorMatcher matcher;
    int matSize;
    DMatch[] truth;

    private Mat getMaskImg() {
        return new Mat(5, 2, CvType.CV_8U, new Scalar(0)) {
            {
                put(0, 0, 1, 1, 1, 1);

            

Reported by PMD.

Double-brace initialization should be avoided
Design

Line: 28

              
    private Mat getMaskImg() {
        return new Mat(5, 2, CvType.CV_8U, new Scalar(0)) {
            {
                put(0, 0, 1, 1, 1, 1);
            }
        };
    }


            

Reported by PMD.

A method/constructor should not explicitly throw java.lang.Exception
Design

Line: 82

                      return cross;
    }

    protected void setUp() throws Exception {
        super.setUp();
        matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_L1);
        matSize = 100;

        truth = new DMatch[] {

            

Reported by PMD.

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

Line: 82

                      return cross;
    }

    protected void setUp() throws Exception {
        super.setUp();
        matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_L1);
        matSize = 100;

        truth = new DMatch[] {

            

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

                              };
    }

    public void testAdd() {
        matcher.add(Arrays.asList(new Mat()));
        assertFalse(matcher.empty());
    }

    public void testClear() {

            

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

                      assertFalse(matcher.empty());
    }

    public void testClear() {
        matcher.add(Arrays.asList(new Mat()));

        matcher.clear();

        assertTrue(matcher.empty());

            

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

                      assertTrue(matcher.empty());
    }

    public void testClone() {
        Mat train = new Mat(1, 1, CvType.CV_8U, new Scalar(123));
        Mat truth = train.clone();
        matcher.add(Arrays.asList(train));

        DescriptorMatcher cloned = matcher.clone();

            

Reported by PMD.

modules/java/generator/android-21/java/org/opencv/android/Camera2Renderer.java
44 issues
Avoid throwing raw exception types.
Design

Line: 125

                          }
            if(mCameraID != null) {
                if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
                    throw new RuntimeException(
                            "Time out waiting to lock camera opening.");
                }
                Log.i(LOGTAG, "Opening camera: " + mCameraID);
                manager.openCamera(mCameraID, mStateCallback, mBackgroundHandler);
            }

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 156

                              mCameraDevice = null;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
        } finally {
            mCameraOpenCloseLock.release();
        }
    }


            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 244

                      } catch (CameraAccessException e) {
            Log.e(LOGTAG, "createCameraPreviewSession");
        } catch (InterruptedException e) {
            throw new RuntimeException(
                    "Interrupted while createCameraPreviewSession", e);
        }
        finally {
            //mCameraOpenCloseLock.release();
        }

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 299

                          createCameraPreviewSession();
        } catch (InterruptedException e) {
            mCameraOpenCloseLock.release();
            throw new RuntimeException("Interrupted while setCameraPreviewSize.", e);
        }
    }
}

            

Reported by PMD.

Avoid reassigning parameters such as 'width'
Design

Line: 275

                  }

    @Override
    protected void setCameraPreviewSize(int width, int height) {
        Log.i(LOGTAG, "setCameraPreviewSize("+width+"x"+height+")");
        if(mMaxCameraWidth  > 0 && mMaxCameraWidth  < width)  width  = mMaxCameraWidth;
        if(mMaxCameraHeight > 0 && mMaxCameraHeight < height) height = mMaxCameraHeight;
        try {
            mCameraOpenCloseLock.acquire();

            

Reported by PMD.

Avoid reassigning parameters such as 'height'
Design

Line: 275

                  }

    @Override
    protected void setCameraPreviewSize(int width, int height) {
        Log.i(LOGTAG, "setCameraPreviewSize("+width+"x"+height+")");
        if(mMaxCameraWidth  > 0 && mMaxCameraWidth  < width)  width  = mMaxCameraWidth;
        if(mMaxCameraHeight > 0 && mMaxCameraHeight < height) height = mMaxCameraHeight;
        try {
            mCameraOpenCloseLock.acquire();

            

Reported by PMD.

The class 'Camera2Renderer' has a Standard Cyclomatic Complexity of 4 (Highest = 11).
Design

Line: 23

              import android.view.Surface;

@TargetApi(21)
public class Camera2Renderer extends CameraGLRendererBase {

    protected final String LOGTAG = "Camera2Renderer";
    private CameraDevice mCameraDevice;
    private CameraCaptureSession mCaptureSession;
    private CaptureRequest.Builder mPreviewRequestBuilder;

            

Reported by PMD.

The class 'Camera2Renderer' has a Modified Cyclomatic Complexity of 4 (Highest = 11).
Design

Line: 23

              import android.view.Surface;

@TargetApi(21)
public class Camera2Renderer extends CameraGLRendererBase {

    protected final String LOGTAG = "Camera2Renderer";
    private CameraDevice mCameraDevice;
    private CameraCaptureSession mCaptureSession;
    private CaptureRequest.Builder mPreviewRequestBuilder;

            

Reported by PMD.

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

Line: 25

              @TargetApi(21)
public class Camera2Renderer extends CameraGLRendererBase {

    protected final String LOGTAG = "Camera2Renderer";
    private CameraDevice mCameraDevice;
    private CameraCaptureSession mCaptureSession;
    private CaptureRequest.Builder mPreviewRequestBuilder;
    private String mCameraID;
    private Size mPreviewSize = new Size(-1, -1);

            

Reported by PMD.

This final field could be made static
Design

Line: 25

              @TargetApi(21)
public class Camera2Renderer extends CameraGLRendererBase {

    protected final String LOGTAG = "Camera2Renderer";
    private CameraDevice mCameraDevice;
    private CameraCaptureSession mCaptureSession;
    private CaptureRequest.Builder mPreviewRequestBuilder;
    private String mCameraID;
    private Size mPreviewSize = new Size(-1, -1);

            

Reported by PMD.

modules/ml/misc/python/test/test_letter_recog.py
43 issues
Unable to import 'cv2'
Error

Line: 27 Column: 1

              from __future__ import print_function

import numpy as np
import cv2 as cv

def load_base(fn):
    a = np.loadtxt(fn, np.float32, delimiter=',', converters={ 0 : lambda ch : ord(ch)-ord('A') })
    samples, responses = a[:,1:], a[:,0]
    return samples, responses

            

Reported by Pylint.

Instance of 'LetterStatModel' has no 'model' member
Error

Line: 39 Column: 9

                  train_ratio = 0.5

    def load(self, fn):
        self.model.load(fn)
    def save(self, fn):
        self.model.save(fn)

    def unroll_samples(self, samples):
        sample_n, var_n = samples.shape

            

Reported by Pylint.

Instance of 'LetterStatModel' has no 'model' member
Error

Line: 41 Column: 9

                  def load(self, fn):
        self.model.load(fn)
    def save(self, fn):
        self.model.save(fn)

    def unroll_samples(self, samples):
        sample_n, var_n = samples.shape
        new_samples = np.zeros((sample_n * self.class_n, var_n+1), np.float32)
        new_samples[:,:-1] = np.repeat(samples, self.class_n, axis=0)

            

Reported by Pylint.

Unable to import 'tests_common'
Error

Line: 142 Column: 1

                      _ret, resp = self.model.predict(samples)
        return resp.argmax(-1)

from tests_common import NewOpenCVTests

class letter_recog_test(NewOpenCVTests):

    def test_letter_recog(self):


            

Reported by Pylint.

Line too long (101/100)
Error

Line: 5 Column: 1

              
'''
The sample demonstrates how to train Random Trees classifier
(or Boosting classifier, or MLP, or Knearest, or Support Vector Machines) using the provided dataset.

We use the sample database letter-recognition.data
from UCI Repository, here is the link:

Newman, D.J. & Hettich, S. & Blake, C.L. & Merz, C.J. (1998).

            

Reported by Pylint.

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

Line: 29 Column: 1

              import numpy as np
import cv2 as cv

def load_base(fn):
    a = np.loadtxt(fn, np.float32, delimiter=',', converters={ 0 : lambda ch : ord(ch)-ord('A') })
    samples, responses = a[:,1:], a[:,0]
    return samples, responses

class LetterStatModel(object):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 29 Column: 1

              import numpy as np
import cv2 as cv

def load_base(fn):
    a = np.loadtxt(fn, np.float32, delimiter=',', converters={ 0 : lambda ch : ord(ch)-ord('A') })
    samples, responses = a[:,1:], a[:,0]
    return samples, responses

class LetterStatModel(object):

            

Reported by Pylint.

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

Line: 30 Column: 5

              import cv2 as cv

def load_base(fn):
    a = np.loadtxt(fn, np.float32, delimiter=',', converters={ 0 : lambda ch : ord(ch)-ord('A') })
    samples, responses = a[:,1:], a[:,0]
    return samples, responses

class LetterStatModel(object):
    class_n = 26

            

Reported by Pylint.

Missing class docstring
Error

Line: 34 Column: 1

                  samples, responses = a[:,1:], a[:,0]
    return samples, responses

class LetterStatModel(object):
    class_n = 26
    train_ratio = 0.5

    def load(self, fn):
        self.model.load(fn)

            

Reported by Pylint.

Class 'LetterStatModel' inherits from object, can be safely removed from bases in python3
Error

Line: 34 Column: 1

                  samples, responses = a[:,1:], a[:,0]
    return samples, responses

class LetterStatModel(object):
    class_n = 26
    train_ratio = 0.5

    def load(self, fn):
        self.model.load(fn)

            

Reported by Pylint.

samples/java/tutorial_code/TrackingMotion/generic_corner_detector/CornerDetectorDemo.java
43 issues
System.err.println is used
Design

Line: 49

                      String filename = args.length > 0 ? args[0] : "../data/building.jpg";
        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.

Too many fields
Design

Line: 25

              import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

class CornerDetector {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private Mat harrisDst = new Mat();
    private Mat shiTomasiDst = new Mat();
    private Mat harrisCopy = new Mat();

            

Reported by PMD.

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

Line: 26

              import org.opencv.imgproc.Imgproc;

class CornerDetector {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private Mat harrisDst = new Mat();
    private Mat shiTomasiDst = new Mat();
    private Mat harrisCopy = new Mat();
    private Mat shiTomasiCopy = new Mat();

            

Reported by PMD.

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

Line: 26

              import org.opencv.imgproc.Imgproc;

class CornerDetector {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private Mat harrisDst = new Mat();
    private Mat shiTomasiDst = new Mat();
    private Mat harrisCopy = new Mat();
    private Mat shiTomasiCopy = new Mat();

            

Reported by PMD.

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

Line: 26

              import org.opencv.imgproc.Imgproc;

class CornerDetector {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private Mat harrisDst = new Mat();
    private Mat shiTomasiDst = new Mat();
    private Mat harrisCopy = new Mat();
    private Mat shiTomasiCopy = new Mat();

            

Reported by PMD.

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

Line: 27

              
class CornerDetector {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private Mat harrisDst = new Mat();
    private Mat shiTomasiDst = new Mat();
    private Mat harrisCopy = new Mat();
    private Mat shiTomasiCopy = new Mat();
    private Mat Mc = new Mat();

            

Reported by PMD.

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

Line: 27

              
class CornerDetector {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private Mat harrisDst = new Mat();
    private Mat shiTomasiDst = new Mat();
    private Mat harrisCopy = new Mat();
    private Mat shiTomasiCopy = new Mat();
    private Mat Mc = new Mat();

            

Reported by PMD.

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

Line: 28

              class CornerDetector {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private Mat harrisDst = new Mat();
    private Mat shiTomasiDst = new Mat();
    private Mat harrisCopy = new Mat();
    private Mat shiTomasiCopy = new Mat();
    private Mat Mc = new Mat();
    private JFrame frame;

            

Reported by PMD.

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

Line: 28

              class CornerDetector {
    private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private Mat harrisDst = new Mat();
    private Mat shiTomasiDst = new Mat();
    private Mat harrisCopy = new Mat();
    private Mat shiTomasiCopy = new Mat();
    private Mat Mc = new Mat();
    private JFrame frame;

            

Reported by PMD.

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

Line: 29

                  private Mat src = new Mat();
    private Mat srcGray = new Mat();
    private Mat harrisDst = new Mat();
    private Mat shiTomasiDst = new Mat();
    private Mat harrisCopy = new Mat();
    private Mat shiTomasiCopy = new Mat();
    private Mat Mc = new Mat();
    private JFrame frame;
    private JLabel harrisImgLabel;

            

Reported by PMD.

modules/video/misc/python/test/test_lk_track.py
42 issues
Unable to import 'cv2'
Error

Line: 16 Column: 1

              from __future__ import print_function

import numpy as np
import cv2 as cv

#local modules
from tst_scene_render import TestSceneRender
from tests_common import NewOpenCVTests, intersectionRate, isPointInRect


            

Reported by Pylint.

Unable to import 'tst_scene_render'
Error

Line: 19 Column: 1

              import cv2 as cv

#local modules
from tst_scene_render import TestSceneRender
from tests_common import NewOpenCVTests, intersectionRate, isPointInRect

lk_params = dict( winSize  = (15, 15),
                  maxLevel = 2,
                  criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 0.03))

            

Reported by Pylint.

Unable to import 'tests_common'
Error

Line: 20 Column: 1

              
#local modules
from tst_scene_render import TestSceneRender
from tests_common import NewOpenCVTests, intersectionRate, isPointInRect

lk_params = dict( winSize  = (15, 15),
                  maxLevel = 2,
                  criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 0.03))


            

Reported by Pylint.

Access to member 'prev_gray' before its definition line 108
Error

Line: 64 Column: 30

                          frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

            if len(self.tracks) > 0:
                img0, img1 = self.prev_gray, frame_gray
                p0 = np.float32([tr[-1][0] for tr in self.tracks]).reshape(-1, 1, 2)
                p1, _st, _err = cv.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)
                p0r, _st, _err = cv.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)
                d = abs(p0-p0r).reshape(-1, 2).max(-1)
                good = d < 1

            

Reported by Pylint.

Too many positional arguments for method call
Error

Line: 65 Column: 22

              
            if len(self.tracks) > 0:
                img0, img1 = self.prev_gray, frame_gray
                p0 = np.float32([tr[-1][0] for tr in self.tracks]).reshape(-1, 1, 2)
                p1, _st, _err = cv.calcOpticalFlowPyrLK(img0, img1, p0, None, **lk_params)
                p0r, _st, _err = cv.calcOpticalFlowPyrLK(img1, img0, p1, None, **lk_params)
                d = abs(p0-p0r).reshape(-1, 2).max(-1)
                good = d < 1
                new_tracks = []

            

Reported by Pylint.

Too many positional arguments for method call
Error

Line: 104 Column: 33

                                  cv.circle(mask, (x, y), 5, 0, -1)
                p = cv.goodFeaturesToTrack(frame_gray, mask = mask, **feature_params)
                if p is not None:
                    for x, y in np.float32(p).reshape(-1, 2):
                        self.tracks.append([[(x, y), self.frame_idx]])

            self.frame_idx += 1
            self.prev_gray = frame_gray


            

Reported by Pylint.

Unused intersectionRate imported from tests_common
Error

Line: 20 Column: 1

              
#local modules
from tst_scene_render import TestSceneRender
from tests_common import NewOpenCVTests, intersectionRate, isPointInRect

lk_params = dict( winSize  = (15, 15),
                  maxLevel = 2,
                  criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 0.03))


            

Reported by Pylint.

Attribute 'prev_gray' defined outside __init__
Error

Line: 108 Column: 13

                                      self.tracks.append([[(x, y), self.frame_idx]])

            self.frame_idx += 1
            self.prev_gray = frame_gray

            if self.frame_idx > 300:
                break



            

Reported by Pylint.

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

Line: 31 Column: 1

                                     minDistance = 7,
                       blockSize = 7 )

def getRectFromPoints(points):

    distances = []
    for point in points:
        distances.append(cv.norm(point, cv.NORM_L2))


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 31 Column: 1

                                     minDistance = 7,
                       blockSize = 7 )

def getRectFromPoints(points):

    distances = []
    for point in points:
        distances.append(cv.norm(point, cv.NORM_L2))


            

Reported by Pylint.

modules/ts/misc/report.py
42 issues
Unused import xml
Error

Line: 3 Column: 1

              #!/usr/bin/env python

import testlog_parser, sys, os, xml, re, glob
from table_formatter import *
from optparse import OptionParser

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-o", "--output", dest="format", help="output results in text format (can be 'txt', 'html' or 'auto' - default)", metavar="FMT", default="auto")

            

Reported by Pylint.

Wildcard import table_formatter
Error

Line: 4 Column: 1

              #!/usr/bin/env python

import testlog_parser, sys, os, xml, re, glob
from table_formatter import *
from optparse import OptionParser

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-o", "--output", dest="format", help="output results in text format (can be 'txt', 'html' or 'auto' - default)", metavar="FMT", default="auto")

            

Reported by Pylint.

Unused import tblRow from wildcard import
Error

Line: 4 Column: 1

              #!/usr/bin/env python

import testlog_parser, sys, os, xml, re, glob
from table_formatter import *
from optparse import OptionParser

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-o", "--output", dest="format", help="output results in text format (can be 'txt', 'html' or 'auto' - default)", metavar="FMT", default="auto")

            

Reported by Pylint.

Unused import getCycleReduction from wildcard import
Error

Line: 4 Column: 1

              #!/usr/bin/env python

import testlog_parser, sys, os, xml, re, glob
from table_formatter import *
from optparse import OptionParser

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-o", "--output", dest="format", help="output results in text format (can be 'txt', 'html' or 'auto' - default)", metavar="FMT", default="auto")

            

Reported by Pylint.

Unused import getRelativeVal from wildcard import
Error

Line: 4 Column: 1

              #!/usr/bin/env python

import testlog_parser, sys, os, xml, re, glob
from table_formatter import *
from optparse import OptionParser

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-o", "--output", dest="format", help="output results in text format (can be 'txt', 'html' or 'auto' - default)", metavar="FMT", default="auto")

            

Reported by Pylint.

Unused import dummyColorizer from wildcard import
Error

Line: 4 Column: 1

              #!/usr/bin/env python

import testlog_parser, sys, os, xml, re, glob
from table_formatter import *
from optparse import OptionParser

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-o", "--output", dest="format", help="output results in text format (can be 'txt', 'html' or 'auto' - default)", metavar="FMT", default="auto")

            

Reported by Pylint.

Unused import getColorizer from wildcard import
Error

Line: 4 Column: 1

              #!/usr/bin/env python

import testlog_parser, sys, os, xml, re, glob
from table_formatter import *
from optparse import OptionParser

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-o", "--output", dest="format", help="output results in text format (can be 'txt', 'html' or 'auto' - default)", metavar="FMT", default="auto")

            

Reported by Pylint.

Unused import escape from wildcard import
Error

Line: 4 Column: 1

              #!/usr/bin/env python

import testlog_parser, sys, os, xml, re, glob
from table_formatter import *
from optparse import OptionParser

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-o", "--output", dest="format", help="output results in text format (can be 'txt', 'html' or 'auto' - default)", metavar="FMT", default="auto")

            

Reported by Pylint.

Unused import getStdoutFilename from wildcard import
Error

Line: 4 Column: 1

              #!/usr/bin/env python

import testlog_parser, sys, os, xml, re, glob
from table_formatter import *
from optparse import OptionParser

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-o", "--output", dest="format", help="output results in text format (can be 'txt', 'html' or 'auto' - default)", metavar="FMT", default="auto")

            

Reported by Pylint.

Unused import t from wildcard import
Error

Line: 4 Column: 1

              #!/usr/bin/env python

import testlog_parser, sys, os, xml, re, glob
from table_formatter import *
from optparse import OptionParser

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-o", "--output", dest="format", help="output results in text format (can be 'txt', 'html' or 'auto' - default)", metavar="FMT", default="auto")

            

Reported by Pylint.

samples/python/grabcut.py
41 issues
Unable to import 'cv2'
Error

Line: 34 Column: 1

              from __future__ import print_function

import numpy as np
import cv2 as cv

import sys

class App():
    BLUE = [255,0,0]        # rectangle color

            

Reported by Pylint.

Unused argument 'param'
Error

Line: 59 Column: 43

                  value = DRAW_FG         # drawing initialized to FG
    thickness = 3           # brush thickness

    def onmouse(self, event, x, y, flags, param):
        # Draw Rectangle
        if event == cv.EVENT_RBUTTONDOWN:
            self.rectangle = True
            self.ix, self.iy = x,y


            

Reported by Pylint.

Unused argument 'flags'
Error

Line: 59 Column: 36

                  value = DRAW_FG         # drawing initialized to FG
    thickness = 3           # brush thickness

    def onmouse(self, event, x, y, flags, param):
        # Draw Rectangle
        if event == cv.EVENT_RBUTTONDOWN:
            self.rectangle = True
            self.ix, self.iy = x,y


            

Reported by Pylint.

Attribute 'ix' defined outside __init__
Error

Line: 63 Column: 13

                      # Draw Rectangle
        if event == cv.EVENT_RBUTTONDOWN:
            self.rectangle = True
            self.ix, self.iy = x,y

        elif event == cv.EVENT_MOUSEMOVE:
            if self.rectangle == True:
                self.img = self.img2.copy()
                cv.rectangle(self.img, (self.ix, self.iy), (x, y), self.BLUE, 2)

            

Reported by Pylint.

Attribute 'iy' defined outside __init__
Error

Line: 63 Column: 22

                      # Draw Rectangle
        if event == cv.EVENT_RBUTTONDOWN:
            self.rectangle = True
            self.ix, self.iy = x,y

        elif event == cv.EVENT_MOUSEMOVE:
            if self.rectangle == True:
                self.img = self.img2.copy()
                cv.rectangle(self.img, (self.ix, self.iy), (x, y), self.BLUE, 2)

            

Reported by Pylint.

Attribute 'img' defined outside __init__
Error

Line: 67 Column: 17

              
        elif event == cv.EVENT_MOUSEMOVE:
            if self.rectangle == True:
                self.img = self.img2.copy()
                cv.rectangle(self.img, (self.ix, self.iy), (x, y), self.BLUE, 2)
                self.rect = (min(self.ix, x), min(self.iy, y), abs(self.ix - x), abs(self.iy - y))
                self.rect_or_mask = 0

        elif event == cv.EVENT_RBUTTONUP:

            

Reported by Pylint.

Attribute 'img' defined outside __init__
Error

Line: 110 Column: 9

                          print("Correct Usage: python grabcut.py <filename> \n")
            filename = 'lena.jpg'

        self.img = cv.imread(cv.samples.findFile(filename))
        self.img2 = self.img.copy()                               # a copy of original image
        self.mask = np.zeros(self.img.shape[:2], dtype = np.uint8) # mask initialized to PR_BG
        self.output = np.zeros(self.img.shape, np.uint8)           # output image to be shown

        # input and output windows

            

Reported by Pylint.

Attribute 'img2' defined outside __init__
Error

Line: 111 Column: 9

                          filename = 'lena.jpg'

        self.img = cv.imread(cv.samples.findFile(filename))
        self.img2 = self.img.copy()                               # a copy of original image
        self.mask = np.zeros(self.img.shape[:2], dtype = np.uint8) # mask initialized to PR_BG
        self.output = np.zeros(self.img.shape, np.uint8)           # output image to be shown

        # input and output windows
        cv.namedWindow('output')

            

Reported by Pylint.

Attribute 'mask' defined outside __init__
Error

Line: 112 Column: 9

              
        self.img = cv.imread(cv.samples.findFile(filename))
        self.img2 = self.img.copy()                               # a copy of original image
        self.mask = np.zeros(self.img.shape[:2], dtype = np.uint8) # mask initialized to PR_BG
        self.output = np.zeros(self.img.shape, np.uint8)           # output image to be shown

        # input and output windows
        cv.namedWindow('output')
        cv.namedWindow('input')

            

Reported by Pylint.

Attribute 'output' defined outside __init__
Error

Line: 113 Column: 9

                      self.img = cv.imread(cv.samples.findFile(filename))
        self.img2 = self.img.copy()                               # a copy of original image
        self.mask = np.zeros(self.img.shape[:2], dtype = np.uint8) # mask initialized to PR_BG
        self.output = np.zeros(self.img.shape, np.uint8)           # output image to be shown

        # input and output windows
        cv.namedWindow('output')
        cv.namedWindow('input')
        cv.setMouseCallback('input', self.onmouse)

            

Reported by Pylint.

modules/calib3d/misc/python/test/test_solvepnp.py
41 issues
Unable to import 'cv2'
Error

Line: 6 Column: 1

              from __future__ import print_function

import numpy as np
import cv2 as cv

from tests_common import NewOpenCVTests

class solvepnp_test(NewOpenCVTests):


            

Reported by Pylint.

Unable to import 'tests_common'
Error

Line: 8 Column: 1

              import numpy as np
import cv2 as cv

from tests_common import NewOpenCVTests

class solvepnp_test(NewOpenCVTests):

    def test_regression_16040(self):
        obj_points = np.array([[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]], dtype=np.float32)

            

Reported by Pylint.

Unused variable 'e'
Error

Line: 23 Column: 18

                      )
        distCoeffs = np.array([[0, 0, 0, 0]], dtype=np.float32)
        r = np.array([], dtype=np.float32)
        x, r, t, e = cv.solvePnPGeneric(
            obj_points, img_points, cameraMatrix, distCoeffs, reprojectionError=r
        )

    def test_regression_16040_2(self):
        obj_points = np.array([[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]], dtype=np.float32)

            

Reported by Pylint.

Unused variable 't'
Error

Line: 23 Column: 15

                      )
        distCoeffs = np.array([[0, 0, 0, 0]], dtype=np.float32)
        r = np.array([], dtype=np.float32)
        x, r, t, e = cv.solvePnPGeneric(
            obj_points, img_points, cameraMatrix, distCoeffs, reprojectionError=r
        )

    def test_regression_16040_2(self):
        obj_points = np.array([[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]], dtype=np.float32)

            

Reported by Pylint.

Unused variable 'x'
Error

Line: 23 Column: 9

                      )
        distCoeffs = np.array([[0, 0, 0, 0]], dtype=np.float32)
        r = np.array([], dtype=np.float32)
        x, r, t, e = cv.solvePnPGeneric(
            obj_points, img_points, cameraMatrix, distCoeffs, reprojectionError=r
        )

    def test_regression_16040_2(self):
        obj_points = np.array([[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]], dtype=np.float32)

            

Reported by Pylint.

Unused variable 'x'
Error

Line: 38 Column: 9

                      )
        distCoeffs = np.array([[0, 0, 0, 0]], dtype=np.float32)
        r = np.array([], dtype=np.float32)
        x, r, t, e = cv.solvePnPGeneric(
            obj_points, img_points, cameraMatrix, distCoeffs, reprojectionError=r
        )

    def test_regression_16049(self):
        obj_points = np.array([[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]], dtype=np.float32)

            

Reported by Pylint.

Unused variable 't'
Error

Line: 38 Column: 15

                      )
        distCoeffs = np.array([[0, 0, 0, 0]], dtype=np.float32)
        r = np.array([], dtype=np.float32)
        x, r, t, e = cv.solvePnPGeneric(
            obj_points, img_points, cameraMatrix, distCoeffs, reprojectionError=r
        )

    def test_regression_16049(self):
        obj_points = np.array([[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]], dtype=np.float32)

            

Reported by Pylint.

Unused variable 'e'
Error

Line: 38 Column: 18

                      )
        distCoeffs = np.array([[0, 0, 0, 0]], dtype=np.float32)
        r = np.array([], dtype=np.float32)
        x, r, t, e = cv.solvePnPGeneric(
            obj_points, img_points, cameraMatrix, distCoeffs, reprojectionError=r
        )

    def test_regression_16049(self):
        obj_points = np.array([[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]], dtype=np.float32)

            

Reported by Pylint.

Unused variable 'x'
Error

Line: 52 Column: 9

                          [[712.0634, 0, 800], [0, 712.540, 500], [0, 0, 1]], dtype=np.float32
        )
        distCoeffs = np.array([[0, 0, 0, 0]], dtype=np.float32)
        x, r, t, e = cv.solvePnPGeneric(
            obj_points, img_points, cameraMatrix, distCoeffs
        )
        if e is None:
            # noArray() is supported, see https://github.com/opencv/opencv/issues/16049
            pass

            

Reported by Pylint.

Unused variable 't'
Error

Line: 52 Column: 15

                          [[712.0634, 0, 800], [0, 712.540, 500], [0, 0, 1]], dtype=np.float32
        )
        distCoeffs = np.array([[0, 0, 0, 0]], dtype=np.float32)
        x, r, t, e = cv.solvePnPGeneric(
            obj_points, img_points, cameraMatrix, distCoeffs
        )
        if e is None:
            # noArray() is supported, see https://github.com/opencv/opencv/issues/16049
            pass

            

Reported by Pylint.

modules/dnn/test/cityscapes_semsegm_test_enet.py
41 issues
Unable to import 'torch.utils.serialization'
Error

Line: 17 Column: 1

              except ImportError:
    raise ImportError('Can\'t find pytorch. Please install it by following instructions on the official site')

from torch.utils.serialization import load_lua
from pascal_semsegm_test_fcn import eval_segm_result, get_conf_mat, get_metrics, DatasetImageFetch, SemSegmEvaluation
from imagenet_cls_test_alexnet import Framework, DnnCaffeModel


class NormalizePreproc:

            

Reported by Pylint.

__iter__ returns non-iterator
Error

Line: 61 Column: 5

                          result.append(DatasetImageFetch.pix_to_c(c))
        return result

    def __iter__(self):
        return self

    def next(self):
        if self.i < len(self.segm_files):
            segm_file = self.segm_files[self.i]

            

Reported by Pylint.

Unused import sys
Error

Line: 2 Column: 1

              import numpy as np
import sys
import os
import fnmatch
import argparse

try:
    import cv2 as cv
except ImportError:

            

Reported by Pylint.

Consider explicitly re-raising using the 'from' keyword
Error

Line: 10 Column: 5

              try:
    import cv2 as cv
except ImportError:
    raise ImportError('Can\'t find OpenCV Python module. If you\'ve built it from sources without installation, '
                      'configure environment variable PYTHONPATH to "opencv_build_dir/lib" directory (with "python3" subdirectory if required)')
try:
    import torch
except ImportError:
    raise ImportError('Can\'t find pytorch. Please install it by following instructions on the official site')

            

Reported by Pylint.

Consider explicitly re-raising using the 'from' keyword
Error

Line: 15 Column: 5

              try:
    import torch
except ImportError:
    raise ImportError('Can\'t find pytorch. Please install it by following instructions on the official site')

from torch.utils.serialization import load_lua
from pascal_semsegm_test_fcn import eval_segm_result, get_conf_mat, get_metrics, DatasetImageFetch, SemSegmEvaluation
from imagenet_cls_test_alexnet import Framework, DnnCaffeModel


            

Reported by Pylint.

Unused get_conf_mat imported from pascal_semsegm_test_fcn
Error

Line: 18 Column: 1

                  raise ImportError('Can\'t find pytorch. Please install it by following instructions on the official site')

from torch.utils.serialization import load_lua
from pascal_semsegm_test_fcn import eval_segm_result, get_conf_mat, get_metrics, DatasetImageFetch, SemSegmEvaluation
from imagenet_cls_test_alexnet import Framework, DnnCaffeModel


class NormalizePreproc:
    def __init__(self):

            

Reported by Pylint.

Unused eval_segm_result imported from pascal_semsegm_test_fcn
Error

Line: 18 Column: 1

                  raise ImportError('Can\'t find pytorch. Please install it by following instructions on the official site')

from torch.utils.serialization import load_lua
from pascal_semsegm_test_fcn import eval_segm_result, get_conf_mat, get_metrics, DatasetImageFetch, SemSegmEvaluation
from imagenet_cls_test_alexnet import Framework, DnnCaffeModel


class NormalizePreproc:
    def __init__(self):

            

Reported by Pylint.

Unused get_metrics imported from pascal_semsegm_test_fcn
Error

Line: 18 Column: 1

                  raise ImportError('Can\'t find pytorch. Please install it by following instructions on the official site')

from torch.utils.serialization import load_lua
from pascal_semsegm_test_fcn import eval_segm_result, get_conf_mat, get_metrics, DatasetImageFetch, SemSegmEvaluation
from imagenet_cls_test_alexnet import Framework, DnnCaffeModel


class NormalizePreproc:
    def __init__(self):

            

Reported by Pylint.

Unused variable 'dirs'
Error

Line: 88 Column: 19

              
    @staticmethod
    def locate(pattern, root_path):
        for path, dirs, files in os.walk(os.path.abspath(root_path)):
            for filename in fnmatch.filter(files, pattern):
                yield os.path.join(path, filename)

    @staticmethod
    def rreplace(s, old, new, occurrence=1):

            

Reported by Pylint.

__init__ method from base class 'DnnCaffeModel' is not called
Error

Line: 116 Column: 5

              class DnnTorchModel(DnnCaffeModel):
    net = cv.dnn.Net()

    def __init__(self, model_file):
        self.net = cv.dnn.readNetFromTorch(model_file)

    def get_output(self, input_blob):
        self.net.setBlob("", input_blob)
        self.net.forward()

            

Reported by Pylint.

samples/dnn/mask_rcnn.py
40 issues
Unable to import 'cv2'
Error

Line: 1 Column: 1

              import cv2 as cv
import argparse
import numpy as np

parser = argparse.ArgumentParser(description=
        'Use this script to run Mask-RCNN object detection and semantic '
        'segmentation network from TensorFlow Object Detection API.')
parser.add_argument('--input', help='Path to input image or video file. Skip this argument to capture frames from a camera.')
parser.add_argument('--model', required=True, help='Path to a .pb file with weights.')

            

Reported by Pylint.

Redefining name 'classes' from outer scope (line 24)
Error

Line: 36 Column: 16

                      colors = [np.array(color.split(' '), np.uint8) for color in f.read().rstrip('\n').split('\n')]

legend = None
def showLegend(classes):
    global legend
    if not classes is None and legend is None:
        blockHeight = 30
        assert(len(classes) == len(colors))


            

Reported by Pylint.

Using the global statement
Error

Line: 37 Column: 5

              
legend = None
def showLegend(classes):
    global legend
    if not classes is None and legend is None:
        blockHeight = 30
        assert(len(classes) == len(colors))

        legend = np.zeros((blockHeight * len(colors), 200, 3), np.uint8)

            

Reported by Pylint.

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

Line: 43 Column: 13

                      assert(len(classes) == len(colors))

        legend = np.zeros((blockHeight * len(colors), 200, 3), np.uint8)
        for i in range(len(classes)):
            block = legend[i * blockHeight:(i + 1) * blockHeight]
            block[:,:] = colors[i]
            cv.putText(block, classes[i], (0, blockHeight//2), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))

        cv.namedWindow('Legend', cv.WINDOW_NORMAL)

            

Reported by Pylint.

Redefining name 'right' from outer scope (line 116)
Error

Line: 53 Column: 46

                      classes = None


def drawBox(frame, classId, conf, left, top, right, bottom):
    # Draw a bounding box.
    cv.rectangle(frame, (left, top), (right, bottom), (0, 255, 0))

    label = '%.2f' % conf


            

Reported by Pylint.

Redefining name 'top' from outer scope (line 115)
Error

Line: 53 Column: 41

                      classes = None


def drawBox(frame, classId, conf, left, top, right, bottom):
    # Draw a bounding box.
    cv.rectangle(frame, (left, top), (right, bottom), (0, 255, 0))

    label = '%.2f' % conf


            

Reported by Pylint.

Redefining name 'bottom' from outer scope (line 117)
Error

Line: 53 Column: 53

                      classes = None


def drawBox(frame, classId, conf, left, top, right, bottom):
    # Draw a bounding box.
    cv.rectangle(frame, (left, top), (right, bottom), (0, 255, 0))

    label = '%.2f' % conf


            

Reported by Pylint.

Redefining name 'frame' from outer scope (line 80)
Error

Line: 53 Column: 13

                      classes = None


def drawBox(frame, classId, conf, left, top, right, bottom):
    # Draw a bounding box.
    cv.rectangle(frame, (left, top), (right, bottom), (0, 255, 0))

    label = '%.2f' % conf


            

Reported by Pylint.

Redefining name 'classId' from outer scope (line 113)
Error

Line: 53 Column: 20

                      classes = None


def drawBox(frame, classId, conf, left, top, right, bottom):
    # Draw a bounding box.
    cv.rectangle(frame, (left, top), (right, bottom), (0, 255, 0))

    label = '%.2f' % conf


            

Reported by Pylint.

Redefining name 'left' from outer scope (line 114)
Error

Line: 53 Column: 35

                      classes = None


def drawBox(frame, classId, conf, left, top, right, bottom):
    # Draw a bounding box.
    cv.rectangle(frame, (left, top), (right, bottom), (0, 255, 0))

    label = '%.2f' % conf


            

Reported by Pylint.