Drop Python2 support.

pull/23988/head
Alexander Smorkalov 2 years ago
parent cea26341a5
commit 1a3523d2d8
  1. 6
      .github/workflows/arm64-build-checks.yml
  2. 13
      CMakeLists.txt
  3. 23
      cmake/OpenCVDetectPython.cmake
  4. 1
      cmake/OpenCVMinDepVersions.cmake
  5. 1
      cmake/OpenCVModule.cmake
  6. 1
      cmake/vars/OPENCV_DISABLE_THREAD_SUPPORT.cmake
  7. 2
      doc/pattern_tools/test_charuco_board.py
  8. 2
      doc/py_tutorials/py_imgproc/py_histograms/py_2d_histogram/py_2d_histogram.markdown
  9. 2
      doc/py_tutorials/py_imgproc/py_histograms/py_histogram_begins/py_histogram_begins.markdown
  10. 3
      doc/py_tutorials/py_setup/py_setup_in_fedora/py_setup_in_fedora.markdown
  11. 12
      doc/py_tutorials/py_setup/py_setup_in_ubuntu/py_setup_in_ubuntu.markdown
  12. 3
      doc/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.markdown
  13. 1
      doc/tutorials/introduction/config_reference/config_reference.markdown
  14. 2
      doc/tutorials/introduction/macos_install/macos_install.markdown
  15. 10
      modules/python/CMakeLists.txt
  16. 15
      modules/python/python2/CMakeLists.txt
  17. 1
      modules/ts/misc/chart.py
  18. 1
      modules/ts/misc/perf_tests_timing.py
  19. 1
      modules/ts/misc/report.py
  20. 1
      modules/ts/misc/run_long.py
  21. 6
      modules/ts/misc/run_suite.py
  22. 8
      modules/ts/misc/run_utils.py
  23. 1
      modules/ts/misc/summary.py
  24. 10
      modules/ts/misc/table_formatter.py
  25. 13
      modules/ts/misc/testlog_parser.py
  26. 12
      modules/ts/misc/trace_profiler.py
  27. 2
      modules/ts/misc/xls-report.py
  28. 2
      platforms/apple/cv_build_utils.py
  29. 1
      platforms/js/build_js.py
  30. 1
      platforms/wince/readme.md
  31. 1
      platforms/winpack_dldt/build_package.py
  32. 8
      samples/_winpack_run_python_sample.cmd
  33. 7
      samples/dnn/download_models.py
  34. 5
      samples/dnn/object_detection.py
  35. 10
      samples/python/browse.py
  36. 10
      samples/python/camshift.py
  37. 10
      samples/python/coherence.py
  38. 19
      samples/python/common.py
  39. 12
      samples/python/contours.py
  40. 30
      samples/python/demo.py
  41. 14
      samples/python/digits_adjust.py
  42. 15
      samples/python/fitline.py
  43. 10
      samples/python/gaussian_mix.py
  44. 8
      samples/python/kalman.py
  45. 14
      samples/python/lappyr.py
  46. 23
      samples/python/morphology.py
  47. 10
      samples/python/mosse.py
  48. 10
      samples/python/plane_tracker.py
  49. 10
      samples/python/qrcode.py
  50. 12
      samples/python/squares.py
  51. 14
      samples/python/turing.py

@ -21,7 +21,6 @@ jobs:
crossbuild-essential-arm64 \
git \
cmake \
libpython-dev:arm64 \
libpython3-dev:arm64 \
python-numpy \
python3-numpy
@ -34,10 +33,7 @@ jobs:
run: |
mkdir build
cd build
cmake -DPYTHON2_INCLUDE_PATH=/usr/include/python2.7/ \
-DPYTHON2_LIBRARIES=/usr/lib/aarch64-linux-gnu/libpython2.7.so \
-DPYTHON2_NUMPY_INCLUDE_DIRS=/usr/lib/python2.7/dist-packages/numpy/core/include \
-DPYTHON3_INCLUDE_PATH=/usr/include/python3.6m/ \
cmake -DPYTHON3_INCLUDE_PATH=/usr/include/python3.6m/ \
-DPYTHON3_LIBRARIES=/usr/lib/aarch64-linux-gnu/libpython3.6m.so \
-DPYTHON3_NUMPY_INCLUDE_DIRS=/usr/lib/python3/dist-packages/numpy/core/include \
-DCMAKE_TOOLCHAIN_FILE=../platforms/linux/aarch64-gnu.toolchain.cmake \

@ -1778,19 +1778,6 @@ if(WITH_CANN)
endif()
# ========================== python ==========================
if(BUILD_opencv_python2)
status("")
status(" Python 2:")
status(" Interpreter:" PYTHON2INTERP_FOUND THEN "${PYTHON2_EXECUTABLE} (ver ${PYTHON2_VERSION_STRING})" ELSE NO)
if(PYTHON2LIBS_VERSION_STRING)
status(" Libraries:" HAVE_opencv_python2 THEN "${PYTHON2_LIBRARIES} (ver ${PYTHON2LIBS_VERSION_STRING})" ELSE NO)
else()
status(" Libraries:" HAVE_opencv_python2 THEN "${PYTHON2_LIBRARIES}" ELSE NO)
endif()
status(" numpy:" PYTHON2_NUMPY_INCLUDE_DIRS THEN "${PYTHON2_NUMPY_INCLUDE_DIRS} (ver ${PYTHON2_NUMPY_VERSION})" ELSE "NO (Python wrappers can not be generated)")
status(" install path:" HAVE_opencv_python2 THEN "${__INSTALL_PATH_PYTHON2}" ELSE "-")
endif()
if(BUILD_opencv_python3)
status("")
status(" Python 3:")

@ -85,11 +85,7 @@ if(NOT ${found})
endif()
ocv_clear_vars(PYTHONINTERP_FOUND PYTHON_EXECUTABLE PYTHON_VERSION_STRING PYTHON_VERSION_MAJOR PYTHON_VERSION_MINOR PYTHON_VERSION_PATCH)
if(NOT CMAKE_VERSION VERSION_LESS "3.12")
if(_python_version_major STREQUAL "2")
set(__PYTHON_PREFIX Python2)
else()
set(__PYTHON_PREFIX Python3)
endif()
set(__PYTHON_PREFIX Python3)
find_host_package(${__PYTHON_PREFIX} "${preferred_version}" COMPONENTS Interpreter)
if(${__PYTHON_PREFIX}_EXECUTABLE)
set(PYTHON_EXECUTABLE "${${__PYTHON_PREFIX}_EXECUTABLE}")
@ -208,9 +204,6 @@ if(NOT ${found})
if(CMAKE_CROSSCOMPILING)
message(STATUS "Cannot probe for Python/Numpy support (because we are cross-compiling OpenCV)")
message(STATUS "If you want to enable Python/Numpy support, set the following variables:")
message(STATUS " PYTHON2_INCLUDE_PATH")
message(STATUS " PYTHON2_LIBRARIES (optional on Unix-like systems)")
message(STATUS " PYTHON2_NUMPY_INCLUDE_DIRS")
message(STATUS " PYTHON3_INCLUDE_PATH")
message(STATUS " PYTHON3_LIBRARIES (optional on Unix-like systems)")
message(STATUS " PYTHON3_NUMPY_INCLUDE_DIRS")
@ -268,14 +261,6 @@ if(OPENCV_PYTHON_SKIP_DETECTION)
return()
endif()
find_python("" "${MIN_VER_PYTHON2}" PYTHON2_LIBRARY PYTHON2_INCLUDE_DIR
PYTHON2INTERP_FOUND PYTHON2_EXECUTABLE PYTHON2_VERSION_STRING
PYTHON2_VERSION_MAJOR PYTHON2_VERSION_MINOR PYTHON2LIBS_FOUND
PYTHON2LIBS_VERSION_STRING PYTHON2_LIBRARIES PYTHON2_LIBRARY
PYTHON2_DEBUG_LIBRARIES PYTHON2_LIBRARY_DEBUG PYTHON2_INCLUDE_PATH
PYTHON2_INCLUDE_DIR PYTHON2_INCLUDE_DIR2 PYTHON2_PACKAGES_PATH
PYTHON2_NUMPY_INCLUDE_DIRS PYTHON2_NUMPY_VERSION)
option(OPENCV_PYTHON3_VERSION "Python3 version" "")
find_python("${OPENCV_PYTHON3_VERSION}" "${MIN_VER_PYTHON3}" PYTHON3_LIBRARY PYTHON3_INCLUDE_DIR
PYTHON3INTERP_FOUND PYTHON3_EXECUTABLE PYTHON3_VERSION_STRING
@ -285,15 +270,9 @@ find_python("${OPENCV_PYTHON3_VERSION}" "${MIN_VER_PYTHON3}" PYTHON3_LIBRARY PYT
PYTHON3_INCLUDE_DIR PYTHON3_INCLUDE_DIR2 PYTHON3_PACKAGES_PATH
PYTHON3_NUMPY_INCLUDE_DIRS PYTHON3_NUMPY_VERSION)
if(PYTHON_DEFAULT_EXECUTABLE)
set(PYTHON_DEFAULT_AVAILABLE "TRUE")
elseif(PYTHON2_EXECUTABLE AND PYTHON2INTERP_FOUND)
# Use Python 2 as default Python interpreter
set(PYTHON_DEFAULT_AVAILABLE "TRUE")
set(PYTHON_DEFAULT_EXECUTABLE "${PYTHON2_EXECUTABLE}")
elseif(PYTHON3_EXECUTABLE AND PYTHON3INTERP_FOUND)
# Use Python 3 as fallback Python interpreter (if there is no Python 2)
set(PYTHON_DEFAULT_AVAILABLE "TRUE")
set(PYTHON_DEFAULT_EXECUTABLE "${PYTHON3_EXECUTABLE}")
endif()

@ -3,6 +3,5 @@ if(NOT DEFINED MIN_VER_CMAKE)
endif()
set(MIN_VER_CUDA 6.5)
set(MIN_VER_CUDNN 7.5)
set(MIN_VER_PYTHON2 2.7)
set(MIN_VER_PYTHON3 3.2)
set(MIN_VER_ZLIB 1.2.3)

@ -544,7 +544,6 @@ function(__ocv_resolve_dependencies)
foreach(the_module ${OPENCV_MODULES_BUILD})
foreach (wrapper ${OPENCV_MODULE_${the_module}_WRAPPERS})
if(wrapper STREQUAL "python") # hack for python (BINDINDS)
ocv_add_dependencies(opencv_python2 OPTIONAL ${the_module})
ocv_add_dependencies(opencv_python3 OPTIONAL ${the_module})
else()
ocv_add_dependencies(opencv_${wrapper} OPTIONAL ${the_module})

@ -13,7 +13,6 @@ ocv_update(WITH_VA OFF)
ocv_update(WITH_VA_INTEL OFF)
# Disable bindings
ocv_update(BUILD_opencv_python2 OFF)
ocv_update(BUILD_opencv_python3 OFF)
ocv_update(BUILD_JAVA OFF)
ocv_update(BUILD_opencv_java OFF)

@ -1,5 +1,3 @@
from __future__ import print_function
import os, tempfile, numpy as np
import sys

@ -108,7 +108,7 @@ You can verify it with any image editing tools like GIMP.
### Method 3 : OpenCV sample style !!
There is a sample code for color-histogram in OpenCV-Python2 samples
There is a sample code for color-histogram in OpenCV-Python samples
(samples/python/color_histogram.py).
If you run the code, you can see the histogram shows the corresponding color also.
Or simply it outputs a color coded histogram.

@ -157,7 +157,7 @@ should be due to the sky)
Well, here you adjust the values of histograms along with its bin values to look like x,y
coordinates so that you can draw it using cv.line() or cv.polyline() function to generate same
image as above. This is already available with OpenCV-Python2 official samples. Check the
image as above. This is already available with OpenCV-Python official samples. Check the
code at samples/python/hist.py.
Application of Mask

@ -1,6 +1,9 @@
Install OpenCV-Python in Fedora {#tutorial_py_setup_in_fedora}
===============================
@warning
The instruction is deprecated. Please use OpenCV-Python package instead. See https://github.com/opencv/opencv-python for more details
Goals
-----

@ -64,12 +64,6 @@ We need **CMake** to configure the installation, **GCC** for compilation, **Pyth
sudo apt-get install cmake
sudo apt-get install gcc g++
```
to support python2:
```
sudo apt-get install python-dev python-numpy
```
to support python3:
```
@ -154,12 +148,6 @@ For additional information about CMake options refer to OpenCV @ref tutorial_lin
You should see these lines in your CMake output (they mean that Python is properly found):
```
-- Python 2:
-- Interpreter: /usr/bin/python2.7 (ver 2.7.6)
-- Libraries: /usr/lib/x86_64-linux-gnu/libpython2.7.so (ver 2.7.6)
-- numpy: /usr/lib/python2.7/dist-packages/numpy/core/include (ver 1.8.2)
-- packages path: lib/python2.7/dist-packages
--
-- Python 3:
-- Interpreter: /usr/bin/python3.4 (ver 3.4.3)
-- Libraries: /usr/lib/x86_64-linux-gnu/libpython3.4m.so (ver 3.4.3)

@ -1,6 +1,9 @@
Install OpenCV-Python in Windows {#tutorial_py_setup_in_windows}
================================
@warning
The instruction is deprecated. Please use OpenCV-Python package instead. See https://github.com/opencv/opencv-python for more details
Goals
-----

@ -573,7 +573,6 @@ Following options can be used to change installation layout for common scenarios
| `ENABLE_FLAKE8` | _ON_ (when docs or examples are enabled) | Enable python scripts check with [Flake8](https://flake8.pycqa.org/) (_check_flake8_ target). Flake8 must be installed. |
| `BUILD_JAVA` | _ON_ | Enable Java wrappers build. Java SDK and Ant must be installed. |
| `BUILD_FAT_JAVA_LIB` | _ON_ (for static Android builds) | Build single _opencv_java_ dynamic library containing all library functionality bundled with Java bindings. |
| `BUILD_opencv_python2` | _ON_ | Build python2 bindings (deprecated). Python with development files and numpy must be installed. |
| `BUILD_opencv_python3` | _ON_ | Build python3 bindings. Python with development files and numpy must be installed. |
TODO: need separate tutorials covering bindings builds

@ -109,8 +109,6 @@ Building OpenCV from Source Using CMake
- `PYTHON3_INCLUDE_DIR = /usr/include/python<version>`
- `PYTHON3_NUMPY_INCLUDE_DIRS =
/usr/lib/python<version>/dist-packages/numpy/core/include/`
@note
To specify Python2 versions, you can replace `PYTHON3_` with `PYTHON2_` in the above parameters.
-# Build. From build directory execute *make*, it is recommended to do this in several threads

@ -4,13 +4,9 @@
if(DEFINED OPENCV_INITIAL_PASS) # OpenCV build
if(ANDROID OR APPLE_FRAMEWORK OR WINRT)
ocv_module_disable_(python2)
ocv_module_disable_(python3)
return()
elseif(BUILD_opencv_world OR (WIN32 AND CMAKE_BUILD_TYPE STREQUAL "Debug"))
if(NOT DEFINED BUILD_opencv_python2)
set(__disable_python2 ON)
endif()
if(NOT DEFINED BUILD_opencv_python3)
set(__disable_python3 ON)
endif()
@ -20,17 +16,11 @@ add_subdirectory(bindings)
add_subdirectory(test)
if(__disable_python2)
ocv_module_disable_(python2)
endif()
if(__disable_python3)
ocv_module_disable_(python3)
endif()
if(__disable_python2 AND __disable_python3)
return()
endif()
add_subdirectory(python2)
add_subdirectory(python3)
else() # standalone build

@ -1,15 +0,0 @@
if(NOT PYTHON2_INCLUDE_PATH OR NOT PYTHON2_NUMPY_INCLUDE_DIRS)
ocv_module_disable(python2)
endif()
set(the_description "The python2 bindings")
set(MODULE_NAME python2)
# Buildbot requires Python 2 to be in root lib dir
set(MODULE_INSTALL_SUBDIR "")
set(PYTHON PYTHON2)
include(../common.cmake)
unset(MODULE_NAME)
unset(MODULE_INSTALL_SUBDIR)

@ -42,7 +42,6 @@ sum::Size_MatType::(Y, X)
32FC1 0.05 ms 1.77 ms 5.23 ms 11.72 ms
"""
from __future__ import print_function
import testlog_parser, sys, os, xml, re
from table_formatter import *
from optparse import OptionParser

@ -22,7 +22,6 @@ opencv Normalize::OCL_NormalizeFixture 5.412 96
... ... ... ...
"""
from __future__ import print_function
import testlog_parser, sys, os, xml, glob, re
from table_formatter import *
from optparse import OptionParser

@ -34,7 +34,6 @@ RadiusMatch::OCL_BruteForceMatcherFixture::(640x480, 32FC1) 1372.68 ms 1375.52 m
--show-all - also include empty and "notrun" lines
"""
from __future__ import print_function
import testlog_parser, sys, os, xml, re, glob
from table_formatter import *
from optparse import OptionParser

@ -2,7 +2,6 @@
""" Utility package for run.py
"""
from __future__ import print_function
import xml.etree.ElementTree as ET
from glob import glob
from pprint import PrettyPrinter as PP

@ -73,7 +73,7 @@ class TestSuite(object):
return set(res)
def isTest(self, fullpath):
if fullpath in ['java', 'python2', 'python3']:
if fullpath in ['java', 'python3']:
return self.options.mode == 'test'
if not os.path.isfile(fullpath):
return False
@ -123,7 +123,7 @@ class TestSuite(object):
cmd += ["buildAndTest"]
ret = execute(cmd, cwd=self.cache.java_test_dir)
return None, ret
elif module in ['python2', 'python3']:
elif module == 'python3':
executable = os.getenv('OPENCV_PYTHON_BINARY', None)
if executable is None or module == 'python{}'.format(sys.version_info[0]):
executable = sys.executable
@ -181,7 +181,7 @@ class TestSuite(object):
more_args = []
exe = self.getTest(test)
if exe in ["java", "python2", "python3"]:
if exe in ["java", "python3"]:
logname = None
else:
userlog = [a for a in args if a.startswith("--gtest_output=")]

@ -92,7 +92,6 @@ parse_patterns = (
{'name': "java_test_dir", 'default': None, 'pattern': re.compile(r"^OPENCV_JAVA_TEST_DIR:\w+=(.*)$")},
{'name': "is_x64", 'default': "OFF", 'pattern': re.compile(r"^CUDA_64_BIT_DEVICE_CODE:\w+=(ON)$")},
{'name': "cmake_generator", 'default': None, 'pattern': re.compile(r"^CMAKE_GENERATOR:\w+=(.+)$")},
{'name': "python2", 'default': None, 'pattern': re.compile(r"^BUILD_opencv_python2:\w+=(.*)$")},
{'name': "python3", 'default': None, 'pattern': re.compile(r"^BUILD_opencv_python3:\w+=(.*)$")},
)
@ -153,22 +152,17 @@ class CMakeCache:
files = glob.glob(os.path.join(d, mask))
if not self.getOS() == "android" and self.withJava():
files.append("java")
if self.withPython2():
files.append("python2")
if self.withPython3():
files.append("python3")
return [f for f in files if isGood(f)]
return []
def isMainModule(self, name):
return name in self.main_modules + ['python2', 'python3']
return name in self.main_modules + ['python3']
def withJava(self):
return self.ant_executable and self.java_test_dir and os.path.exists(self.java_test_dir)
def withPython2(self):
return self.python2 == 'ON'
def withPython3(self):
return self.python3 == 'ON'

@ -32,7 +32,6 @@ LUT::OCL_LUTFixture::(640x480, 32FC4) 21.254 4.296 4.95
LUT::SizePrm::640x480 2.268 0.687 3.30
"""
from __future__ import print_function
import testlog_parser, sys, os, xml, glob, re
from table_formatter import *
from optparse import OptionParser

@ -4,12 +4,8 @@
This module serves as utility for other scripts.
"""
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 html import escape
from optparse import OptionParser
from color import getColorizer, dummyColorizer
@ -215,12 +211,8 @@ class table(object):
cell.width = len(max(cell.text, key = lambda line: len(line)))
def reformatTextValue(self, value):
if sys.version_info >= (2,7):
unicode = str
if isinstance(value, str):
vstr = value
elif isinstance(value, unicode):
vstr = str(value)
else:
try:
vstr = '\n'.join([str(v) for v in value])

@ -3,16 +3,13 @@
This module serves as utility for other scripts.
"""
from __future__ import print_function
import collections
import re
import os.path
import sys
from xml.dom.minidom import parse
if sys.version_info > (3,):
long = int
def cmp(a, b): return (a>b)-(a<b)
def cmp(a, b): return (a>b)-(a<b)
class TestInfo(object):
@ -59,9 +56,9 @@ class TestInfo(object):
def parseLongMetric(self, xmlnode, name, default = 0):
if name in self.properties:
self.metrix[name] = long(self.properties[name])
self.metrix[name] = int(self.properties[name])
elif xmlnode.hasAttribute(name):
self.metrix[name] = long(xmlnode.getAttribute(name))
self.metrix[name] = int(xmlnode.getAttribute(name))
else:
self.metrix[name] = default
@ -117,8 +114,8 @@ class TestInfo(object):
if units == "ns":
scale = 1000000000.0
if units == "ticks":
frequency = long(1)
scale = long(1)
frequency = int(1)
scale = int(1)
return val * scale / frequency
return val

@ -26,19 +26,12 @@ See https://github.com/opencv/opencv/wiki/Profiling-OpenCV-Applications for more
0.173 ...
"""
from __future__ import print_function
import os
import sys
import csv
from pprint import pprint
from collections import deque
try:
long # Python 2
except NameError:
long = int # Python 3
# trace.hpp
REGION_FLAG_IMPL_MASK = 15 << 16
REGION_FLAG_IMPL_IPP = 1 << 16
@ -65,11 +58,6 @@ def tryNum(s):
return int(s)
except ValueError:
pass
if sys.version_info[0] < 3:
try:
return long(s)
except ValueError:
pass
return s
def formatTimestamp(t):

@ -74,8 +74,6 @@
Finally, run the script. Use the --help option for usage information.
"""
from __future__ import division
import ast
import errno
import fnmatch

@ -1,6 +1,6 @@
#!/usr/bin/env python
"""
Common utilities. These should be compatible with Python 2 and 3.
Common utilities. These should be compatible with Python3.
"""
from __future__ import print_function

@ -137,7 +137,6 @@ class Builder:
"-DBUILD_opencv_stitching=OFF",
"-DBUILD_opencv_java=OFF",
"-DBUILD_opencv_js=ON",
"-DBUILD_opencv_python2=OFF",
"-DBUILD_opencv_python3=OFF",
"-DBUILD_EXAMPLES=ON",
"-DBUILD_PACKAGE=OFF",

@ -38,7 +38,6 @@ For headless WEC2013, this configuration may not be limited to but is known to w
-DBUILD_opencv_videostab=OFF `
-DBUILD_opencv_dnn=OFF `
-DBUILD_opencv_java=OFF `
-DBUILD_opencv_python2=OFF `
-DBUILD_opencv_python3=OFF `
-DBUILD_opencv_java_bindings_generator=OFF `
-DBUILD_opencv_python_bindings_generator=OFF `

@ -379,7 +379,6 @@ class Builder:
OPENCV_INSTALL_DATA_DIR_RELATIVE='../../src/opencv',
BUILD_opencv_python2='OFF',
BUILD_opencv_python3='ON',
PYTHON3_LIMITED_API='ON',
OPENCV_PYTHON_INSTALL_PATH='python',

@ -67,12 +67,12 @@ ECHO Found Python %PY_VERSION% from Windows Registry: %PYTHON%
ENDLOCAL & SET PYTHON=%PYTHON%
EXIT /B 0
IF exist C:\Python27-x64\python.exe (
SET PYTHON=C:\Python27-x64\python.exe
IF exist C:\Python36-x64\python.exe (
SET PYTHON=C:\Python36-x64\python.exe
GOTO :PYTHON_FOUND
)
IF exist C:\Python27\python.exe (
SET PYTHON=C:\Python27\python.exe
IF exist C:\Python36\python.exe (
SET PYTHON=C:\Python36\python.exe
GOTO :PYTHON_FOUND
)

@ -15,10 +15,7 @@ import requests
import shutil
from pathlib import Path
from datetime import datetime
if sys.version_info[0] < 3:
from urllib2 import urlopen
else:
from urllib.request import urlopen
from urllib.request import urlopen
import xml.etree.ElementTree as ET
__all__ = ["downloadFile"]
@ -361,4 +358,4 @@ if __name__ == '__main__':
if selected_model_name and not m.name.startswith(selected_model_name):
continue
print('Model: ' + selected_model_name)
m.get()
m.get()

@ -4,10 +4,7 @@ import numpy as np
import sys
import time
from threading import Thread
if sys.version_info[0] == 2:
import Queue as queue
else:
import queue
import queue
from common import *
from tf_text_graph_common import readTextMessage

@ -12,14 +12,6 @@ browse.py [image filename]
'''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np
import cv2 as cv
@ -45,7 +37,7 @@ def main():
small = img
for _i in xrange(3):
for _i in range(3):
small = cv.pyrDown(small)
def onmouse(event, x, y, flags, param):

@ -22,14 +22,6 @@ Keys:
b - toggle back-projected probability visualization
'''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np
import cv2 as cv
@ -68,7 +60,7 @@ class App(object):
bin_count = self.hist.shape[0]
bin_w = 24
img = np.zeros((256, bin_count*bin_w, 3), np.uint8)
for i in xrange(bin_count):
for i in range(bin_count):
h = int(self.hist[i])
cv.rectangle(img, (i*bin_w+2, 255), ((i+1)*bin_w-2, 255-h), (int(180.0*i/bin_count), 255, 255), -1)
img = cv.cvtColor(img, cv.COLOR_HSV2BGR)

@ -9,21 +9,13 @@ inspired by
http://www.mia.uni-saarland.de/Publications/weickert-dagm03.pdf
'''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np
import cv2 as cv
def coherence_filter(img, sigma = 11, str_sigma = 11, blend = 0.5, iter_n = 4):
h, w = img.shape[:2]
for i in xrange(iter_n):
for i in range(iter_n):
print(i)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

@ -4,14 +4,7 @@
This module contains some common routines used by other samples.
'''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
from functools import reduce
from functools import reduce
import numpy as np
import cv2 as cv
@ -202,10 +195,7 @@ class RectSelector:
def grouper(n, iterable, fillvalue=None):
'''grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx'''
args = [iter(iterable)] * n
if PY3:
output = it.zip_longest(fillvalue=fillvalue, *args)
else:
output = it.izip_longest(fillvalue=fillvalue, *args)
output = it.zip_longest(fillvalue=fillvalue, *args)
return output
def mosaic(w, imgs):
@ -215,10 +205,7 @@ def mosaic(w, imgs):
imgs -- images (must have same size and format)
'''
imgs = iter(imgs)
if PY3:
img0 = next(imgs)
else:
img0 = imgs.next()
img0 = next(imgs)
pad = np.zeros_like(img0)
imgs = it.chain([img0], imgs)
rows = grouper(w, imgs, pad)

@ -9,26 +9,18 @@ Usage:
A trackbar is put up which controls the contour level from -3 to 3
'''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
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
for i in xrange(6):
for i in range(6):
dx = int((i%2)*250 - 30)
dy = int((i/2.)*150)
if i == 0:
for j in xrange(11):
for j in range(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])

@ -4,8 +4,6 @@
Sample-launcher application.
'''
# Python 2/3 compatibility
from __future__ import print_function
import sys
# local modules
@ -16,13 +14,8 @@ import webbrowser
from glob import glob
from subprocess import Popen
try:
import tkinter as tk # Python 3
from tkinter.scrolledtext import ScrolledText
except ImportError:
import Tkinter as tk # Python 2
from ScrolledText import ScrolledText
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
#from IPython.Shell import IPShellEmbed
#ipshell = IPShellEmbed()
@ -117,19 +110,12 @@ class App:
descr = ""
try:
if sys.version_info[0] > 2:
# Python 3.x
module_globals = {}
module_locals = {}
with open(fn, 'r') as f:
module_code = f.read()
exec(compile(module_code, fn, 'exec'), module_globals, module_locals)
descr = module_locals.get('__doc__', 'no-description')
else:
# Python 2
module_globals = {}
execfile(fn, module_globals) # noqa: F821
descr = module_globals.get('__doc__', 'no-description')
module_globals = {}
module_locals = {}
with open(fn, 'r') as f:
module_code = f.read()
exec(compile(module_code, fn, 'exec'), module_globals, module_locals)
descr = module_locals.get('__doc__', 'no-description')
except Exception as e:
descr = str(e)

@ -13,14 +13,6 @@ Usage:
'''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np
import cv2 as cv
@ -45,9 +37,9 @@ def cross_validate(model_class, params, samples, labels, kfold = 3, pool = None)
print(".", end='')
return score
if pool is None:
scores = list(map(f, xrange(kfold)))
scores = list(map(f, range(kfold)))
else:
scores = pool.map(f, xrange(kfold))
scores = pool.map(f, range(kfold))
return np.mean(scores)
@ -108,7 +100,7 @@ class App(object):
err = cross_validate(KNearest, dict(k=k), samples, labels)
return k, err
best_err, best_k = np.inf, -1
for k, err in self.run_jobs(f, xrange(1, 9)):
for k, err in self.run_jobs(f, range(1, 9)):
if err < best_err:
best_err, best_k = err, k
print('k = %d, error: %.2f %%' % (k, err*100))

@ -22,11 +22,6 @@ f - change distance function
ESC - exit
'''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
import numpy as np
import cv2 as cv
@ -49,10 +44,7 @@ def sample_line(p1, p2, n, noise=0.0):
dist_func_names = it.cycle('DIST_L2 DIST_L1 DIST_L12 DIST_FAIR DIST_WELSCH DIST_HUBER'.split())
if PY3:
cur_func_name = next(dist_func_names)
else:
cur_func_name = dist_func_names.next()
cur_func_name = next(dist_func_names)
def update(_=None):
noise = cv.getTrackbarPos('noise', 'fit line')
@ -89,10 +81,7 @@ def main():
ch = cv.waitKey(0)
if ch == ord('f'):
global cur_func_name
if PY3:
cur_func_name = next(dist_func_names)
else:
cur_func_name = dist_func_names.next()
cur_func_name = next(dist_func_names)
if ch == 27:
break

@ -1,13 +1,5 @@
#!/usr/bin/env python
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np
import cv2 as cv
@ -16,7 +8,7 @@ from numpy import random
def make_gaussians(cluster_n, img_size):
points = []
ref_distrs = []
for _i in xrange(cluster_n):
for _i in range(cluster_n):
mean = (0.1 + 0.8*random.rand(2)) * img_size
a = (random.rand(2, 2)-0.5)*img_size*0.1
cov = np.dot(a.T, a) + img_size*0.05*np.eye(2)

@ -15,12 +15,6 @@
Pressing any key (except ESC) will reset the tracking.
Pressing ESC will stop the program.
"""
# Python 2/3 compatibility
import sys
PY3 = sys.version_info[0] == 3
if PY3:
long = int
import numpy as np
import cv2 as cv
@ -32,7 +26,7 @@ def main():
img_width = 500
kalman = cv.KalmanFilter(2, 1, 0)
code = long(-1)
code = -1
num_circle_steps = 12
while True:
img = np.zeros((img_height, img_width, 3), np.uint8)

@ -12,14 +12,6 @@ References:
Alexander Mordvintsev 6/10/12
'''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np
import cv2 as cv
@ -29,7 +21,7 @@ from common import nothing, getsize
def build_lappyr(img, leveln=6, dtype=np.int16):
img = dtype(img)
levels = []
for _i in xrange(leveln-1):
for _i in range(leveln-1):
next_img = cv.pyrDown(img)
img1 = cv.pyrUp(next_img, dstsize=getsize(img))
levels.append(img-img1)
@ -56,14 +48,14 @@ def main():
leveln = 6
cv.namedWindow('level control')
for i in xrange(leveln):
for i in range(leveln):
cv.createTrackbar('%d'%i, 'level control', 5, 50, nothing)
while True:
_ret, frame = cap.read()
pyr = build_lappyr(frame, leveln)
for i in xrange(leveln):
for i in range(leveln):
v = int(cv.getTrackbarPos('%d'%i, 'level control') / 5)
pyr[i] *= v
res = merge_lappyr(pyr)

@ -12,11 +12,6 @@ Keys:
ESC - exit
'''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
import numpy as np
import cv2 as cv
@ -42,12 +37,8 @@ def main():
modes = cycle(['erode/dilate', 'open/close', 'blackhat/tophat', 'gradient'])
str_modes = cycle(['ellipse', 'rect', 'cross'])
if PY3:
cur_mode = next(modes)
cur_str_mode = next(str_modes)
else:
cur_mode = modes.next()
cur_str_mode = str_modes.next()
cur_mode = next(modes)
cur_str_mode = next(str_modes)
def update(dummy=None):
try: # do not get trackbar position while trackbar is not created
@ -84,15 +75,9 @@ def main():
if ch == 27:
break
if ch == ord('1'):
if PY3:
cur_mode = next(modes)
else:
cur_mode = modes.next()
cur_mode = next(modes)
if ch == ord('2'):
if PY3:
cur_str_mode = next(str_modes)
else:
cur_str_mode = str_modes.next()
cur_str_mode = next(str_modes)
update()
print('Done')

@ -21,14 +21,6 @@ Keys:
http://www.cs.colostate.edu/~draper/papers/bolme_cvpr10.pdf
'''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np
import cv2 as cv
from common import draw_str, RectSelector
@ -73,7 +65,7 @@ class MOSSE:
self.G = cv.dft(g, flags=cv.DFT_COMPLEX_OUTPUT)
self.H1 = np.zeros_like(self.G)
self.H2 = np.zeros_like(self.G)
for _i in xrange(128):
for _i in range(128):
a = self.preprocess(rnd_warp(img))
A = cv.dft(a, flags=cv.DFT_COMPLEX_OUTPUT)
self.H1 += cv.mulSpectrums(self.G, A, 0, conjB=True)

@ -21,14 +21,6 @@ Keys:
Select a textured planar object to track by drawing a box with a mouse.
'''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np
import cv2 as cv
@ -104,7 +96,7 @@ class PlaneTracker:
matches = [m[0] for m in matches if len(m) == 2 and m[0].distance < m[1].distance * 0.75]
if len(matches) < MIN_MATCH_COUNT:
return []
matches_by_id = [[] for _ in xrange(len(self.targets))]
matches_by_id = [[] for _ in range(len(self.targets))]
for m in matches:
matches_by_id[m.imgIdx].append(m)
tracked = []

@ -7,20 +7,10 @@ Usage:
qrcode.py
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2 as cv
import argparse
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
class QrSample:
def __init__(self, args):

@ -6,14 +6,6 @@ Simple "Square Detector" program.
Loads several images sequentially and tries to find squares in each image.
'''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np
import cv2 as cv
@ -26,7 +18,7 @@ def find_squares(img):
img = cv.GaussianBlur(img, (5, 5), 0)
squares = []
for gray in cv.split(img):
for thrs in xrange(0, 255, 26):
for thrs in range(0, 255, 26):
if thrs == 0:
bin = cv.Canny(gray, 0, 50, apertureSize=5)
bin = cv.dilate(bin, None)
@ -38,7 +30,7 @@ def find_squares(img):
cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True)
if len(cnt) == 4 and cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt):
cnt = cnt.reshape(-1, 2)
max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in range(4)])
if max_cos < 0.1:
squares.append(cnt)
return squares

@ -7,14 +7,6 @@ Multiscale Turing Patterns generator
Inspired by http://www.jonathanmccabe.com/Cyclic_Symmetric_Multi-Scale_Turing_Patterns.pdf
'''
# Python 2/3 compatibility
from __future__ import print_function
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np
import cv2 as cv
from common import draw_str
@ -45,7 +37,7 @@ def main():
def process_scale(a_lods, lod):
d = a_lods[lod] - cv.pyrUp(a_lods[lod+1])
for _i in xrange(lod):
for _i in range(lod):
d = cv.pyrUp(d)
v = cv.GaussianBlur(d*d, (3, 3), 0)
return np.sign(d), v
@ -53,10 +45,10 @@ def main():
scale_num = 6
for frame_i in count():
a_lods = [a]
for i in xrange(scale_num):
for i in range(scale_num):
a_lods.append(cv.pyrDown(a_lods[-1]))
ms, vs = [], []
for i in xrange(1, scale_num):
for i in range(1, scale_num):
m, v = process_scale(a_lods, i)
ms.append(m)
vs.append(v)

Loading…
Cancel
Save