The following issues were found

samples/dnn/dnn_model_runner/dnn_conversion/pytorch/pytorch_model.py
17 issues
Unable to import 'cv2'
Error

Line: 3 Column: 1

              import os

import cv2
import torch.onnx
from torch.autograd import Variable

from ..common.abstract_model import AbstractModel, Framework
from ..common.utils import DNN_LIB, get_full_model_path


            

Reported by Pylint.

Unable to import 'torch.onnx'
Error

Line: 4 Column: 1

              import os

import cv2
import torch.onnx
from torch.autograd import Variable

from ..common.abstract_model import AbstractModel, Framework
from ..common.utils import DNN_LIB, get_full_model_path


            

Reported by Pylint.

Unable to import 'torch.autograd'
Error

Line: 5 Column: 1

              
import cv2
import torch.onnx
from torch.autograd import Variable

from ..common.abstract_model import AbstractModel, Framework
from ..common.utils import DNN_LIB, get_full_model_path

CURRENT_LIB = "PyTorch"

            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 7 Column: 1

              import torch.onnx
from torch.autograd import Variable

from ..common.abstract_model import AbstractModel, Framework
from ..common.utils import DNN_LIB, get_full_model_path

CURRENT_LIB = "PyTorch"
MODEL_FORMAT = ".onnx"


            

Reported by Pylint.

Attempted relative import beyond top-level package
Error

Line: 8 Column: 1

              from torch.autograd import Variable

from ..common.abstract_model import AbstractModel, Framework
from ..common.utils import DNN_LIB, get_full_model_path

CURRENT_LIB = "PyTorch"
MODEL_FORMAT = ".onnx"



            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import os

import cv2
import torch.onnx
from torch.autograd import Variable

from ..common.abstract_model import AbstractModel, Framework
from ..common.utils import DNN_LIB, get_full_model_path


            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 14 Column: 1

              MODEL_FORMAT = ".onnx"


class PyTorchModelPreparer(AbstractModel):

    def __init__(
            self,
            height,
            width,

            

Reported by Pylint.

Missing class docstring
Error

Line: 14 Column: 1

              MODEL_FORMAT = ".onnx"


class PyTorchModelPreparer(AbstractModel):

    def __init__(
            self,
            height,
            width,

            

Reported by Pylint.

Too many instance attributes (9/7)
Error

Line: 14 Column: 1

              MODEL_FORMAT = ".onnx"


class PyTorchModelPreparer(AbstractModel):

    def __init__(
            self,
            height,
            width,

            

Reported by Pylint.

Too many arguments (8/5)
Error

Line: 16 Column: 5

              
class PyTorchModelPreparer(AbstractModel):

    def __init__(
            self,
            height,
            width,
            model_name="default",
            original_model=object,

            

Reported by Pylint.

samples/java/tutorial_code/ImgTrans/canny_detector/CannyDetectorDemo.java
17 issues
System.out.println is used
Design

Line: 40

                      String imagePath = args.length > 0 ? args[0] : "../data/fruits.jpg";
        src = Imgcodecs.imread(imagePath);
        if (src.empty()) {
            System.out.println("Empty image: " + imagePath);
            System.exit(0);
        }

        // Create and set up the window.
        frame = new JFrame("Edge Map (Canny detector demo)");

            

Reported by PMD.

Avoid using redundant field initializer for 'lowThresh'
Performance

Line: 28

                  private static final int RATIO = 3;
    private static final int KERNEL_SIZE = 3;
    private static final Size BLUR_SIZE = new Size(3,3);
    private int lowThresh = 0;
    private Mat src;
    private Mat srcBlur = new Mat();
    private Mat detectedEdges = new Mat();
    private Mat dst = new Mat();
    private JFrame frame;

            

Reported by PMD.

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

Line: 28

                  private static final int RATIO = 3;
    private static final int KERNEL_SIZE = 3;
    private static final Size BLUR_SIZE = new Size(3,3);
    private int lowThresh = 0;
    private Mat src;
    private Mat srcBlur = new Mat();
    private Mat detectedEdges = new Mat();
    private Mat dst = 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 static final int KERNEL_SIZE = 3;
    private static final Size BLUR_SIZE = new Size(3,3);
    private int lowThresh = 0;
    private Mat src;
    private Mat srcBlur = new Mat();
    private Mat detectedEdges = new Mat();
    private Mat dst = new Mat();
    private JFrame frame;
    private JLabel imgLabel;

            

Reported by PMD.

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

Line: 29

                  private static final int KERNEL_SIZE = 3;
    private static final Size BLUR_SIZE = new Size(3,3);
    private int lowThresh = 0;
    private Mat src;
    private Mat srcBlur = new Mat();
    private Mat detectedEdges = new Mat();
    private Mat dst = new Mat();
    private JFrame frame;
    private JLabel imgLabel;

            

Reported by PMD.

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

Line: 30

                  private static final Size BLUR_SIZE = new Size(3,3);
    private int lowThresh = 0;
    private Mat src;
    private Mat srcBlur = new Mat();
    private Mat detectedEdges = new Mat();
    private Mat dst = new Mat();
    private JFrame frame;
    private JLabel imgLabel;


            

Reported by PMD.

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

Line: 30

                  private static final Size BLUR_SIZE = new Size(3,3);
    private int lowThresh = 0;
    private Mat src;
    private Mat srcBlur = new Mat();
    private Mat detectedEdges = new Mat();
    private Mat dst = new Mat();
    private JFrame frame;
    private JLabel imgLabel;


            

Reported by PMD.

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

Line: 31

                  private int lowThresh = 0;
    private Mat src;
    private Mat srcBlur = new Mat();
    private Mat detectedEdges = new Mat();
    private Mat dst = new Mat();
    private JFrame frame;
    private JLabel imgLabel;

    public CannyDetectorDemo(String[] args) {

            

Reported by PMD.

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

Line: 31

                  private int lowThresh = 0;
    private Mat src;
    private Mat srcBlur = new Mat();
    private Mat detectedEdges = new Mat();
    private Mat dst = new Mat();
    private JFrame frame;
    private JLabel imgLabel;

    public CannyDetectorDemo(String[] args) {

            

Reported by PMD.

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

Line: 32

                  private Mat src;
    private Mat srcBlur = new Mat();
    private Mat detectedEdges = new Mat();
    private Mat dst = new Mat();
    private JFrame frame;
    private JLabel imgLabel;

    public CannyDetectorDemo(String[] args) {
        String imagePath = args.length > 0 ? args[0] : "../data/fruits.jpg";

            

Reported by PMD.

modules/features2d/misc/java/test/ORBDescriptorExtractorTest.java
16 issues
Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 17

              
public class ORBDescriptorExtractorTest extends OpenCVTestCase {

    ORB extractor;
    int matSize;

    public static void assertDescriptorsClose(Mat expected, Mat actual, int allowedDistance) {
        double distance = Core.norm(expected, actual, Core.NORM_HAMMING);
        assertTrue("expected:<" + allowedDistance + "> but was:<" + distance + ">", distance <= allowedDistance);

            

Reported by PMD.

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

Line: 18

              public class ORBDescriptorExtractorTest extends OpenCVTestCase {

    ORB extractor;
    int matSize;

    public static void assertDescriptorsClose(Mat expected, Mat actual, int allowedDistance) {
        double distance = Core.norm(expected, actual, Core.NORM_HAMMING);
        assertTrue("expected:<" + allowedDistance + "> but was:<" + distance + ">", distance <= allowedDistance);
    }

            

Reported by PMD.

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

Line: 33

                      return cross;
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        extractor = ORB.create();
        matSize = 100;
    }

            

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

                      matSize = 100;
    }

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

    public void testComputeMatListOfKeyPointMat() {
        KeyPoint point = new KeyPoint(55.775577545166016f, 44.224422454833984f, 16, 9.754629f, 8617.863f, 1, -1);

            

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

                      fail("Not yet implemented");
    }

    public void testComputeMatListOfKeyPointMat() {
        KeyPoint point = new KeyPoint(55.775577545166016f, 44.224422454833984f, 16, 9.754629f, 8617.863f, 1, -1);
        MatOfKeyPoint keypoints = new MatOfKeyPoint(point);
        Mat img = getTestImg();
        Mat descriptors = new Mat();


            

Reported by PMD.

Double-brace initialization should be avoided
Design

Line: 53

                      extractor.compute(img, keypoints, descriptors);

        Mat truth = new Mat(1, 32, CvType.CV_8UC1) {
            {
                put(0, 0,
                        6, 74, 6, 129, 2, 130, 56, 0, 44, 132, 66, 165, 172, 6, 3, 72, 102, 61, 171, 214, 0, 144, 65, 232, 4, 32, 138, 131, 4, 21, 37, 217);
            }
        };
        assertDescriptorsClose(truth, descriptors, 1);

            

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

                      assertDescriptorsClose(truth, descriptors, 1);
    }

    public void testCreate() {
        assertNotNull(extractor);
    }

    public void testDescriptorSize() {
        assertEquals(32, extractor.descriptorSize());

            

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

                      assertNotNull(extractor);
    }

    public void testDescriptorSize() {
        assertEquals(32, extractor.descriptorSize());
    }

    public void testDescriptorType() {
        assertEquals(CvType.CV_8U, extractor.descriptorType());

            

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

                      assertEquals(32, extractor.descriptorSize());
    }

    public void testDescriptorType() {
        assertEquals(CvType.CV_8U, extractor.descriptorType());
    }

    public void testEmpty() {
//        assertFalse(extractor.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: 73

                      assertEquals(CvType.CV_8U, extractor.descriptorType());
    }

    public void testEmpty() {
//        assertFalse(extractor.empty());
        fail("Not yet implemented"); // ORB does not override empty() method
    }

    public void testRead() {

            

Reported by PMD.

samples/python/tutorial_code/ShapeDescriptors/bounding_rects_circles/generalContours_demo1.py
16 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

rng.seed(12345)

def thresh_callback(val):

            

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

rng.seed(12345)

def thresh_callback(val):

            

Reported by Pylint.

Module name "generalContours_demo1" 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

rng.seed(12345)

def thresh_callback(val):

            

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

rng.seed(12345)

def thresh_callback(val):

            

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

rng.seed(12345)

def thresh_callback(val):
    threshold = val

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 9 Column: 1

              
rng.seed(12345)

def thresh_callback(val):
    threshold = val

    ## [Canny]
    # Detect edges using Canny
    canny_output = cv.Canny(src_gray, threshold, threshold * 2)

            

Reported by Pylint.

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

Line: 25 Column: 5

                  ## [allthework]
    # Approximate contours to polygons + get bounding rects and circles
    contours_poly = [None]*len(contours)
    boundRect = [None]*len(contours)
    centers = [None]*len(contours)
    radius = [None]*len(contours)
    for i, c in enumerate(contours):
        contours_poly[i] = cv.approxPolyDP(c, 3, True)
        boundRect[i] = cv.boundingRect(contours_poly[i])

            

Reported by Pylint.

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

Line: 28 Column: 12

                  boundRect = [None]*len(contours)
    centers = [None]*len(contours)
    radius = [None]*len(contours)
    for i, c in enumerate(contours):
        contours_poly[i] = cv.approxPolyDP(c, 3, True)
        boundRect[i] = cv.boundingRect(contours_poly[i])
        centers[i], radius[i] = cv.minEnclosingCircle(contours_poly[i])
    ## [allthework]


            

Reported by Pylint.

Standard pseudo-random generators are not suitable for security/cryptographic purposes.
Security blacklist

Line: 41
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b311-random

                  ## [forContour]
    # Draw polygonal contour + bonding rects + circles
    for i in range(len(contours)):
        color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256))
        cv.drawContours(drawing, contours_poly, i, color)
        cv.rectangle(drawing, (int(boundRect[i][0]), int(boundRect[i][1])), \
          (int(boundRect[i][0]+boundRect[i][2]), int(boundRect[i][1]+boundRect[i][3])), color, 2)
        cv.circle(drawing, (int(centers[i][0]), int(centers[i][1])), int(radius[i]), color, 2)
    ## [forContour]

            

Reported by Bandit.

Standard pseudo-random generators are not suitable for security/cryptographic purposes.
Security blacklist

Line: 41
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b311-random

                  ## [forContour]
    # Draw polygonal contour + bonding rects + circles
    for i in range(len(contours)):
        color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256))
        cv.drawContours(drawing, contours_poly, i, color)
        cv.rectangle(drawing, (int(boundRect[i][0]), int(boundRect[i][1])), \
          (int(boundRect[i][0]+boundRect[i][2]), int(boundRect[i][1]+boundRect[i][3])), color, 2)
        cv.circle(drawing, (int(centers[i][0]), int(centers[i][1])), int(radius[i]), color, 2)
    ## [forContour]

            

Reported by Bandit.

samples/python/contours.py
16 issues
Unable to import 'cv2'
Error

Line: 21 Column: 1

                  xrange = range

import numpy as np
import cv2 as cv

def make_image():
    img = np.zeros((500, 500), np.uint8)
    black, white = 0, 255
    for i in xrange(6):

            

Reported by Pylint.

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

Line: 18 Column: 5

              PY3 = sys.version_info[0] == 3

if PY3:
    xrange = range

import numpy as np
import cv2 as cv

def make_image():

            

Reported by Pylint.

Import "import numpy as np" should be placed at the top of the module
Error

Line: 20 Column: 1

              if PY3:
    xrange = range

import numpy as np
import cv2 as cv

def make_image():
    img = np.zeros((500, 500), np.uint8)
    black, white = 0, 255

            

Reported by Pylint.

Import "import cv2 as cv" should be placed at the top of the module
Error

Line: 21 Column: 1

                  xrange = range

import numpy as np
import cv2 as cv

def make_image():
    img = np.zeros((500, 500), np.uint8)
    black, white = 0, 255
    for i in xrange(6):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 23 Column: 1

              import numpy as np
import cv2 as cv

def make_image():
    img = np.zeros((500, 500), np.uint8)
    black, white = 0, 255
    for i in xrange(6):
        dx = int((i%2)*250 - 30)
        dy = int((i/2.)*150)

            

Reported by Pylint.

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

Line: 27 Column: 9

                  img = np.zeros((500, 500), np.uint8)
    black, white = 0, 255
    for i in xrange(6):
        dx = int((i%2)*250 - 30)
        dy = int((i/2.)*150)

        if i == 0:
            for j in xrange(11):
                angle = (j+5)*np.pi/21

            

Reported by Pylint.

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

Line: 28 Column: 9

                  black, white = 0, 255
    for i in xrange(6):
        dx = int((i%2)*250 - 30)
        dy = int((i/2.)*150)

        if i == 0:
            for j in xrange(11):
                angle = (j+5)*np.pi/21
                c, s = np.cos(angle), np.sin(angle)

            

Reported by Pylint.

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

Line: 33 Column: 20

                      if i == 0:
            for j in xrange(11):
                angle = (j+5)*np.pi/21
                c, s = np.cos(angle), np.sin(angle)
                x1, y1 = np.int32([dx+100+j*10-80*c, dy+100-90*s])
                x2, y2 = np.int32([dx+100+j*10-30*c, dy+100-30*s])
                cv.line(img, (x1, y1), (x2, y2), white)

        cv.ellipse( img, (dx+150, dy+100), (100,70), 0, 0, 360, white, -1 )

            

Reported by Pylint.

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

Line: 33 Column: 17

                      if i == 0:
            for j in xrange(11):
                angle = (j+5)*np.pi/21
                c, s = np.cos(angle), np.sin(angle)
                x1, y1 = np.int32([dx+100+j*10-80*c, dy+100-90*s])
                x2, y2 = np.int32([dx+100+j*10-30*c, dy+100-30*s])
                cv.line(img, (x1, y1), (x2, y2), white)

        cv.ellipse( img, (dx+150, dy+100), (100,70), 0, 0, 360, white, -1 )

            

Reported by Pylint.

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

Line: 34 Column: 17

                          for j in xrange(11):
                angle = (j+5)*np.pi/21
                c, s = np.cos(angle), np.sin(angle)
                x1, y1 = np.int32([dx+100+j*10-80*c, dy+100-90*s])
                x2, y2 = np.int32([dx+100+j*10-30*c, dy+100-30*s])
                cv.line(img, (x1, y1), (x2, y2), white)

        cv.ellipse( img, (dx+150, dy+100), (100,70), 0, 0, 360, white, -1 )
        cv.ellipse( img, (dx+115, dy+70), (30,20), 0, 0, 360, black, -1 )

            

Reported by Pylint.

modules/core/misc/java/test/TermCriteriaTest.java
16 issues
Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 8

              
public class TermCriteriaTest extends OpenCVTestCase {

    private TermCriteria tc1;
    private TermCriteria tc2;

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

            

Reported by PMD.

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

Line: 9

              public class TermCriteriaTest extends OpenCVTestCase {

    private TermCriteria tc1;
    private TermCriteria tc2;

    @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: 11

                  private TermCriteria tc1;
    private TermCriteria tc2;

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

        tc1 = new TermCriteria();
        tc2 = new TermCriteria(2, 4, EPS);

            

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

                      tc2 = new TermCriteria(2, 4, EPS);
    }

    public void testClone() {
        tc1 = tc2.clone();
        assertEquals(tc2, tc1);
    }

    public void testEqualsObject() {

            

Reported by PMD.

Unit tests should not contain more than 1 assert(s).
Design

Line: 24

                      assertEquals(tc2, tc1);
    }

    public void testEqualsObject() {
        assertFalse(tc2.equals(tc1));

        tc1 = tc2.clone();
        assertTrue(tc2.equals(tc1));
    }

            

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

                      assertEquals(tc2, tc1);
    }

    public void testEqualsObject() {
        assertFalse(tc2.equals(tc1));

        tc1 = tc2.clone();
        assertTrue(tc2.equals(tc1));
    }

            

Reported by PMD.

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

Line: 31

                      assertTrue(tc2.equals(tc1));
    }

    public void testHashCode() {
        assertEquals(tc2.hashCode(), tc2.hashCode());
    }

    public void testSet() {
        double[] vals1 = {};

            

Reported by PMD.

Unit tests should not contain more than 1 assert(s).
Design

Line: 35

                      assertEquals(tc2.hashCode(), tc2.hashCode());
    }

    public void testSet() {
        double[] vals1 = {};
        tc1.set(vals1);

        assertEquals(0, tc1.type);
        assertEquals(0, tc1.maxCount);

            

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

                      assertEquals(tc2.hashCode(), tc2.hashCode());
    }

    public void testSet() {
        double[] vals1 = {};
        tc1.set(vals1);

        assertEquals(0, tc1.type);
        assertEquals(0, tc1.maxCount);

            

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

                      assertEquals(0.002, tc2.epsilon);
    }

    public void testTermCriteria() {
        tc1 = new TermCriteria();

        assertNotNull(tc1);
        assertEquals(0, tc1.type);
        assertEquals(0, tc1.maxCount);

            

Reported by PMD.

samples/java/tutorial_code/ImgTrans/remap/RemapDemo.java
16 issues
System.err.println is used
Design

Line: 62

                      //! [Load]
        Mat src = Imgcodecs.imread(filename, Imgcodecs.IMREAD_COLOR);
        if (src.empty()) {
            System.err.println("Cannot read image: " + filename);
            System.exit(0);
        }
        //! [Load]

        //! [Create]

            

Reported by PMD.

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

Line: 9

              import org.opencv.imgproc.Imgproc;

class Remap {
    private Mat mapX = new Mat();
    private Mat mapY = new Mat();
    private Mat dst = new Mat();
    private int ind = 0;

    //! [Update]

            

Reported by PMD.

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

Line: 10

              
class Remap {
    private Mat mapX = new Mat();
    private Mat mapY = new Mat();
    private Mat dst = new Mat();
    private int ind = 0;

    //! [Update]
    private void updateMap() {

            

Reported by PMD.

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

Line: 11

              class Remap {
    private Mat mapX = new Mat();
    private Mat mapY = new Mat();
    private Mat dst = new Mat();
    private int ind = 0;

    //! [Update]
    private void updateMap() {
        float buffX[] = new float[(int) (mapX.total() * mapX.channels())];

            

Reported by PMD.

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

Line: 11

              class Remap {
    private Mat mapX = new Mat();
    private Mat mapY = new Mat();
    private Mat dst = new Mat();
    private int ind = 0;

    //! [Update]
    private void updateMap() {
        float buffX[] = new float[(int) (mapX.total() * mapX.channels())];

            

Reported by PMD.

Avoid using redundant field initializer for 'ind'
Performance

Line: 12

                  private Mat mapX = new Mat();
    private Mat mapY = new Mat();
    private Mat dst = new Mat();
    private int ind = 0;

    //! [Update]
    private void updateMap() {
        float buffX[] = new float[(int) (mapX.total() * mapX.channels())];
        mapX.get(0, 0, buffX);

            

Reported by PMD.

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

Line: 12

                  private Mat mapX = new Mat();
    private Mat mapY = new Mat();
    private Mat dst = new Mat();
    private int ind = 0;

    //! [Update]
    private void updateMap() {
        float buffX[] = new float[(int) (mapX.total() * mapX.channels())];
        mapX.get(0, 0, buffX);

            

Reported by PMD.

The method 'updateMap()' has a cyclomatic complexity of 11.
Design

Line: 15

                  private int ind = 0;

    //! [Update]
    private void updateMap() {
        float buffX[] = new float[(int) (mapX.total() * mapX.channels())];
        mapX.get(0, 0, buffX);

        float buffY[] = new float[(int) (mapY.total() * mapY.channels())];
        mapY.get(0, 0, buffY);

            

Reported by PMD.

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

Line: 61

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


            

Reported by PMD.

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

Line: 63

                      Mat src = Imgcodecs.imread(filename, Imgcodecs.IMREAD_COLOR);
        if (src.empty()) {
            System.err.println("Cannot read image: " + filename);
            System.exit(0);
        }
        //! [Load]

        //! [Create]
        mapX = new Mat(src.size(), CvType.CV_32F);

            

Reported by PMD.

samples/python/distrans.py
16 issues
Unable to import 'cv2'
Error

Line: 18 Column: 1

              from __future__ import print_function

import numpy as np
import cv2 as cv

from common import make_cmap

def main():
    import sys

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 26 Column: 5

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

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

            

Reported by Pylint.

Redefining name 'need_update' from outer scope (line 41)
Error

Line: 36 Column: 5

                      sys.exit(1)

    cm = make_cmap('jet')
    need_update = True
    voronoi = False

    def update(dummy=None):
        global need_update
        need_update = False

            

Reported by Pylint.

Unused argument 'dummy'
Error

Line: 39 Column: 16

                  need_update = True
    voronoi = False

    def update(dummy=None):
        global need_update
        need_update = False
        thrs = cv.getTrackbarPos('threshold', 'distrans')
        mark = cv.Canny(img, thrs, 3*thrs)
        dist, labels = cv.distanceTransformWithLabels(~mark, cv.DIST_L2, 5)

            

Reported by Pylint.

Global variable 'need_update' undefined at the module level
Error

Line: 40 Column: 9

                  voronoi = False

    def update(dummy=None):
        global need_update
        need_update = False
        thrs = cv.getTrackbarPos('threshold', 'distrans')
        mark = cv.Canny(img, thrs, 3*thrs)
        dist, labels = cv.distanceTransformWithLabels(~mark, cv.DIST_L2, 5)
        if voronoi:

            

Reported by Pylint.

Unused argument 'dummy'
Error

Line: 52 Column: 20

                      vis[mark != 0] = 255
        cv.imshow('distrans', vis)

    def invalidate(dummy=None):
        global need_update
        need_update = True

    cv.namedWindow('distrans')
    cv.createTrackbar('threshold', 'distrans', 60, 255, invalidate)

            

Reported by Pylint.

Global variable 'need_update' undefined at the module level
Error

Line: 53 Column: 9

                      cv.imshow('distrans', vis)

    def invalidate(dummy=None):
        global need_update
        need_update = True

    cv.namedWindow('distrans')
    cv.createTrackbar('threshold', 'distrans', 60, 255, invalidate)
    update()

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 22 Column: 1

              
from common import make_cmap

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

            

Reported by Pylint.

Import outside toplevel (sys)
Error

Line: 23 Column: 5

              from common import make_cmap

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


            

Reported by Pylint.

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

Line: 25 Column: 9

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

    fn = cv.samples.findFile(fn)
    img = cv.imread(fn, cv.IMREAD_GRAYSCALE)

            

Reported by Pylint.

samples/python/houghlines.py
16 issues
Unable to import 'cv2'
Error

Line: 14 Column: 1

              # Python 2/3 compatibility
from __future__ import print_function

import cv2 as cv
import numpy as np

import sys
import math


            

Reported by Pylint.

Using a conditional statement with a constant value
Error

Line: 30 Column: 5

                  dst = cv.Canny(src, 50, 200)
    cdst = cv.cvtColor(dst, cv.COLOR_GRAY2BGR)

    if True: # HoughLinesP
        lines = cv.HoughLinesP(dst, 1, math.pi/180.0, 40, np.array([]), 50, 10)
        a, b, _c = lines.shape
        for i in range(a):
            cv.line(cdst, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv.LINE_AA)


            

Reported by Pylint.

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

Line: 17 Column: 1

              import cv2 as cv
import numpy as np

import sys
import math

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

            

Reported by Pylint.

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

Line: 18 Column: 1

              import numpy as np

import sys
import math

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

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 20 Column: 1

              import sys
import math

def main():
    try:
        fn = sys.argv[1]
    except IndexError:
        fn = 'pic1.png'


            

Reported by Pylint.

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

Line: 22 Column: 9

              
def main():
    try:
        fn = sys.argv[1]
    except IndexError:
        fn = 'pic1.png'

    src = cv.imread(cv.samples.findFile(fn))
    dst = cv.Canny(src, 50, 200)

            

Reported by Pylint.

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

Line: 24 Column: 9

                  try:
        fn = sys.argv[1]
    except IndexError:
        fn = 'pic1.png'

    src = cv.imread(cv.samples.findFile(fn))
    dst = cv.Canny(src, 50, 200)
    cdst = cv.cvtColor(dst, cv.COLOR_GRAY2BGR)


            

Reported by Pylint.

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

Line: 32 Column: 9

              
    if True: # HoughLinesP
        lines = cv.HoughLinesP(dst, 1, math.pi/180.0, 40, np.array([]), 50, 10)
        a, b, _c = lines.shape
        for i in range(a):
            cv.line(cdst, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv.LINE_AA)

    else:    # HoughLines
        lines = cv.HoughLines(dst, 1, math.pi/180.0, 50, np.array([]), 0, 0)

            

Reported by Pylint.

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

Line: 32 Column: 12

              
    if True: # HoughLinesP
        lines = cv.HoughLinesP(dst, 1, math.pi/180.0, 40, np.array([]), 50, 10)
        a, b, _c = lines.shape
        for i in range(a):
            cv.line(cdst, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv.LINE_AA)

    else:    # HoughLines
        lines = cv.HoughLines(dst, 1, math.pi/180.0, 50, np.array([]), 0, 0)

            

Reported by Pylint.

Line too long (121/100)
Error

Line: 34 Column: 1

                      lines = cv.HoughLinesP(dst, 1, math.pi/180.0, 40, np.array([]), 50, 10)
        a, b, _c = lines.shape
        for i in range(a):
            cv.line(cdst, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv.LINE_AA)

    else:    # HoughLines
        lines = cv.HoughLines(dst, 1, math.pi/180.0, 50, np.array([]), 0, 0)
        if lines is not None:
            a, b, _c = lines.shape

            

Reported by Pylint.

samples/python/hist.py
16 issues
Unable to import 'cv2'
Error

Line: 22 Column: 1

              from __future__ import print_function

import numpy as np
import cv2 as cv

bins = np.arange(256).reshape(256,1)

def hist_curve(im):
    h = np.zeros((300,256,3))

            

Reported by Pylint.

Line too long (127/100)
Error

Line: 3 Column: 1

              #!/usr/bin/env python

''' This is a sample for histogram plotting for RGB images and grayscale images for better understanding of colour distribution

Benefit : Learn how to draw histogram of images
          Get familier with cv.calcHist, cv.equalizeHist,cv.normalize and some drawing functions

Level : Beginner or Intermediate


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 26 Column: 1

              
bins = np.arange(256).reshape(256,1)

def hist_curve(im):
    h = np.zeros((300,256,3))
    if len(im.shape) == 2:
        color = [(255,255,255)]
    elif im.shape[2] == 3:
        color = [ (255,0,0),(0,255,0),(0,0,255) ]

            

Reported by Pylint.

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

Line: 26 Column: 1

              
bins = np.arange(256).reshape(256,1)

def hist_curve(im):
    h = np.zeros((300,256,3))
    if len(im.shape) == 2:
        color = [(255,255,255)]
    elif im.shape[2] == 3:
        color = [ (255,0,0),(0,255,0),(0,0,255) ]

            

Reported by Pylint.

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

Line: 27 Column: 5

              bins = np.arange(256).reshape(256,1)

def hist_curve(im):
    h = np.zeros((300,256,3))
    if len(im.shape) == 2:
        color = [(255,255,255)]
    elif im.shape[2] == 3:
        color = [ (255,0,0),(0,255,0),(0,0,255) ]
    for ch, col in enumerate(color):

            

Reported by Pylint.

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

Line: 32 Column: 9

                      color = [(255,255,255)]
    elif im.shape[2] == 3:
        color = [ (255,0,0),(0,255,0),(0,0,255) ]
    for ch, col in enumerate(color):
        hist_item = cv.calcHist([im],[ch],None,[256],[0,256])
        cv.normalize(hist_item,hist_item,0,255,cv.NORM_MINMAX)
        hist=np.int32(np.around(hist_item))
        pts = np.int32(np.column_stack((bins,hist)))
        cv.polylines(h,[pts],False,col)

            

Reported by Pylint.

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

Line: 38 Column: 5

                      hist=np.int32(np.around(hist_item))
        pts = np.int32(np.column_stack((bins,hist)))
        cv.polylines(h,[pts],False,col)
    y=np.flipud(h)
    return y

def hist_lines(im):
    h = np.zeros((300,256,3))
    if len(im.shape)!=2:

            

Reported by Pylint.

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

Line: 41 Column: 1

                  y=np.flipud(h)
    return y

def hist_lines(im):
    h = np.zeros((300,256,3))
    if len(im.shape)!=2:
        print("hist_lines applicable only for grayscale images")
        #print("so converting image to grayscale for representation"
        im = cv.cvtColor(im,cv.COLOR_BGR2GRAY)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 41 Column: 1

                  y=np.flipud(h)
    return y

def hist_lines(im):
    h = np.zeros((300,256,3))
    if len(im.shape)!=2:
        print("hist_lines applicable only for grayscale images")
        #print("so converting image to grayscale for representation"
        im = cv.cvtColor(im,cv.COLOR_BGR2GRAY)

            

Reported by Pylint.

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

Line: 42 Column: 5

                  return y

def hist_lines(im):
    h = np.zeros((300,256,3))
    if len(im.shape)!=2:
        print("hist_lines applicable only for grayscale images")
        #print("so converting image to grayscale for representation"
        im = cv.cvtColor(im,cv.COLOR_BGR2GRAY)
    hist_item = cv.calcHist([im],[0],None,[256],[0,256])

            

Reported by Pylint.