Ejemplo n.º 1
0
    def get_contours_for_range(img, color, vision):
        """
        Action: Gets a list of all the contours within the range that.
        :param color: a Color object describing (or numpy uint8 array) of color limit range in the hsv format.
        :param img: image from which to get the contours.
        :param vision: the vision object with a calibration to read from
        :return: list of all contours matching the range of hsv colours.
        :rtype: list, single numpy array (single contour) or None if no contour was found.
        """
        # If there was a problem reading the image, exit
        if img is None:
            raise Exception("No picture given!")
        hsv_low, hsv_high = color.low, color.high

        if vision.saturation_weight_vector is not None:
            image_mean = cv2.mean(img)[1]
            new_s = General.get_calibrated_value(
                image_mean, vision.saturation_weight_vector)
            hsv_low[1] = new_s

        if vision.value_weight_vector is not None:
            image_mean = cv2.mean(img)[2]
            new_v = General.get_calibrated_value(image_mean,
                                                 vision.value_weight_vector)
            hsv_low[2] = new_v

        img_in_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        img_mask = cv2.inRange(img_in_hsv, hsv_low, hsv_high)

        if cv2.__version__.startswith("3."):
            return cv2.findContours(img_mask, cv2.RETR_TREE,
                                    cv2.CHAIN_APPROX_SIMPLE)[1]
        if cv2.__version__.startswith("4."):
            return cv2.findContours(img_mask, cv2.RETR_TREE,
                                    cv2.CHAIN_APPROX_SIMPLE)[1]
        elif cv2.__version__.startswith("2."):
            return cv2.findContours(img_mask, cv2.RETR_TREE,
                                    cv2.CHAIN_APPROX_SIMPLE)[0]
        else:
            raise General.VersionError(
                "This code works with version 2 and 3 of openCV!")