Python cv2.__version__() Examples

The following are 30 code examples of cv2.__version__(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: PrerequisitesCheckerGramplet.py    From addons-source with GNU General Public License v2.0 6 votes vote down vote up
def check23_pedigreechart(self):
        '''PedigreeChart - Can optionally use - NumPy if installed

        https://github.com/gramps-project/addons-source/blob/master/PedigreeChart/PedigreeChart.py
        '''
        self.append_text("\n")
        self.render_text("""<b>03. <a href="https://gramps-project.org/wiki"""
                         """/index.php?title=PedigreeChart">"""
                         """Addon:PedigreeChart</a> :</b> """)
        # Start check

        try:
            import numpy
            numpy_ver = str(numpy.__version__)
            #print("numpy.__version__ :" + numpy_ver )
            # NUMPY_check = True
        except ImportError:
            numpy_ver = "Not found"
            # NUMPY_check = False

        result = "(NumPy : " + numpy_ver + " )"
        # End check
        self.append_text(result)
        #self.append_text("\n") 
Example #2
Source File: siammask_tracker.py    From pysot with Apache License 2.0 6 votes vote down vote up
def _mask_post_processing(self, mask):
        target_mask = (mask > cfg.TRACK.MASK_THERSHOLD)
        target_mask = target_mask.astype(np.uint8)
        if cv2.__version__[-5] == '4':
            contours, _ = cv2.findContours(target_mask,
                                           cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_NONE)
        else:
            _, contours, _ = cv2.findContours(target_mask,
                                              cv2.RETR_EXTERNAL,
                                              cv2.CHAIN_APPROX_NONE)
        cnt_area = [cv2.contourArea(cnt) for cnt in contours]
        if len(contours) != 0 and np.max(cnt_area) > 100:
            contour = contours[np.argmax(cnt_area)]
            polygon = contour.reshape(-1, 2)
            prbox = cv2.boxPoints(cv2.minAreaRect(polygon))
            rbox_in_img = prbox
        else:  # empty mask
            location = cxy_wh_2_rect(self.center_pos, self.size)
            rbox_in_img = np.array([[location[0], location[1]],
                                    [location[0] + location[2], location[1]],
                                    [location[0] + location[2], location[1] + location[3]],
                                    [location[0], location[1] + location[3]]])
        return rbox_in_img 
Example #3
Source File: test.py    From yolo_v1_tensorflow_guiyu with MIT License 6 votes vote down vote up
def draw_result(self, img, result):   #输出结果
        print("hell")
        print(len(result))
        for i in range(len(result)):
            x = int(result[i][1])
            y = int(result[i][2])
            w = int(result[i][3] / 2)
            h = int(result[i][4] / 2)
            cv2.rectangle(img, (x - w, y - h), (x + w, y + h), (0, 255, 0), 2)
            cv2.rectangle(img, (x - w, y - h - 20),
                          (x + w, y - h), (125, 125, 125), -1)
            lineType = cv2.LINE_AA if cv2.__version__ > '3' else cv2.CV_AA
            cv2.putText(
                img, result[i][0] + ' : %.2f' % result[i][5],
                (x - w + 5, y - h - 7), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                (0, 0, 0), 1, lineType) 
Example #4
Source File: siam_mask_tracker.py    From models with MIT License 6 votes vote down vote up
def _mask_post_processing(mask, center_pos, size, track_mask_threshold):
    target_mask = (mask > track_mask_threshold)
    target_mask = target_mask.astype(np.uint8)
    if cv2.__version__[-5] == '4':
        contours, _ = cv2.findContours(target_mask,
                                       cv2.RETR_EXTERNAL,
                                       cv2.CHAIN_APPROX_NONE)
    else:
        _, contours, _ = cv2.findContours(
                target_mask,
                cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    cnt_area = [cv2.contourArea(cnt) for cnt in contours]
    if len(contours) != 0 and np.max(cnt_area) > 100:
        contour = contours[np.argmax(cnt_area)] 
        polygon = contour.reshape(-1, 2)
        prbox = cv2.boxPoints(cv2.minAreaRect(polygon))
        rbox_in_img = prbox
    else:  # empty mask
        location = cxy_wh_2_rect(center_pos, size)
        rbox_in_img = np.array([[location[0], location[1]],
                    [location[0] + location[2], location[1]],
                    [location[0] + location[2], location[1] + location[3]],
                    [location[0], location[1] + location[3]]])
    return rbox_in_img 
Example #5
Source File: stitcher.py    From dual-fisheye-video-stitching with MIT License 6 votes vote down vote up
def detectAndDescribe(self, image):
        # check to see if we are using OpenCV 3.X
        if int(cv2.__version__[0]) >= 3:
            # detect and extract features from the image
            descriptor = cv2.xfeatures2d.SIFT_create()
            (kps, features) = descriptor.detectAndCompute(image, None)

        # otherwise, we are using OpenCV 2.4.X
        else:
            # convert the image to grayscale
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

            # detect keypoints in the image
            detector = cv2.FeatureDetector_create("SIFT")
            kps = detector.detect(gray)

            # extract features from the image
            extractor = cv2.DescriptorExtractor_create("SIFT")
            (kps, features) = extractor.compute(gray, kps)

        # convert the keypoints from KeyPoint objects to NumPy arrays
        kps = np.float32([kp.pt for kp in kps])

        # return a tuple of keypoints and features
        return (kps, features) 
Example #6
Source File: PrerequisitesCheckerGramplet.py    From addons-source with GNU General Public License v2.0 6 votes vote down vote up
def check_fontconfig(self):
        ''' The python-fontconfig library is used to support the Genealogical
        Symbols tab of the Preferences.  Without it Genealogical Symbols don't
        work '''
        try:
            import fontconfig
            vers = fontconfig.__version__
            if vers.startswith("0.5."):
                result = ("* python-fontconfig " + vers +
                          " (Success version 0.5.x is installed.)")
            else:
                result = ("* python-fontconfig " + vers +
                          " (Requires version 0.5.x)")
        except ImportError:
            result = "* python-fontconfig Not found, (Requires version 0.5.x)"
        # End check
        self.append_text(result)

    #Optional 
Example #7
Source File: PrerequisitesCheckerGramplet.py    From addons-source with GNU General Public License v2.0 6 votes vote down vote up
def check6_bsddb3(self):
        '''bsddb3 - Python Bindings for Oracle Berkeley DB

        requires Berkeley DB

        PY_BSDDB3_VER_MIN = (6, 0, 1) # 6.x series at least
        '''
        self.append_text("\n")
        # Start check

        try:
            import bsddb3 as bsddb
            bsddb_str = bsddb.__version__  # Python adaptation layer
            # Underlying DB library
            bsddb_db_str = str(bsddb.db.version()).replace(', ', '.')\
                .replace('(', '').replace(')', '')
        except ImportError:
            bsddb_str = 'not found'
            bsddb_db_str = 'not found'

        result = ("* Berkeley Database library (bsddb3: " + bsddb_db_str +
                  ") (Python-bsddb3 : " + bsddb_str + ")")
        # End check
        self.append_text(result) 
Example #8
Source File: setup.py    From vidgear with Apache License 2.0 6 votes vote down vote up
def test_opencv():
    """
    This function is workaround to 
    test if correct OpenCV Library version has already been installed
    on the machine or not. Returns True if previously not installed.
    """
    try:
        # import OpenCV Binaries
        import cv2

        # check whether OpenCV Binaries are 3.x+
        if parse_version(cv2.__version__) < parse_version("3"):
            raise ImportError(
                "Incompatible (< 3.0) OpenCV version-{} Installation found on this machine!".format(
                    parse_version(cv2.__version__)
                )
            )
    except ImportError:
        return True
    return False 
Example #9
Source File: tests.py    From SimpleCV2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_matchSIFTKeyPoints():
    try:
        import cv2
    except ImportError:
        pass
        return
    if not "2.4.3" in cv2.__version__:
        pass
        return
    img = Image("lenna")
    skp, tkp =  img.matchSIFTKeyPoints(img)
    if len(skp) == len(tkp):
        for i in range(len(skp)):
            if (skp[i].x == tkp[i].x and skp[i].y == tkp[i].y):
                pass
            else:
                assert False
    else:
        assert False 
Example #10
Source File: tests.py    From SimpleCV2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_getFREAKDescriptor():
    try:
        import cv2
    except ImportError:
        pass
    if '$Rev' in cv2.__version__:
        pass
    else:
        if int(cv2.__version__.replace('.','0'))>=20402:
            img = Image("lenna")
            flavors = ["SIFT", "SURF", "BRISK", "ORB", "STAR", "MSER", "FAST", "Dense"]
            for flavor in flavors:
                f, d = img.getFREAKDescriptor(flavor)
                if len(f) == 0:
                    assert False
                if d.shape[0] != len(f) and d.shape[1] != 64:
                    assert False
        else:
            pass
    pass 
Example #11
Source File: tests.py    From SimpleCV2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_keypoint_extraction():
    try:
        import cv2
    except:
        pass
        return

    img1 = Image("../sampleimages/KeypointTemplate2.png")
    img2 = Image("../sampleimages/KeypointTemplate2.png")
    img3 = Image("../sampleimages/KeypointTemplate2.png")
    img4 = Image("../sampleimages/KeypointTemplate2.png")

    kp1 = img1.findKeypoints()
    kp2 = img2.findKeypoints(highQuality=True)
    kp3 = img3.findKeypoints(flavor="STAR")
    if not cv2.__version__.startswith("$Rev:"):
        kp4 = img4.findKeypoints(flavor="BRISK")
        kp4.draw()
        if len(kp4) == 0:
            assert False
    kp1.draw()
    kp2.draw()
    kp3.draw()



    #TODO: Fix FAST binding
    #~ kp4 = img.findKeypoints(flavor="FAST",min_quality=10)
    if( len(kp1)==190 and
        len(kp2)==190 and
        len(kp3)==37
        #~ and len(kp4)==521
      ):
        pass
    else:
        assert False
    results = [img1,img2,img3]
    name_stem = "test_keypoint_extraction"
    perform_diff(results,name_stem,tolerance=4.0) 
Example #12
Source File: frame_extractor.py    From keras-video-classifier with MIT License 5 votes vote down vote up
def main():
    print(cv2.__version__)
    data_dir_path = '.././very_large_data'
    X, Y = scan_and_extract_videos_for_conv2d(data_dir_path)
    print(X[0].shape) 
Example #13
Source File: lung_cancer_utils.py    From sql_python_deep_learning with MIT License 5 votes vote down vote up
def print_library_version():
    print(os.getcwd())
    version_pandas = pkg_resources.get_distribution("pandas").version
    print("Version pandas: {}".format(version_pandas))
    print("Version OpenCV: {}".format(cv2.__version__))
    version_cntk = pkg_resources.get_distribution("cntk").version
    print("Version CNTK: {}".format(version_cntk))
    cntk.logging.set_trace_level(2)
    print("Devices used by CNTK: {}".format(cntk.all_devices()))



######################################################################
# for feature generation 
Example #14
Source File: utils.py    From AMNet with MIT License 5 votes vote down vote up
def ge_pkg_versions():

    dep_versions = {}
    cmd = 'cat /proc/driver/nvidia/version'
    display_driver = run_command(cmd)
    dep_versions['display'] = display_driver

    dep_versions['cuda'] = 'NA'
    cuda_home = '/usr/local/cuda/'
    if 'CUDA_HOME' in os.environ:
        cuda_home = os.environ['CUDA_HOME']

    cmd = cuda_home+'/version.txt'
    if os.path.isfile(cmd):
        cuda_version = run_command('cat '+cmd)

    dep_versions['cuda'] = cuda_version
    dep_versions['cudnn'] = torch.backends.cudnn.version()

    dep_versions['platform'] = platform.platform()
    dep_versions['python'] = sys.version_info[0]
    dep_versions['torch'] = torch.__version__
    dep_versions['numpy'] = np.__version__
    dep_versions['PIL'] = Image.VERSION

    dep_versions['OpenCV'] = 'NA'
    if 'cv2' in sys.modules:
        dep_versions['OpenCV'] = cv2.__version__

    dep_versions['torchvision'] = pkg_resources.get_distribution("torchvision").version

    return dep_versions 
Example #15
Source File: train_siammask_refine.py    From SiamMask with MIT License 5 votes vote down vote up
def collect_env_info():
    env_str = get_pretty_env_info()
    env_str += "\n        OpenCV ({})".format(cv2.__version__)
    return env_str 
Example #16
Source File: train_siammask.py    From SiamMask with MIT License 5 votes vote down vote up
def collect_env_info():
    env_str = get_pretty_env_info()
    env_str += "\n        OpenCV ({})".format(cv2.__version__)
    return env_str 
Example #17
Source File: train_siamrpn.py    From SiamMask with MIT License 5 votes vote down vote up
def collect_env_info():
    env_str = get_pretty_env_info()
    env_str += "\n        OpenCV ({})".format(cv2.__version__)
    return env_str 
Example #18
Source File: test_environment.py    From image-processing-pipeline with MIT License 5 votes vote down vote up
def test_opencv_version():
    assert cv2.__version__ >= '4.0' 
Example #19
Source File: blob_clustering.py    From aggregation with Apache License 2.0 5 votes vote down vote up
def __find_positive_regions__(self,user_ids,markings,dimensions):
        """
        give a set of polygon markings made by people, determine the area(s) in the image which were outlined
        by enough people. "positive" => true positive as opposed to noise or false positive
        """
        unique_users = set(user_ids)

        aggregate_polygon_list = []

        for i in unique_users:
            user_polygons = [markings[j] for j,u in enumerate(user_ids) if u == i]

            template = np.zeros(dimensions,np.uint8)

            # start by drawing the outline of the area
            cv2.polylines(template,user_polygons,True,255)

            # now take the EXTERNAL contour
            # the docker image has an older version of opencv where findcontours only returns 2 values
            if cv2.__version__ == '2.4.8':
                contours, hierarchy = cv2.findContours(template,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
            else:
                im2, contours, hierarchy = cv2.findContours(template,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
            template2 = np.zeros(dimensions,np.uint8)
            cv2.drawContours(template2,contours,-1,1,-1)

            aggregate_polygon_list.append(template2)

        aggregate_polygon = np.sum(aggregate_polygon_list,axis=0,dtype=np.uint8)

        # the threshold determines the minimum number of people who have outlined an area
        threshold = int(len(set(user_ids))/2)
        ret,thresh1 = cv2.threshold(aggregate_polygon,threshold,255,cv2.THRESH_BINARY)

        return thresh1 
Example #20
Source File: VideoCapture.py    From IntelligentEdgeHOL with MIT License 5 votes vote down vote up
def __init__(
            self,
            videoPath = "",
            verbose = True,
            videoW = 0,
            videoH = 0,
            fontScale = 1.0,
            inference = True,
            confidenceLevel = 0.5):

        self.videoPath = videoPath
        self.verbose = verbose
        self.videoW = videoW
        self.videoH = videoH
        self.inference = inference
        self.confidenceLevel = confidenceLevel
        self.useStream = False
        self.useMovieFile = False
        self.frameCount = 0
        self.vStream = None
        self.vCapture = None
        self.displayFrame = None
        self.fontScale = float(fontScale)
        self.captureInProgress = False

        print("VideoCapture::__init__()")
        print("OpenCV Version : %s" % (cv2.__version__))
        print("===============================================================")
        print("Initialising Video Capture with the following parameters: ")
        print("   - Video path      : " + self.videoPath)
        print("   - Video width     : " + str(self.videoW))
        print("   - Video height    : " + str(self.videoH))
        print("   - Font Scale      : " + str(self.fontScale))
        print("   - Inference?      : " + str(self.inference))
        print("   - ConficenceLevel : " + str(self.confidenceLevel))
        print("")

        self.imageServer = ImageServer(80, self)
        self.imageServer.start()

        self.yoloInference = YoloInference(self.fontScale) 
Example #21
Source File: common.py    From ADL with MIT License 5 votes vote down vote up
def get_tf_version_tuple():
    """
    Return TensorFlow version as a 2-element tuple (for comparison).
    """
    return tuple(map(int, tf.__version__.split('.')[:2])) 
Example #22
Source File: main.py    From open_model_zoo with Apache License 2.0 5 votes vote down vote up
def print_processing_info(model, launcher, device, tags, dataset):
    print_info('Processing info:')
    print_info('model: {}'.format(model))
    print_info('launcher: {}'.format(launcher))
    if tags:
        print_info('launcher tags: {}'.format(' '.join(tags)))
    print_info('device: {}'.format(device.upper()))
    print_info('dataset: {}'.format(dataset))
    print_info('OpenCV version: {}'.format(cv2.__version__)) 
Example #23
Source File: common.py    From tensorpack with Apache License 2.0 5 votes vote down vote up
def get_tf_version_tuple():
    """
    Return TensorFlow version as a 2-element tuple (for comparison).
    """
    return tuple(map(int, tf.__version__.split('.')[:2])) 
Example #24
Source File: sigrecog.py    From signature-recognition with MIT License 5 votes vote down vote up
def main():
    print('OpenCV version {} '.format(cv2.__version__))

    current_dir = os.path.dirname(__file__)

    author = '021'
    training_folder = os.path.join(current_dir, 'data/training/', author)
    test_folder = os.path.join(current_dir, 'data/test/', author)

    training_data = []
    for filename in os.listdir(training_folder):
        img = cv2.imread(os.path.join(training_folder, filename), 0)
        if img is not None:
            data = np.array(preprocessor.prepare(img))
            data = np.reshape(data, (901, 1))
            result = [[0], [1]] if "genuine" in filename else [[1], [0]]
            result = np.array(result)
            result = np.reshape(result, (2, 1))
            training_data.append((data, result))

    test_data = []
    for filename in os.listdir(test_folder):
        img = cv2.imread(os.path.join(test_folder, filename), 0)
        if img is not None:
            data = np.array(preprocessor.prepare(img))
            data = np.reshape(data, (901, 1))
            result = 1 if "genuine" in filename else 0
            test_data.append((data, result))

    net = network.NeuralNetwork([901, 500, 500, 2])
    net.sgd(training_data, 10, 50, 0.01, test_data) 
Example #25
Source File: test_environment.py    From detectron2-pipeline with MIT License 5 votes vote down vote up
def test_opencv_version():
    assert cv2.__version__ >= '4.0' 
Example #26
Source File: obj_detect_tracking.py    From Object_Detection_Tracking with Apache License 2.0 5 votes vote down vote up
def check_args(args):
  """Check the argument."""
  assert args.video_dir is not None
  assert args.video_lst_file is not None
  assert args.frame_gap >= 1
  if args.get_box_feat:
    assert args.box_feat_path is not None
    if not os.path.exists(args.box_feat_path):
      os.makedirs(args.box_feat_path)
  #print("cv2 version %s" % (cv2.__version__) 
Example #27
Source File: detect_yolo.py    From zmMagik with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self,configPath=None, weightPath=None, labelsPath=None, kernel_fill=3):

        if g.args['gpu'] and not g.args['use_opencv_dnn_cuda']:

            utils.success_print('Using Darknet GPU model for YOLO')
            utils.success_print('If you run out of memory, please tweak yolo.cfg')

            if not g.args['use_opencv_dnn_cuda']:
                self.m = yolo.SimpleYolo(configPath=configPath,
                        weightPath=weightPath,
                        darknetLib=g.args['darknet_lib'],
                        labelsPath=labelsPath,
                        useGPU=True)

        else:
            utils.success_print('Using OpenCV model for YOLO')
            utils.success_print('If you run out of memory, please tweak yolo.cfg')

            self.net = cv2.dnn.readNetFromDarknet(configPath, weightPath)
            self.labels = open(labelsPath).read().strip().split("\n")
            np.random.seed(42)
            self.colors = np.random.randint(
                0, 255, size=(len(self.labels), 3), dtype="uint8")
            self.kernel_fill = np.ones((kernel_fill,kernel_fill),np.uint8)

            if g.args['use_opencv_dnn_cuda'] and g.args['gpu']:
                (maj,minor,patch) = cv2.__version__.split('.')
                min_ver = int (maj+minor)
                if min_ver < 42:
                    utils.fail_print('Not setting CUDA backend for OpenCV DNN')
                    utils.dim_print ('You are using OpenCV version {} which does not support CUDA for DNNs. A minimum of 4.2 is required. See https://www.pyimagesearch.com/2020/02/03/how-to-use-opencvs-dnn-module-with-nvidia-gpus-cuda-and-cudnn/ on how to compile and install openCV 4.2'.format(cv2.__version__))
                else:
                    utils.success_print ('Setting CUDA backend for OpenCV. If you did not set your CUDA_ARCH_BIN correctly during OpenCV compilation, you will get errors during detection related to invalid device/make_policy')
                    self.net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
                    self.net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)

        utils.success_print('YOLO initialized') 
Example #28
Source File: sigrecogtf.py    From signature-recognition with MIT License 5 votes vote down vote up
def main():
    print('OpenCV version {} '.format(cv2.__version__))

    current_dir = os.path.dirname(__file__)

    author = '021'
    training_folder = os.path.join(current_dir, 'data/training/', author)
    test_folder = os.path.join(current_dir, 'data/test/', author)

    training_data = []
    training_labels = []
    for filename in os.listdir(training_folder):
        img = cv2.imread(os.path.join(training_folder, filename), 0)
        if img is not None:
            data = preprocessor.prepare(img)
            training_data.append(data)
            training_labels.append([0, 1] if "genuine" in filename else [1, 0])

    test_data = []
    test_labels = []
    for filename in os.listdir(test_folder):
        img = cv2.imread(os.path.join(test_folder, filename), 0)
        if img is not None:
            data = preprocessor.prepare(img)
            test_data.append(data)
            test_labels.append([0, 1] if "genuine" in filename else [1, 0])

    sgd(training_data, training_labels, test_data, test_labels)


# Softmax Regression Model 
Example #29
Source File: webcam.py    From facemoji with MIT License 5 votes vote down vote up
def show_webcam_and_run(model, emoticons, window_size=None, window_name='webcam', update_time=10):
    """
    Shows webcam image, detects faces and its emotions in real time and draw emoticons over those faces.
    :param model: Learnt emotion detection model.
    :param emoticons: List of emotions images.
    :param window_size: Size of webcam image window.
    :param window_name: Name of webcam image window.
    :param update_time: Image update time interval.
    """
    cv2.namedWindow(window_name, WINDOW_NORMAL)
    if window_size:
        width, height = window_size
        cv2.resizeWindow(window_name, width, height)

    vc = cv2.VideoCapture(0)
    if vc.isOpened():
        read_value, webcam_image = vc.read()
    else:
        print("webcam not found")
        return

    while read_value:
        for normalized_face, (x, y, w, h) in find_faces(webcam_image):
            prediction = model.predict(normalized_face)  # do prediction
            if cv2.__version__ != '3.1.0':
                prediction = prediction[0]

            image_to_draw = emoticons[prediction]
            draw_with_alpha(webcam_image, image_to_draw, (x, y, w, h))

        cv2.imshow(window_name, webcam_image)
        read_value, webcam_image = vc.read()
        key = cv2.waitKey(update_time)

        if key == 27:  # exit on ESC
            break

    cv2.destroyWindow(window_name) 
Example #30
Source File: video2images.py    From Realtime-Action-Recognition with MIT License 5 votes vote down vote up
def get_fps(self):

        # Find OpenCV version
        (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')

        # With webcam get(CV_CAP_PROP_FPS) does not work.
        # Let's see for ourselves.

        # Get video properties
        if int(major_ver) < 3:
            fps = self.video.get(cv2.cv.CV_CAP_PROP_FPS)
        else:
            fps = self.video.get(cv2.CAP_PROP_FPS)
        return fps