The following issues were found

modules/python/src2/gen2.py
181 issues
Unable to import 'cStringIO'
Error

Line: 12 Column: 5

              if sys.version_info[0] >= 3:
    from io import StringIO
else:
    from cStringIO import StringIO


forbidden_arg_types = ["void*"]

ignored_arg_types = ["RNG*"]

            

Reported by Pylint.

Argument 'builtins.bool' does not match format type 'd'
Error

Line: 418 Column: 16

                      return self.tp in ["Mat", "vector_Mat", "cuda::GpuMat", "GpuMat", "vector_GpuMat", "UMat", "vector_UMat"] # or self.tp.startswith("vector")

    def crepr(self):
        return "ArgInfo(\"%s\", %d)" % (self.name, self.outputarg)


class FuncVariant(object):
    def __init__(self, classname, name, decl, isconstructor, isphantom=False):
        self.classname = classname

            

Reported by Pylint.

Instance of 'PythonWrapperGenerator' has no 'gen_const_reg' member
Error

Line: 1173 Column: 13

                      constlist = list(self.consts.items())
        constlist.sort()
        for name, constinfo in constlist:
            self.gen_const_reg(constinfo)

        # That's it. Now save all the files
        self.save(output_path, "pyopencv_generated_include.h", self.code_include)
        self.save(output_path, "pyopencv_generated_funcs.h", self.code_funcs)
        self.save(output_path, "pyopencv_generated_enums.h", self.code_enums)

            

Reported by Pylint.

Unused import os
Error

Line: 4 Column: 1

              #!/usr/bin/env python

from __future__ import print_function
import hdr_parser, sys, re, os
from string import Template
from pprint import pprint
from collections import namedtuple

if sys.version_info[0] >= 3:

            

Reported by Pylint.

Unused pprint imported from pprint
Error

Line: 6 Column: 1

              from __future__ import print_function
import hdr_parser, sys, re, os
from string import Template
from pprint import pprint
from collections import namedtuple

if sys.version_info[0] >= 3:
    from io import StringIO
else:

            

Reported by Pylint.

Unused variable 'all_classes'
Error

Line: 307 Column: 9

                      return code

    def gen_code(self, codegen):
        all_classes = codegen.classes
        if self.ismap:
            return self.gen_map_code(codegen)

        getset_code = StringIO()
        getset_inits = StringIO()

            

Reported by Pylint.

Unused variable 'mname'
Error

Line: 344 Column: 13

                      if self.constructor is not None:
            methods_code.write(self.constructor.gen_code(codegen))

        for mname, m in sorted_methods:
            methods_code.write(m.gen_code(codegen))
            methods_inits.write(m.get_tab_entry())

        code = gen_template_type_impl.substitute(name=self.name, wname=self.wname, cname=self.cname,
            getset_code=getset_code.getvalue(), getset_inits=getset_inits.getvalue(),

            

Reported by Pylint.

Unused variable 'aname'
Error

Line: 525 Column: 13

                      self.py_prototype = "%s(%s) -> %s" % (self.wname, argstr, outstr)
        self.py_noptargs = noptargs
        self.py_arglist = arglist
        for aname, argno in arglist:
            self.args[argno].py_inputarg = True
        for aname, argno in outlist:
            if argno >= 0:
                self.args[argno].py_outputarg = True
        self.py_outlist = outlist

            

Reported by Pylint.

Unused variable 'tp1'
Error

Line: 668 Column: 17

                                  code_args += defval
                    all_cargs.append([[None, ""], ""])
                    continue
                tp1 = tp = a.tp
                amp = ""
                defval0 = ""
                if tp in pass_by_val_types:
                    tp = tp1 = tp[:-1]
                    amp = "&"

            

Reported by Pylint.

Unused variable 'argno'
Error

Line: 790 Column: 28

                              if self.isconstructor:
                    code_ret = "return 0"
                else:
                    aname, argno = v.py_outlist[0]
                    code_ret = "return pyopencv_from(%s)" % (aname,)
            else:
                # there is more than 1 return parameter; form the tuple out of them
                fmtspec = "N"*len(v.py_outlist)
                code_ret = "return Py_BuildValue(\"(%s)\", %s)" % \

            

Reported by Pylint.

modules/ts/misc/table_formatter.py
179 issues
Unable to import 'msvcrt'
Error

Line: 614 Column: 13

              def getStdoutFilename():
    try:
        if os.name == "nt":
            import msvcrt, ctypes
            handle = msvcrt.get_osfhandle(sys.stdout.fileno())
            size = ctypes.c_ulong(1024)
            nameBuffer = ctypes.create_string_buffer(size.value)
            ctypes.windll.kernel32.GetFinalPathNameByHandleA(handle, nameBuffer, size, 4)
            return nameBuffer.value

            

Reported by Pylint.

Unused import re
Error

Line: 4 Column: 1

              #!/usr/bin/env python

from __future__ import print_function
import sys, re, os.path, stat, math
try:
    from html import escape
except ImportError:
    from cgi import escape  # Python 2.7
from optparse import OptionParser

            

Reported by Pylint.

Unused import stat
Error

Line: 4 Column: 1

              #!/usr/bin/env python

from __future__ import print_function
import sys, re, os.path, stat, math
try:
    from html import escape
except ImportError:
    from cgi import escape  # Python 2.7
from optparse import OptionParser

            

Reported by Pylint.

Uses of a deprecated module 'optparse'
Error

Line: 9 Column: 1

                  from html import escape
except ImportError:
    from cgi import escape  # Python 2.7
from optparse import OptionParser
from color import getColorizer, dummyColorizer

class tblCell(object):
    def __init__(self, text, value = None, props = None):
        self.text = text

            

Reported by Pylint.

Redefining built-in 'str'
Error

Line: 29 Column: 16

                      self.cells = [None] * colsNum
        self.props = props

def htmlEncode(str):
    return '<br/>'.join([escape(s) for s in str])

class table(object):
    def_align = "left"
    def_valign = "middle"

            

Reported by Pylint.

Redefining built-in 'format'
Error

Line: 42 Column: 40

                  def_italic = False
    def_text="-"

    def __init__(self, caption = None, format=None):
        self.format = format
        self.is_markdown = self.format == 'markdown'
        self.is_tabs = self.format == 'tabs'
        self.columns = {}
        self.rows = []

            

Reported by Pylint.

Unnecessary semicolon
Error

Line: 48 Column: 1

                      self.is_tabs = self.format == 'tabs'
        self.columns = {}
        self.rows = []
        self.ridx = -1;
        self.caption = caption
        pass

    def newRow(self, **properties):
        if len(self.rows) - 1 == self.ridx:

            

Reported by Pylint.

Unnecessary pass statement
Error

Line: 50 Column: 9

                      self.rows = []
        self.ridx = -1;
        self.caption = caption
        pass

    def newRow(self, **properties):
        if len(self.rows) - 1 == self.ridx:
            self.rows.append(tblRow(len(self.columns), properties))
        else:

            

Reported by Pylint.

Attribute 'index' defined outside __init__
Error

Line: 77 Column: 13

                          return caption
        else:
            col = tblColumn(caption, title, properties)
            col.index = index
            self.columns[name] = col
            return col

    def getColumn(self, name):
        if isinstance(name, str):

            

Reported by Pylint.

Attribute 'headerHeight' defined outside __init__
Error

Line: 111 Column: 9

                      colspanned = []
        rowspanned = []

        self.headerHeight = 1
        rowsToAppend = 0

        for col in columns:
            self.measureCell(col)
            if col.height > self.headerHeight:

            

Reported by Pylint.

modules/calib3d/misc/java/test/Calib3dTest.java
158 issues
Do not use the short type
Performance

Line: 473

                      truth = new Mat(matSize, matSize, CvType.CV_16SC3);

        short[] _truth = new short[matSize * matSize * 3];
        for (short i = 0; i < matSize; i++)
            for (short j = 0; j < matSize; j++) {
                _truth[(i * matSize + j) * 3 + 0] = i;
                _truth[(i * matSize + j) * 3 + 1] = j;
                _truth[(i * matSize + j) * 3 + 2] = (short) (i - j);
            }

            

Reported by PMD.

Do not use the short type
Performance

Line: 474

              
        short[] _truth = new short[matSize * matSize * 3];
        for (short i = 0; i < matSize; i++)
            for (short j = 0; j < matSize; j++) {
                _truth[(i * matSize + j) * 3 + 0] = i;
                _truth[(i * matSize + j) * 3 + 1] = j;
                _truth[(i * matSize + j) * 3 + 2] = (short) (i - j);
            }
        truth.put(0, 0, _truth);

            

Reported by PMD.

This class has a bunch of public methods and attributes
Design

Line: 1

              package org.opencv.test.calib3d;

import java.util.ArrayList;

import org.opencv.calib3d.Calib3d;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDouble;

            

Reported by PMD.

This class has too many methods, consider refactoring it.
Design

Line: 18

              import org.opencv.test.OpenCVTestCase;
import org.opencv.imgproc.Imgproc;

public class Calib3dTest extends OpenCVTestCase {

    Size size;

    @Override
    protected void setUp() throws Exception {

            

Reported by PMD.

The class 'Calib3dTest' has a total cyclomatic complexity of 109 (highest 5).
Design

Line: 18

              import org.opencv.test.OpenCVTestCase;
import org.opencv.imgproc.Imgproc;

public class Calib3dTest extends OpenCVTestCase {

    Size size;

    @Override
    protected void setUp() throws Exception {

            

Reported by PMD.

Possible God Class (WMC=109, ATFD=136, TCC=0.255%)
Design

Line: 18

              import org.opencv.test.OpenCVTestCase;
import org.opencv.imgproc.Imgproc;

public class Calib3dTest extends OpenCVTestCase {

    Size size;

    @Override
    protected void setUp() throws Exception {

            

Reported by PMD.

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

Line: 20

              
public class Calib3dTest extends OpenCVTestCase {

    Size size;

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

              
    Size size;

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

        size = new Size(3, 3);
    }

            

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

                      size = new Size(3, 3);
    }

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

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

            

Reported by PMD.

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

Line: 30

                  }

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

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

            

Reported by PMD.

platforms/ios/build_framework.py
157 issues
Unable to import 'cv_build_utils'
Error

Line: 40 Column: 1

              from distutils.dir_util import copy_tree

sys.path.insert(0, os.path.abspath(os.path.abspath(os.path.dirname(__file__))+'/../apple'))
from cv_build_utils import execute, print_error, get_xcode_major, get_xcode_setting, get_xcode_version, get_cmake_version

IPHONEOS_DEPLOYMENT_TARGET='9.0'  # default, can be changed via command line options or environment variable

class Builder:
    def __init__(self, opencv, contrib, dynamic, bitcodedisabled, exclude, disable, enablenonfree, targets, debug, debug_info, framework_name, run_tests, build_docs, swiftdisabled):

            

Reported by Pylint.

Assigning result of a function call, where the function returns None
Error

Line: 249 Column: 9

                      return 'ios'

    def makeCMakeCmd(self, arch, target, dir, cmakeargs = []):
        toolchain = self.getToolchain(arch, target)
        cmakecmd = self.getCMakeArgs(arch, target) + \
            (["-DCMAKE_TOOLCHAIN_FILE=%s" % toolchain] if toolchain is not None else [])
        if target.lower().startswith("iphoneos"):
            cmakecmd.append("-DCPU_BASELINE=DETECT")
        if target.lower().startswith("iphonesimulator"):

            

Reported by Pylint.

Unused import string
Error

Line: 35 Column: 1

              """

from __future__ import print_function, unicode_literals
import glob, os, os.path, shutil, string, sys, argparse, traceback, multiprocessing, codecs, io
from subprocess import check_call, check_output, CalledProcessError
from distutils.dir_util import copy_tree

sys.path.insert(0, os.path.abspath(os.path.abspath(os.path.dirname(__file__))+'/../apple'))
from cv_build_utils import execute, print_error, get_xcode_major, get_xcode_setting, get_xcode_version, get_cmake_version

            

Reported by Pylint.

Unused CalledProcessError imported from subprocess
Error

Line: 36 Column: 1

              
from __future__ import print_function, unicode_literals
import glob, os, os.path, shutil, string, sys, argparse, traceback, multiprocessing, codecs, io
from subprocess import check_call, check_output, CalledProcessError
from distutils.dir_util import copy_tree

sys.path.insert(0, os.path.abspath(os.path.abspath(os.path.dirname(__file__))+'/../apple'))
from cv_build_utils import execute, print_error, get_xcode_major, get_xcode_setting, get_xcode_version, get_cmake_version


            

Reported by Pylint.

Redefining name 'targets' from outer scope (line 568)
Error

Line: 45 Column: 100

              IPHONEOS_DEPLOYMENT_TARGET='9.0'  # default, can be changed via command line options or environment variable

class Builder:
    def __init__(self, opencv, contrib, dynamic, bitcodedisabled, exclude, disable, enablenonfree, targets, debug, debug_info, framework_name, run_tests, build_docs, swiftdisabled):
        self.opencv = os.path.abspath(opencv)
        self.contrib = None
        if contrib:
            modpath = os.path.join(contrib, "modules")
            if os.path.isdir(modpath):

            

Reported by Pylint.

Using possibly undefined loop variable 'target'
Error

Line: 143 Column: 234

                      self.makeFramework(outdir, dirs)
        if self.build_objc_wrapper:
            if self.run_tests:
                check_call([sys.argv[0].replace("build_framework", "run_tests"), "--framework_dir=" + outdir, "--framework_name=" + self.framework_name, dirs[0] +  "/modules/objc_bindings_generator/{}/test".format(self.getObjcTarget(target[1]))])
            else:
                print("To run tests call:")
                print(sys.argv[0].replace("build_framework", "run_tests") + " --framework_dir=" + outdir + " --framework_name=" + self.framework_name + " " + dirs[0] +  "/modules/objc_bindings_generator/{}/test".format(self.getObjcTarget(target[1])))
            if self.build_docs:
                check_call([sys.argv[0].replace("build_framework", "build_docs"), dirs[0] + "/modules/objc/framework_build"])

            

Reported by Pylint.

Using possibly undefined loop variable 'target'
Error

Line: 146 Column: 239

                              check_call([sys.argv[0].replace("build_framework", "run_tests"), "--framework_dir=" + outdir, "--framework_name=" + self.framework_name, dirs[0] +  "/modules/objc_bindings_generator/{}/test".format(self.getObjcTarget(target[1]))])
            else:
                print("To run tests call:")
                print(sys.argv[0].replace("build_framework", "run_tests") + " --framework_dir=" + outdir + " --framework_name=" + self.framework_name + " " + dirs[0] +  "/modules/objc_bindings_generator/{}/test".format(self.getObjcTarget(target[1])))
            if self.build_docs:
                check_call([sys.argv[0].replace("build_framework", "build_docs"), dirs[0] + "/modules/objc/framework_build"])
                doc_path = os.path.join(dirs[0], "modules", "objc", "doc_build", "docs")
                if os.path.exists(doc_path):
                    shutil.copytree(doc_path, os.path.join(outdir, "docs"))

            

Reported by Pylint.

Catching too general exception Exception
Error

Line: 177 Column: 16

                  def build(self, outdir):
        try:
            self._build(outdir)
        except Exception as e:
            print_error(e)
            traceback.print_exc(file=sys.stderr)
            sys.exit(1)

    def getToolchain(self, arch, target):

            

Reported by Pylint.

Unused argument 'target'
Error

Line: 182 Column: 34

                          traceback.print_exc(file=sys.stderr)
            sys.exit(1)

    def getToolchain(self, arch, target):
        return None

    def getConfiguration(self):
        return "Debug" if self.debug else "Release"


            

Reported by Pylint.

Unused argument 'arch'
Error

Line: 182 Column: 28

                          traceback.print_exc(file=sys.stderr)
            sys.exit(1)

    def getToolchain(self, arch, target):
        return None

    def getConfiguration(self):
        return "Debug" if self.debug else "Release"


            

Reported by Pylint.

modules/ts/misc/trace_profiler.py
137 issues
Unused argument 'args'
Error

Line: 25 Column: 16

                  dprint = print
    dpprint = pprint
else:
    def dprint(args, **kwargs):
        pass
    def dpprint(args, **kwargs):
        pass

def tryNum(s):

            

Reported by Pylint.

Unused argument 'kwargs'
Error

Line: 25 Column: 1

                  dprint = print
    dpprint = pprint
else:
    def dprint(args, **kwargs):
        pass
    def dpprint(args, **kwargs):
        pass

def tryNum(s):

            

Reported by Pylint.

Unused argument 'args'
Error

Line: 27 Column: 17

              else:
    def dprint(args, **kwargs):
        pass
    def dpprint(args, **kwargs):
        pass

def tryNum(s):
    if s.startswith('0x'):
        try:

            

Reported by Pylint.

Unused argument 'kwargs'
Error

Line: 27 Column: 1

              else:
    def dprint(args, **kwargs):
        pass
    def dpprint(args, **kwargs):
        pass

def tryNum(s):
    if s.startswith('0x'):
        try:

            

Reported by Pylint.

Redefining built-in 'id'
Error

Line: 255 Column: 14

                      self.tasks_list.sort(key=lambda x: x.beginTimestamp)

        parallel_for_location = None
        for (id, l) in self.locations.items():
            if l.name == 'parallel_for':
                parallel_for_location = l.locationID
                break

        for task in self.tasks_list:

            

Reported by Pylint.

Unused variable 'id'
Error

Line: 255 Column: 14

                      self.tasks_list.sort(key=lambda x: x.beginTimestamp)

        parallel_for_location = None
        for (id, l) in self.locations.items():
            if l.name == 'parallel_for':
                parallel_for_location = l.locationID
                break

        for task in self.tasks_list:

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 264 Column: 13

                          try:
                task.duration = task.endTimestamp - task.beginTimestamp
                task.selfDuration = task.duration
            except:
                task.duration = None
                task.selfDuration = None
            task.totalTimeIPP = task.selfTimeIPP
            task.totalTimeOpenCL = task.selfTimeOpenCL


            

Reported by Pylint.

TODO parallel_for
Error

Line: 281 Column: 3

                              timeIPP = task.selfTimeIPP
                timeOpenCL = task.selfTimeOpenCL
                while parentTask:
                    if parentTask.locationID == parallel_for_location:  # TODO parallel_for
                        break
                    parentLocation = self.locations[parentTask.locationID]
                    if (parentLocation.flags & REGION_FLAG_IMPL_MASK) == REGION_FLAG_IMPL_IPP:
                        parentTask.selfTimeIPP = parentTask.selfTimeIPP - timeIPP
                        timeIPP = 0

            

Reported by Pylint.

Unused variable 'loc0'
Error

Line: 401 Column: 13

                      print(fmt2.format("", "", "", "", "t-min", "t-max", "t-median", "t-avg", "total", "t-IPP", "%", "t-OpenCL", "%"))
        for (index, callID) in enumerate(calls_sorted):
            call_self_times = calls[callID].selfTimes
            loc0 = self.locations[callID[0]]
            loc_array = []  # [str(callID)]
            for (i, l) in enumerate(callID):
                loc = self.locations[l]
                loc_array.append(loc.name if i > 0 else str(loc))
            loc_str = '|'.join(loc_array)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from __future__ import print_function

import os
import sys
import csv
from pprint import pprint
from collections import deque

try:

            

Reported by Pylint.

modules/java/test/pure_test/src/org/opencv/test/OpenCVTestCase.java
131 issues
Avoid instantiating FileInputStream, FileOutputStream, FileReader, or FileWriter
Performance

Line: 549

              
    protected static String readFile(String path) {
        try {
        BufferedReader br = new BufferedReader(new FileReader(path));
        String line;
        StringBuffer result = new StringBuffer();
        while ((line = br.readLine()) != null) {
            result.append(line);
            result.append("\n");

            

Reported by PMD.

Avoid instantiating FileInputStream, FileOutputStream, FileReader, or FileWriter
Performance

Line: 567

                  protected static void writeFile(String path, String content) {
        FileOutputStream stream = null;
        try {
            stream = new FileOutputStream(new File(path));
            FileChannel fc = stream.getChannel();
            fc.write(Charset.defaultCharset().encode(content));
        } catch (IOException e) {
            OpenCVTestRunner.Log("Failed to write file \"" + path
                    + "\". Exception is thrown: " + e);

            

Reported by PMD.

System.out.println is used
Design

Line: 112

                      try {
            System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        } catch (SecurityException e) {
            System.out.println(e.toString());
            System.exit(-1);
        } catch (UnsatisfiedLinkError e) {
            System.out.println(e.toString());
            System.exit(-1);
        }

            

Reported by PMD.

System.out.println is used
Design

Line: 115

                          System.out.println(e.toString());
            System.exit(-1);
        } catch (UnsatisfiedLinkError e) {
            System.out.println(e.toString());
            System.exit(-1);
        }

        Core.setErrorVerbosity(false);


            

Reported by PMD.

System.out.println is used
Design

Line: 125

                      try {
            pwd = new File(".").getCanonicalPath() + File.separator;
        } catch (IOException e) {
            System.out.println(e);
            return;
        }

        OpenCVTestRunner.LENA_PATH = pwd + "res/drawable/lena.png";
        OpenCVTestRunner.CHESS_PATH = pwd + "res/drawable/chessboard.jpg";

            

Reported by PMD.

This class has too many methods, consider refactoring it.
Design

Line: 30

              import org.opencv.core.KeyPoint;
import org.opencv.imgcodecs.Imgcodecs;

public class OpenCVTestCase extends TestCase {

    public static class TestSkipException extends RuntimeException {
        public TestSkipException() {}
    }


            

Reported by PMD.

Possible God Class (WMC=127, ATFD=153, TCC=0.775%)
Design

Line: 30

              import org.opencv.core.KeyPoint;
import org.opencv.imgcodecs.Imgcodecs;

public class OpenCVTestCase extends TestCase {

    public static class TestSkipException extends RuntimeException {
        public TestSkipException() {}
    }


            

Reported by PMD.

The class 'OpenCVTestCase' has a total cyclomatic complexity of 127 (highest 10).
Design

Line: 30

              import org.opencv.core.KeyPoint;
import org.opencv.imgcodecs.Imgcodecs;

public class OpenCVTestCase extends TestCase {

    public static class TestSkipException extends RuntimeException {
        public TestSkipException() {}
    }


            

Reported by PMD.

This class name ends with Test but contains no test cases
Error

Line: 30

              import org.opencv.core.KeyPoint;
import org.opencv.imgcodecs.Imgcodecs;

public class OpenCVTestCase extends TestCase {

    public static class TestSkipException extends RuntimeException {
        public TestSkipException() {}
    }


            

Reported by PMD.

Too many fields
Design

Line: 30

              import org.opencv.core.KeyPoint;
import org.opencv.imgcodecs.Imgcodecs;

public class OpenCVTestCase extends TestCase {

    public static class TestSkipException extends RuntimeException {
        public TestSkipException() {}
    }


            

Reported by PMD.

modules/dnn/misc/quantize_face_detector.py
124 issues
Unable to import 'cv2'
Error

Line: 4 Column: 1

              from __future__ import print_function
import sys
import argparse
import cv2 as cv
import tensorflow as tf
import numpy as np
import struct

if sys.version_info > (3,):

            

Reported by Pylint.

No name 'python' in module 'tensorflow'
Error

Line: 12 Column: 1

              if sys.version_info > (3,):
    long = int

from tensorflow.python.tools import optimize_for_inference_lib
from tensorflow.tools.graph_transforms import TransformGraph
from tensorflow.core.framework.node_def_pb2 import NodeDef
from google.protobuf import text_format

parser = argparse.ArgumentParser(description="Use this script to create TensorFlow graph "

            

Reported by Pylint.

Unable to import 'tensorflow.python.tools'
Error

Line: 12 Column: 1

              if sys.version_info > (3,):
    long = int

from tensorflow.python.tools import optimize_for_inference_lib
from tensorflow.tools.graph_transforms import TransformGraph
from tensorflow.core.framework.node_def_pb2 import NodeDef
from google.protobuf import text_format

parser = argparse.ArgumentParser(description="Use this script to create TensorFlow graph "

            

Reported by Pylint.

Unable to import 'tensorflow.tools.graph_transforms'
Error

Line: 13 Column: 1

                  long = int

from tensorflow.python.tools import optimize_for_inference_lib
from tensorflow.tools.graph_transforms import TransformGraph
from tensorflow.core.framework.node_def_pb2 import NodeDef
from google.protobuf import text_format

parser = argparse.ArgumentParser(description="Use this script to create TensorFlow graph "
                                             "with weights from OpenCV's face detection network. "

            

Reported by Pylint.

No name 'tools' in module 'tensorflow'
Error

Line: 13 Column: 1

                  long = int

from tensorflow.python.tools import optimize_for_inference_lib
from tensorflow.tools.graph_transforms import TransformGraph
from tensorflow.core.framework.node_def_pb2 import NodeDef
from google.protobuf import text_format

parser = argparse.ArgumentParser(description="Use this script to create TensorFlow graph "
                                             "with weights from OpenCV's face detection network. "

            

Reported by Pylint.

Unable to import 'tensorflow.core.framework.node_def_pb2'
Error

Line: 14 Column: 1

              
from tensorflow.python.tools import optimize_for_inference_lib
from tensorflow.tools.graph_transforms import TransformGraph
from tensorflow.core.framework.node_def_pb2 import NodeDef
from google.protobuf import text_format

parser = argparse.ArgumentParser(description="Use this script to create TensorFlow graph "
                                             "with weights from OpenCV's face detection network. "
                                             "Only backbone part of SSD model is converted this way. "

            

Reported by Pylint.

No name 'core' in module 'tensorflow'
Error

Line: 14 Column: 1

              
from tensorflow.python.tools import optimize_for_inference_lib
from tensorflow.tools.graph_transforms import TransformGraph
from tensorflow.core.framework.node_def_pb2 import NodeDef
from google.protobuf import text_format

parser = argparse.ArgumentParser(description="Use this script to create TensorFlow graph "
                                             "with weights from OpenCV's face detection network. "
                                             "Only backbone part of SSD model is converted this way. "

            

Reported by Pylint.

Unable to import 'google.protobuf'
Error

Line: 15 Column: 1

              from tensorflow.python.tools import optimize_for_inference_lib
from tensorflow.tools.graph_transforms import TransformGraph
from tensorflow.core.framework.node_def_pb2 import NodeDef
from google.protobuf import text_format

parser = argparse.ArgumentParser(description="Use this script to create TensorFlow graph "
                                             "with weights from OpenCV's face detection network. "
                                             "Only backbone part of SSD model is converted this way. "
                                             "Look for .pbtxt configuration file at "

            

Reported by Pylint.

Module 'tensorflow' has no 'float16' member
Error

Line: 32 Column: 9

              
assert(not args.quantize or not args.fp16)

dtype = tf.float16 if args.fp16 else tf.float32

################################################################################
cvNet = cv.dnn.readNetFromCaffe(args.proto, args.model)

def dnnLayer(name):

            

Reported by Pylint.

Module 'tensorflow' has no 'float32' member
Error

Line: 32 Column: 38

              
assert(not args.quantize or not args.fp16)

dtype = tf.float16 if args.fp16 else tf.float32

################################################################################
cvNet = cv.dnn.readNetFromCaffe(args.proto, args.model)

def dnnLayer(name):

            

Reported by Pylint.

modules/dnn/misc/python/test/test_dnn.py
123 issues
Unable to import 'cv2'
Error

Line: 3 Column: 1

              #!/usr/bin/env python
import os
import cv2 as cv
import numpy as np

from tests_common import NewOpenCVTests, unittest

def normAssert(test, a, b, msg=None, lInf=1e-5):
    test.assertLess(np.max(np.abs(a - b)), lInf, msg)

            

Reported by Pylint.

Unable to import 'tests_common'
Error

Line: 6 Column: 1

              import cv2 as cv
import numpy as np

from tests_common import NewOpenCVTests, unittest

def normAssert(test, a, b, msg=None, lInf=1e-5):
    test.assertLess(np.max(np.abs(a - b)), lInf, msg)

def inter_area(box1, box2):

            

Reported by Pylint.

Using the global statement
Error

Line: 80 Column: 9

                  def setUp(self):
        super(dnn_test, self).setUp()

        global g_dnnBackendsAndTargets
        if g_dnnBackendsAndTargets is None:
            g_dnnBackendsAndTargets = self.initBackendsAndTargets()
        self.dnnBackendsAndTargets = g_dnnBackendsAndTargets

    def initBackendsAndTargets(self):

            

Reported by Pylint.

Catching too general exception BaseException
Error

Line: 122 Column: 16

                      try:
            net.setInput(inp)
            net.forward()
        except BaseException as e:
            return False
        return True

    def test_getAvailableTargets(self):
        targets = cv.dnn.getAvailableTargets(cv.dnn.DNN_BACKEND_OPENCV)

            

Reported by Pylint.

Unused variable 'e'
Error

Line: 122 Column: 9

                      try:
            net.setInput(inp)
            net.forward()
        except BaseException as e:
            return False
        return True

    def test_getAvailableTargets(self):
        targets = cv.dnn.getAvailableTargets(cv.dnn.DNN_BACKEND_OPENCV)

            

Reported by Pylint.

Unused argument 'blobs'
Error

Line: 315 Column: 40

              
    def test_custom_layer(self):
        class CropLayer(object):
            def __init__(self, params, blobs):
                self.xstart = 0
                self.xend = 0
                self.ystart = 0
                self.yend = 0
            # Our layer receives two inputs. We need to crop the first input blob

            

Reported by Pylint.

Unused argument 'params'
Error

Line: 315 Column: 32

              
    def test_custom_layer(self):
        class CropLayer(object):
            def __init__(self, params, blobs):
                self.xstart = 0
                self.xend = 0
                self.ystart = 0
                self.yend = 0
            # Our layer receives two inputs. We need to crop the first input blob

            

Reported by Pylint.

Redefining built-in 'input'
Error

Line: 395 Column: 9

                                                  "Verify OPENCV_DNN_TEST_DATA_PATH configuration parameter.")

        net = cv.dnn.readNet(model)
        input = np.load(input_file)
        # we have to expand the shape of input tensor because Python bindings cut 3D tensors to 2D
        # it should be fixed in future. see : https://github.com/opencv/opencv/issues/19091
        # please remove `expand_dims` after that
        input = np.expand_dims(input, axis=3)
        gold_output = np.load(output_file)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python
import os
import cv2 as cv
import numpy as np

from tests_common import NewOpenCVTests, unittest

def normAssert(test, a, b, msg=None, lInf=1e-5):
    test.assertLess(np.max(np.abs(a - b)), lInf, msg)

            

Reported by Pylint.

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

Line: 8 Column: 1

              
from tests_common import NewOpenCVTests, unittest

def normAssert(test, a, b, msg=None, lInf=1e-5):
    test.assertLess(np.max(np.abs(a - b)), lInf, msg)

def inter_area(box1, box2):
    x_min, x_max = max(box1[0], box2[0]), min(box1[2], box2[2])
    y_min, y_max = max(box1[1], box2[1]), min(box1[3], box2[3])

            

Reported by Pylint.

modules/java/test/android_test/src/org/opencv/test/OpenCVTestCase.java
122 issues
Avoid instantiating FileInputStream, FileOutputStream, FileReader, or FileWriter
Performance

Line: 517

              
    protected static String readFile(String path) {
        try {
        BufferedReader br = new BufferedReader(new FileReader(path));
        String line;
        StringBuffer result = new StringBuffer();
        while ((line = br.readLine()) != null) {
            result.append(line);
            result.append("\n");

            

Reported by PMD.

Avoid instantiating FileInputStream, FileOutputStream, FileReader, or FileWriter
Performance

Line: 535

                  protected static void writeFile(String path, String content) {
        FileOutputStream stream = null;
        try {
            stream = new FileOutputStream(new File(path));
            FileChannel fc = stream.getChannel();
            fc.write(Charset.defaultCharset().encode(content));
        } catch (IOException e) {
            OpenCVTestRunner.Log("Failed to write file \"" + path
                    + "\". Exception is thrown: " + e);

            

Reported by PMD.

The class 'OpenCVTestCase' has a total cyclomatic complexity of 122 (highest 10).
Design

Line: 32

              import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;

public class OpenCVTestCase extends TestCase {

    public static class TestSkipException extends RuntimeException {
        public TestSkipException() {}
    }


            

Reported by PMD.

This class has too many methods, consider refactoring it.
Design

Line: 32

              import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;

public class OpenCVTestCase extends TestCase {

    public static class TestSkipException extends RuntimeException {
        public TestSkipException() {}
    }


            

Reported by PMD.

This class name ends with Test but contains no test cases
Error

Line: 32

              import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;

public class OpenCVTestCase extends TestCase {

    public static class TestSkipException extends RuntimeException {
        public TestSkipException() {}
    }


            

Reported by PMD.

Too many fields
Design

Line: 32

              import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;

public class OpenCVTestCase extends TestCase {

    public static class TestSkipException extends RuntimeException {
        public TestSkipException() {}
    }


            

Reported by PMD.

Possible God Class (WMC=122, ATFD=141, TCC=0.813%)
Design

Line: 32

              import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;

public class OpenCVTestCase extends TestCase {

    public static class TestSkipException extends RuntimeException {
        public TestSkipException() {}
    }


            

Reported by PMD.

Classes implementing Serializable should set a serialVersionUID
Error

Line: 34

              
public class OpenCVTestCase extends TestCase {

    public static class TestSkipException extends RuntimeException {
        public TestSkipException() {}
    }

    //change to 'true' to unblock fail on fail("Not yet implemented")
    public static final boolean passNYI = true;

            

Reported by PMD.

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

Line: 52

              
    private static final String TAG = "OpenCVTestCase";

    protected Mat dst;
    protected Mat truth;

    protected Scalar colorBlack;
    protected Scalar colorWhite;


            

Reported by PMD.

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

Line: 53

                  private static final String TAG = "OpenCVTestCase";

    protected Mat dst;
    protected Mat truth;

    protected Scalar colorBlack;
    protected Scalar colorWhite;

    // Naming notation: <channels info>_[depth]_[dimensions]_value

            

Reported by PMD.

platforms/winpack_dldt/build_package.py
120 issues
subprocess call with shell=True identified, security issue.
Security injection

Line: 32
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b602_subprocess_popen_with_shell_equals_true.html

                      log.info('Executing: ' + ' '.join(cmd))
        if cwd:
            log.info("    in: %s" % cwd)
        retcode = subprocess.call(cmd, shell=shell, cwd=str(cwd) if cwd else None)
        if retcode < 0:
            raise Fail("Child was terminated by signal: %s" % -retcode)
        elif retcode > 0:
            raise Fail("Child returned: %s" % retcode)
    except OSError as e:

            

Reported by Bandit.

Unused import glob
Error

Line: 5 Column: 1

              
import os, sys
import argparse
import glob
import re
import shutil
import subprocess
import time


            

Reported by Pylint.

Unused import re
Error

Line: 6 Column: 1

              import os, sys
import argparse
import glob
import re
import shutil
import subprocess
import time

import logging as log

            

Reported by Pylint.

Unused import time
Error

Line: 9 Column: 1

              import re
import shutil
import subprocess
import time

import logging as log

if sys.version_info[0] == 2:
    sys.exit("FATAL: Python 2.x is not supported")

            

Reported by Pylint.

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

Line: 21 Column: 5

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

class Fail(Exception):
    def __init__(self, text=None):
        self.t = text
    def __str__(self):
        return "ERROR" if self.t is None else self.t

def execute(cmd, cwd=None, shell=False):

            

Reported by Pylint.

Use lazy % formatting in logging functions
Error

Line: 28 Column: 9

              
def execute(cmd, cwd=None, shell=False):
    try:
        log.debug("Executing: %s" % cmd)
        log.info('Executing: ' + ' '.join(cmd))
        if cwd:
            log.info("    in: %s" % cwd)
        retcode = subprocess.call(cmd, shell=shell, cwd=str(cwd) if cwd else None)
        if retcode < 0:

            

Reported by Pylint.

Use lazy % formatting in logging functions
Error

Line: 29 Column: 9

              def execute(cmd, cwd=None, shell=False):
    try:
        log.debug("Executing: %s" % cmd)
        log.info('Executing: ' + ' '.join(cmd))
        if cwd:
            log.info("    in: %s" % cwd)
        retcode = subprocess.call(cmd, shell=shell, cwd=str(cwd) if cwd else None)
        if retcode < 0:
            raise Fail("Child was terminated by signal: %s" % -retcode)

            

Reported by Pylint.

Use lazy % formatting in logging functions
Error

Line: 31 Column: 13

                      log.debug("Executing: %s" % cmd)
        log.info('Executing: ' + ' '.join(cmd))
        if cwd:
            log.info("    in: %s" % cwd)
        retcode = subprocess.call(cmd, shell=shell, cwd=str(cwd) if cwd else None)
        if retcode < 0:
            raise Fail("Child was terminated by signal: %s" % -retcode)
        elif retcode > 0:
            raise Fail("Child returned: %s" % retcode)

            

Reported by Pylint.

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

Line: 38 Column: 9

                      elif retcode > 0:
            raise Fail("Child returned: %s" % retcode)
    except OSError as e:
        raise Fail("Execution failed: %d / %s" % (e.errno, e.strerror))

def check_executable(cmd):
    try:
        log.debug("Executing: %s" % cmd)
        result = subprocess.check_output(cmd, stderr=subprocess.STDOUT)

            

Reported by Pylint.

Use lazy % formatting in logging functions
Error

Line: 42 Column: 9

              
def check_executable(cmd):
    try:
        log.debug("Executing: %s" % cmd)
        result = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
        if not isinstance(result, str):
            result = result.decode("utf-8")
        log.debug("Result: %s" % (result + '\n').split('\n')[0])
        return True

            

Reported by Pylint.