示例#1
0
import numpy as np

img = cv.imread('imagen/wppstalkerlarge.jpg')

cv.imshow('stalker', img)

blank = np.zeros(img.shape, dtype='uint8')
cv.imshow('blank', blank)

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Gray', gray)

grayblurred = cv.GaussianBlur(gray, (5,5), cv.BORDER_DEFAULT)

#corners
canny = cv.Canny(grayblurred, 125, 175)
cv.imshow('CannyEdges', canny)
#corners can also be found by threesholding

#threeshold
#ret, thresh = cv.threshold(gray, 125, 255, cv.THRESH_BINARY)
#cv.imshow('Thresh', thresh)

#contours
contours, hierarchies = cv.findContours(canny, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
print(f'{len(contours)} contour(s) found!')

cv.drawContours(blank, contours, -1, (0,255,0), 1)
cv.imshow('contoursDrawn', blank)

cv.waitKey(0)
示例#2
0
from cv2 import cv2
import numpy as np
from skimage.morphology import opening
#dulieu=str(input("Enter link image:"))
img = cv2.imread('beans.jpg')
kernel = np.ones((5, 5), np.uint8)

# Bước 1: Chuyển về ảnh xám
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Bước 2: Làm mờ ảnh
blur = cv2.GaussianBlur(gray, (9, 9), 1)
cv2.imshow('new', blur)

# Bước 3: Lọc nhiễu
new = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
                            cv2.THRESH_BINARY, 9, -5)

# Bước 4: Opening
opening = cv2.morphologyEx(new, cv2.MORPH_OPEN, kernel)

# Bước 5: Đếm
contours = cv2.findContours(opening, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0]

# Kiểm tra kết quả
cv2.drawContours(img, contours, -1, (255, 0, 0), 3)
cv2.imshow('opening', opening)
print("Count: " + str(len(contours)))
cv2.waitKey(0)
cv2.destroyAllWindows()
    cv2.imshow('Threshold', thresh)
    major = cv2.__version__.split('.')[0]
    if major == '3':
        image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,
                                                      cv2.CHAIN_APPROX_SIMPLE)
    else:
        contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_TREE,
                                               cv2.CHAIN_APPROX_SIMPLE)

    try:
        contour = max(contours, key=lambda x: cv2.contourArea(x))
        x, y, w, h = cv2.boundingRect(contour)
        cv2.rectangle(crop_image, (x, y), (x + w, y + h), (0, 0, 255), 0)
        hull = cv2.convexHull(contour)
        drawing = np.zeros(crop_image.shape, np.uint8)
        cv2.drawContours(drawing, [contour], -1, (0, 255, 0), 0)
        cv2.drawContours(drawing, [hull], -1, (0, 255, 0), 0)
        hull = cv2.convexHull(contour, returnPoints=False)
        defects = cv2.convexityDefects(contour, hull)

        count_defects = 0
        for i in range(defects.shape[0]):
            s, e, f, d = defects[i, 0]
            start = tuple(contour[s][0])
            end = tuple(contour[e][0])
            far = tuple(contour[f][0])

            a = math.sqrt((end[0] - start[0])**2 + (end[1] - start[1])**2)
            b = math.sqrt((far[0] - start[0])**2 + (far[1] - start[1])**2)
            c = math.sqrt((end[0] - far[0])**2 + (end[1] - far[1])**2)
            angle = (math.acos(
示例#4
0
    def test(self, saved_region_parent_dir=None):
        print("Pre-processing test data...")

        img_hsv = self.training_data[self.test_img_name]['hsv_img']
        img_rgb = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2RGB)
        img_s = img_hsv[:, :, 1]
        img_shape = (img_hsv.shape[0], img_hsv.shape[1])

        # blur kernels
        large_blur_kernel = (95, 95)
        med_blur_kernel = (63, 63)
        small_blur_kernel = (31, 31)

        # Dilation/erosion kernels
        cross_strel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
        block_strel = np.ones((3, 3))
        ellipse_strel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
        ellipse90_strel = np.rot90(ellipse_strel)
        circle_strel = np.bitwise_or(ellipse_strel, ellipse90_strel)

        b_over_r = img_rgb[:, :, 0] < img_rgb[:, :, 2]
        b_over_g = img_rgb[:, :, 1] < img_rgb[:, :, 2]
        b_over_rg = np.bitwise_and(b_over_r, b_over_g)

        b_replace = np.max([img_rgb[:, :, 0], img_rgb[:, :, 1]], axis=0)

        b_suppress_img = img_rgb.copy()
        b_suppress_img[b_over_rg, 2] = b_replace[b_over_rg]
        b_suppress_img_hsv = cv2.cvtColor(b_suppress_img, cv2.COLOR_RGB2HSV)
        enhanced_v_img = b_suppress_img_hsv[:, :, 2]

        # diff of gaussians
        img_blur_1 = cv2.blur(enhanced_v_img, (15, 15))
        img_blur_2 = cv2.blur(enhanced_v_img, (127, 127))

        tmp_img_1 = img_blur_1.astype(np.int16)
        tmp_img_2 = img_blur_2.astype(np.int16)

        edge_mask = tmp_img_2 - tmp_img_1
        edge_mask[edge_mask > 0] = 0
        edge_mask[edge_mask < 0] = 255

        edge_mask = edge_mask.astype(np.uint8)

        contours = cv2x.filter_contours_by_size(edge_mask, min_size=15 * 15)

        edge_mask = np.zeros(img_shape, dtype=np.uint8)
        cv2.drawContours(edge_mask, contours, -1, 255, -1)

        edge_mask = cv2.dilate(edge_mask, cross_strel, iterations=1)

        # color candidates (all non-monochrome, non-blue colors)
        print("Generating color candidates...")

        tmp_color_img = cv2.cvtColor(b_suppress_img_hsv, cv2.COLOR_HSV2RGB)
        tmp_color_img = cv2.blur(tmp_color_img, (9, 9))
        tmp_color_img = cv2.cvtColor(tmp_color_img, cv2.COLOR_RGB2HSV)

        color_mask = color_utils.create_mask(
            tmp_color_img, ['green', 'cyan', 'red', 'violet', 'yellow'])

        # Next, clean up any "noise", say, ~ 11 x 11
        contours = cv2x.filter_contours_by_size(color_mask, min_size=5 * 5)

        color_mask2 = np.zeros(img_shape, dtype=np.uint8)
        cv2.drawContours(color_mask2, contours, -1, 255, -1)

        # do a couple dilations to smooth some outside edges & connect any
        # adjacent cells each other
        color_mask3 = cv2.dilate(color_mask2, cross_strel, iterations=2)
        color_mask3 = cv2.erode(color_mask3, cross_strel, iterations=3)

        # filter out any remaining contours that are the size of roughly 2 cells
        contours = cv2x.filter_contours_by_size(color_mask3,
                                                min_size=2 * 40 * 40)

        color_mask3 = np.zeros(img_shape, dtype=np.uint8)
        cv2.drawContours(color_mask3, contours, -1, 255, -1)

        good_color_contours = []

        for i, c in enumerate(contours):
            filled_c_mask = np.zeros(img_shape, dtype=np.uint8)
            cv2.drawContours(filled_c_mask, [c], -1, 255, cv2.FILLED)

            new_mask, signal, orig = cv2x.find_border_by_mask(
                edge_mask,
                filled_c_mask,
                max_dilate_percentage=0.3,
                dilate_iterations=1)

            if not orig and signal > 0.7:
                _, contours, _ = cv2.findContours(new_mask, cv2.RETR_EXTERNAL,
                                                  cv2.CHAIN_APPROX_SIMPLE)

                good_color_contours.append(contours[0])
            elif orig and signal > 0.7:
                good_color_contours.append(c)
            else:
                pass  # don't include contour

        # The previous contours represent the final count of contours for the color group,
        # but not their final shape/size. The final step is to use approxPolyDP, followed
        # by a few more dilations, but we won't re-draw and extract the contours, as that
        # would possibly connect some of them together. However, we will draw them for
        # the mask to exclude these regions from the next 2 groups of candidates
        final_color_contours = []

        for c in good_color_contours:
            peri = cv2.arcLength(c, True)
            smooth_c = cv2.approxPolyDP(c, 0.007 * peri, True)

            single_cnt_mask = np.zeros(img_shape, dtype=np.uint8)
            cv2.drawContours(single_cnt_mask, [smooth_c], 0, 255, -1)

            # erode & dilate
            single_cnt_mask = cv2.erode(single_cnt_mask,
                                        block_strel,
                                        iterations=1)
            single_cnt_mask = cv2.dilate(single_cnt_mask,
                                         block_strel,
                                         iterations=8)

            _, contours, _ = cv2.findContours(single_cnt_mask,
                                              cv2.RETR_EXTERNAL,
                                              cv2.CHAIN_APPROX_SIMPLE)

            if len(contours) > 0:
                final_color_contours.append(contours[0])

        # final color mask to use for exclusion from further groups
        final_color_mask = np.zeros(img_shape, dtype=np.uint8)
        cv2.drawContours(final_color_mask, final_color_contours, -1, 255, -1)

        # start large structure saturation candidates
        print("Generating large saturation candidates...")

        img_s_large_blur = cv2.GaussianBlur(img_s, large_blur_kernel, 0, 0)

        med = np.median(img_s_large_blur[img_s_large_blur > 0])

        img_s_large_blur = cv2.bitwise_and(img_s_large_blur,
                                           img_s_large_blur,
                                           mask=~final_color_mask)
        mode_s_large = cv2.inRange(img_s_large_blur, med, 255)
        mode_s_large = cv2.erode(mode_s_large, block_strel, iterations=5)

        good_contours_large = cv2x.filter_contours_by_size(
            mode_s_large,
            min_size=10 * 32 * 32,
            max_size=(img_shape[0] * img_shape[1]) * .33)

        # update the signal mask by removing the previous color candidates
        edge_mask = cv2.bitwise_and(edge_mask,
                                    edge_mask,
                                    mask=~final_color_mask)
        contours = cv2x.filter_contours_by_size(edge_mask, min_size=21 * 21)
        edge_mask = np.zeros(img_shape, dtype=np.uint8)
        cv2.drawContours(edge_mask, contours, -1, 255, -1)
        edge_mask = cv2.dilate(edge_mask, (3, 3), iterations=2)

        good_large_sat_val_contours = []

        for i, c in enumerate(good_contours_large):
            filled_c_mask = np.zeros(img_shape, dtype=np.uint8)
            cv2.drawContours(filled_c_mask, [c], -1, 255, cv2.FILLED)

            new_mask, signal, orig = cv2x.find_border_by_mask(
                edge_mask,
                filled_c_mask,
                max_dilate_percentage=2.0,
                dilate_iterations=1)

            if not orig and signal > 0.7:
                _, contours, _ = cv2.findContours(new_mask, cv2.RETR_EXTERNAL,
                                                  cv2.CHAIN_APPROX_SIMPLE)

                good_large_sat_val_contours.append(contours[0])
            elif signal > 0.7:
                good_large_sat_val_contours.append(c)
            else:
                pass  # ignore contour

        # The previous contours represent the final contour count for the large sat-val group,
        # but not their final shape/size. The final step is to use approxPolyDP, followed
        # by a few more dilations, but we won't re-draw and extract the contours, as that
        # would possibly connect some of them together. However, we will draw them for
        # the mask to exclude these regions from the next group of candidates
        final_large_sat_val_contours = []

        for c in good_large_sat_val_contours:
            peri = cv2.arcLength(c, True)
            smooth_c = cv2.approxPolyDP(c, 0.0035 * peri, True)

            single_cnt_mask = np.zeros(img_shape, dtype=np.uint8)
            cv2.drawContours(single_cnt_mask, [smooth_c], 0, 255, -1)

            # erode & dilate
            single_cnt_mask = cv2.dilate(single_cnt_mask,
                                         circle_strel,
                                         iterations=10)

            _, tmp_contours, _ = cv2.findContours(single_cnt_mask,
                                                  cv2.RETR_EXTERNAL,
                                                  cv2.CHAIN_APPROX_SIMPLE)

            final_large_sat_val_contours.append(tmp_contours[0])

        # final group mask to use for exclusion from further groups
        final_large_sat_val_mask = np.zeros(img_shape, dtype=np.uint8)
        cv2.drawContours(final_large_sat_val_mask,
                         final_large_sat_val_contours, -1, 255, -1)

        # start medium structure saturation candidates
        print("Generating medium saturation candidates...")

        img_s_medium_blur = cv2.GaussianBlur(img_s, med_blur_kernel, 0, 0)
        med = np.median(img_s_medium_blur[img_s_medium_blur > 0])

        # make intermediate candidate mask
        tmp_candidate_mask = np.bitwise_or(final_color_mask,
                                           final_large_sat_val_mask)

        img_s_medium_blur = cv2.bitwise_and(img_s_medium_blur,
                                            img_s_medium_blur,
                                            mask=~tmp_candidate_mask)

        mode_s_med = cv2.inRange(img_s_medium_blur, np.ceil(med), 255)

        mode_s_med = cv2.erode(mode_s_med, block_strel, iterations=8)

        good_contours_med = cv2x.filter_contours_by_size(
            mode_s_med,
            min_size=2 * 32 * 32,
            max_size=(img_shape[0] * img_shape[1]) * .125)

        # update signal mask with last group of candidates
        edge_mask = cv2.bitwise_and(edge_mask,
                                    edge_mask,
                                    mask=~final_large_sat_val_mask)
        contours = cv2x.filter_contours_by_size(edge_mask, min_size=21 * 21)

        edge_mask = np.zeros(img_shape, dtype=np.uint8)
        cv2.drawContours(edge_mask, contours, -1, 255, -1)
        edge_mask = cv2.dilate(edge_mask, (3, 3), iterations=2)

        final_med_sat_val_contours = []

        for i, c in enumerate(good_contours_med):
            filled_c_mask = np.zeros(img_shape, dtype=np.uint8)
            cv2.drawContours(filled_c_mask, [c], -1, 255, cv2.FILLED)

            new_mask, signal, orig = cv2x.find_border_by_mask(
                edge_mask,
                filled_c_mask,
                max_dilate_percentage=1.5,
                dilate_iterations=1)

            if not orig and signal > 0.7:
                _, contours, _ = cv2.findContours(new_mask, cv2.RETR_EXTERNAL,
                                                  cv2.CHAIN_APPROX_SIMPLE)

                final_med_sat_val_contours.append(contours[0])
            elif signal > 0.7:
                final_med_sat_val_contours.append(c)
            else:
                pass  # ignore contour

        med_sat_val_mask = np.zeros(img_shape, dtype=np.uint8)
        cv2.drawContours(med_sat_val_mask, final_med_sat_val_contours, -1, 255,
                         cv2.FILLED)

        # The previous contours represent the final count of contours for the med sat-val group,
        # but not their final shape/size. The final step is to use approxPolyDP, followed
        # by a few more dilations, but we won't re-draw and extract the contours, as that
        # would possibly connect some of them together. However, we will draw them for
        # the mask to exclude these regions from the next group of candidates
        _, contours, _ = cv2.findContours(med_sat_val_mask, cv2.RETR_EXTERNAL,
                                          cv2.CHAIN_APPROX_SIMPLE)

        final_med_sat_val_contours = []

        for c in contours:
            peri = cv2.arcLength(c, True)
            smooth_c = cv2.approxPolyDP(c, 0.0035 * peri, True)

            single_cnt_mask = np.zeros(img_shape, dtype=np.uint8)
            cv2.drawContours(single_cnt_mask, [smooth_c], 0, 255, -1)

            # erode & dilate
            single_cnt_mask = cv2.dilate(single_cnt_mask,
                                         ellipse90_strel,
                                         iterations=10)

            _, tmp_contours, _ = cv2.findContours(single_cnt_mask,
                                                  cv2.RETR_EXTERNAL,
                                                  cv2.CHAIN_APPROX_SIMPLE)

            final_med_sat_val_contours.append(tmp_contours[0])

        # final color mask to use for exclusion from further groups
        final_med_sat_val_mask = np.zeros(img_shape, dtype=np.uint8)
        cv2.drawContours(final_med_sat_val_mask, final_med_sat_val_contours,
                         -1, 255, -1)

        # start small structure saturation candidates
        print("Generating small saturation candidates...")

        img_s_small_blur = cv2.bilateralFilter(img_s, small_blur_kernel[0], 31,
                                               31)
        med = np.median(img_s_small_blur[img_s_small_blur > 0])

        # make intermediate candidate mask
        tmp_candidate_mask = np.bitwise_or(tmp_candidate_mask,
                                           final_med_sat_val_mask)

        img_s_small_blur = cv2.bitwise_and(img_s_small_blur,
                                           img_s_small_blur,
                                           mask=~tmp_candidate_mask)

        mode_s_small = cv2.inRange(img_s_small_blur, np.ceil(med), 255)

        mode_s_small = cv2.erode(mode_s_small, block_strel, iterations=2)

        good_contours_small = cv2x.filter_contours_by_size(
            mode_s_small,
            min_size=15 * 15,
            max_size=(img_shape[0] * img_shape[1]) * .05)

        # update signal mask with last group of candidates
        edge_mask = cv2.bitwise_and(edge_mask,
                                    edge_mask,
                                    mask=~final_med_sat_val_mask)
        contours = cv2x.filter_contours_by_size(edge_mask, min_size=31 * 31)
        edge_mask = np.zeros(img_shape, dtype=np.uint8)
        cv2.drawContours(edge_mask, contours, -1, 255, -1)
        edge_mask = cv2.dilate(edge_mask, (3, 3), iterations=3)

        good_small_sat_val_contours = []

        for i, c in enumerate(good_contours_small):
            filled_c_mask = np.zeros(img_shape, dtype=np.uint8)
            cv2.drawContours(filled_c_mask, [c], -1, 255, cv2.FILLED)

            new_mask, signal, orig = cv2x.find_border_by_mask(
                edge_mask,
                filled_c_mask,
                max_dilate_percentage=2.5,
                dilate_iterations=1)

            if not orig and signal > 0.7:
                _, contours, _ = cv2.findContours(new_mask, cv2.RETR_EXTERNAL,
                                                  cv2.CHAIN_APPROX_SIMPLE)

                good_small_sat_val_contours.append(contours[0])
            elif signal > 0.7:
                good_small_sat_val_contours.append(c)
            else:
                pass  # ignore contour

        tmp_small_sat_val_contours = good_small_sat_val_contours.copy()
        good_small_sat_val_contours = []

        for c in tmp_small_sat_val_contours:
            area = cv2.contourArea(c)
            if area > 27 * 27:
                good_small_sat_val_contours.append(c)

        # The previous contours represent the final countour count for the small sat-val group,
        # but not their final shape/size. The final step is to use approxPolyDP, followed
        # by a few more dilations, but we won't re-draw and extract the contours, as that
        # would possibly connect some of them together. However, we will draw them for
        # the mask to exclude these regions from the next group of candidates
        final_small_sat_val_contours = []

        for c in good_small_sat_val_contours:
            peri = cv2.arcLength(c, True)
            smooth_c = cv2.approxPolyDP(c, 0.007 * peri, True)

            single_cnt_mask = np.zeros(img_shape, dtype=np.uint8)
            cv2.drawContours(single_cnt_mask, [smooth_c], 0, 255, -1)

            # erode & dilate
            single_cnt_mask = cv2.dilate(single_cnt_mask,
                                         block_strel,
                                         iterations=10)

            _, tmp_contours, _ = cv2.findContours(single_cnt_mask,
                                                  cv2.RETR_EXTERNAL,
                                                  cv2.CHAIN_APPROX_SIMPLE)

            final_small_sat_val_contours.append(tmp_contours[0])

        all_contours = final_color_contours + \
            final_large_sat_val_contours + \
            final_med_sat_val_contours + \
            final_small_sat_val_contours

        model_classes = list(self.pipe.named_steps['classification'].classes_)
        final_contour_results = []

        test_data_processed = []

        for c_idx, c in enumerate(all_contours):
            if saved_region_parent_dir is not None:
                region_base_name = '.'.join([str(c_idx), 'png'])
                region_file_path = os.path.join(saved_region_parent_dir,
                                                region_base_name)

                if not os.path.exists(saved_region_parent_dir):
                    os.makedirs(saved_region_parent_dir)
            else:
                region_file_path = None
                region_base_name = None
            features = color_utils.generate_features(
                img_hsv, c, region_file_path=region_file_path)
            features_df = pd.DataFrame([features])
            probabilities = self.pipe.predict_proba(
                features_df.drop('label', axis=1))
            labelled_probs = {
                a: probabilities[0][i]
                for i, a in enumerate(model_classes)
            }
            pred_label = max(labelled_probs,
                             key=lambda key: labelled_probs[key])
            pred_label_prob = labelled_probs[pred_label]

            final_contour_results.append({
                'test_index': c_idx,
                'contour': c,
                'prob': labelled_probs
            })

            features['pred_label'] = pred_label
            features['pred_label_prob'] = pred_label_prob
            features['region_file'] = region_base_name
            features['region_index'] = c_idx

            test_data_processed.append(features)

        self.test_data_processed = pd.DataFrame(test_data_processed)
        self.test_data_processed.set_index('region_index')

        self.test_results = final_contour_results
示例#5
0
import numpy as np
from cv2 import cv2

# Load image - resize hình do kích thước hình quá to
image = cv2.imread('cell.jpg')
image = cv2.resize(image, (1200, 900))

# Convert to Gray image
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Image binarization
ret, binary_image = cv2.threshold(gray_image, 165, 255, cv2.THRESH_BINARY)

# Contour detection
_, contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL,
                                  cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
    cv2.drawContours(image, contour, -1, (255, 0, 0), 3)

cv2.imshow('Image', image)
cv2.imshow('Gray image', gray_image)
cv2.imshow('Binary image', binary_image)

cv2.waitKey(0)
cv2.destroyAllWindows()
示例#6
0
        _, im = cv2.threshold(gray_img, 220, 1,
                              cv2.THRESH_BINARY + cv2.THRESH_OTSU)

        if sum(sum(gray_img.astype('double'))) > 1000:
            cnts, hier = cv2.findContours(im, cv2.RETR_TREE,
                                          cv2.CHAIN_APPROX_SIMPLE)
            center = None
            for c in cnts:
                x, y, w, h = cv2.boundingRect(c)
                #cv2.rectangle(img, (x,y),(x+w,y+h),(0,255,0),2)

                rect = cv2.minAreaRect(c)
                box = cv2.boxPoints(rect)

                box = np.int0(box)
                cv2.drawContours(img, [box], 0, (0, 0, 255))
            if len(cnts) > 1:
                c = sorted(cnts, key=cv2.contourArea)[-1]  # The largest area
                ((x, y), radius) = cv2.minEnclosingCircle(c)
                M = cv2.moments(c)
                #deal with division by zero
                if M["m00"] != 0:
                    center = (int(M["m10"] / M["m00"]),
                              int(M["m01"] / M["m00"]))
                else:
                    center = (0, 0)
                CX = center[0]
                CY = center[1]
                center_string = "CX:{}, CY:{}".format(CX, CY)
                cv2.putText(img, center_string, (0, 128),
                            cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 1)
from cv2 import cv2

img = cv2.imread('tomato2.jpg', 1)
img = cv2.resize(img, (0, 0), fx=0.6, fy=0.6)
#Convert to hsv channel for segmentation, then contour miscalculation due to segmentation overlap
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
ret, seg_img = cv2.threshold(
    hsv[:, :, 0], 25, 255,
    cv2.THRESH_BINARY_INV)  #red in hue channel is b/w 0-25 and 250-255
cv2.imshow("Poor Segmentation", seg_img)

#Try contouring on overlapped segments, tomatoes group considered one object
contours, heirarchy = cv2.findContours(seg_img, cv2.RETR_TREE,
                                       cv2.CHAIN_APPROX_SIMPLE)
img2 = img.copy()
cv2.drawContours(img2, contours, -1, (0, 0, 0), 2)
cv2.imshow("Wrong Contours", img2)

#Canny Edges
edges = cv2.Canny(img, 100, 70)  #Lower and upper limit of threshold edges
cv2.imshow("Canny", edges)

#Canny Contours, using edges to find better segmented img for better contour
improve_seg_img = seg_img - edges
cv2.imshow("Canny Segmentation", improve_seg_img)

contours, heirarchy = cv2.findContours(improve_seg_img, cv2.RETR_TREE,
                                       cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img, contours, -1, (0, 0, 0), 1)
cv2.imshow("Canny Contours", img)
示例#8
0
#膨胀操作
kernel = np.ones((3, 3), np.uint8)
paper1 = cv2.dilate(paper1, kernel, iterations=1)
if show_process:
    imshow(paper1)

#轮廓检测
cnts = cv2.findContours(paper1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[1]

#提取面积最大的轮廓
cnts = sorted(cnts, key=lambda x: cv2.contourArea(x), reverse=True)

#绘制面积最大的轮廓
show = org1.copy()
show = cv2.drawContours(show, cnts, 0, (0, 255, 0), 1)

if show_process:
    imshow(show)

cnt = []

#步长设置为周长的0.0001倍,一般来说取epsilon = 0.001倍周长
step = 0.0001 * cv2.arcLength(cnts[0], True)
epsilon = step

#不断递增epsilon直到近似所得轮廓正好包含四个点
while len(cnt) != 4:
    cnt = cv2.approxPolyDP(cnts[0], epsilon, True)

    #步增epsilon
def gestos_mano():
    cap = cv2.VideoCapture(0)
    # cap = cv2.VideoCapture(1)

    bg = None
    # COLORES PARA VISUALIZACIÓN
    color_start = (204, 204, 0)
    color_end = (204, 0, 204)
    color_far = (255, 0, 0)
    color_start_far = (204, 204, 0)
    color_far_end = (204, 0, 204)
    color_start_end = (0, 255, 255)
    color_contorno = (0, 255, 0)
    color_ymin = (0, 130, 255)  # Punto más alto del contorno
    # color_angulo = (0,255,255)
    # color_d = (0,255,255)
    color_fingers = (0, 255, 255)

    while True:
        ret, frame = cap.read()
        if ret == False: break
        # Redimensionar la imagen para que tenga un ancho de 640
        frame = imutils.resize(frame, width=640)
        frame = cv2.flip(frame, 1)
        frameAux = frame.copy()

        if bg is not None:

            # Determinar la región de interés
            ROI = frame[50:300, 380:600]
            cv2.rectangle(frame, (380 - 2, 50 - 2), (600 + 2, 300 + 2),
                          color_fingers, 1)
            grayROI = cv2.cvtColor(ROI, cv2.COLOR_BGR2GRAY)

            # Región de interés del fondo de la imagen
            bgROI = bg[50:300, 380:600]

            # Determinar la imagen binaria (background vs foreground)
            dif = cv2.absdiff(grayROI, bgROI)
            _, th = cv2.threshold(dif, 30, 255, cv2.THRESH_BINARY)
            th = cv2.medianBlur(th, 7)

            # Encontrando los contornos de la imagen binaria
            cnts, _ = cv2.findContours(th, cv2.RETR_EXTERNAL,
                                       cv2.CHAIN_APPROX_SIMPLE)
            cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:1]
            for cnt in cnts:
                # Encontrar el centro del contorno
                M = cv2.moments(cnt)
                if M["m00"] == 0: M["m00"] = 1
                x = int(M["m10"] / M["m00"])
                y = int(M["m01"] / M["m00"])
                cv2.circle(ROI, tuple([x, y]), 5, (0, 255, 0), -1)

                # Punto más alto del contorno
                ymin = cnt.min(axis=1)
                cv2.circle(ROI, tuple(ymin[0]), 5, color_ymin, -1)

                # Contorno encontrado a través de cv2.convexHull
                hull1 = cv2.convexHull(cnt)
                cv2.drawContours(ROI, [hull1], 0, color_contorno, 2)

                # Defectos convexos
                hull2 = cv2.convexHull(cnt, returnPoints=False)
                defects = cv2.convexityDefects(cnt, hull2)

                # Seguimos con la condición si es que existen defectos convexos
                if defects is not None:
                    inicio = [
                    ]  # Contenedor en donde se almacenarán los puntos iniciales de los defectos convexos
                    fin = [
                    ]  # Contenedor en donde se almacenarán los puntos finales de los defectos convexos
                    fingers = 0  # Contador para el número de dedos levantados
                    for i in range(defects.shape[0]):

                        s, e, f, d = defects[i, 0]
                        start = cnt[s][0]
                        end = cnt[e][0]
                        far = cnt[f][0]
                        # Encontrar el triángulo asociado a cada defecto convexo para determinar ángulo
                        a = np.linalg.norm(far - end)
                        b = np.linalg.norm(far - start)
                        c = np.linalg.norm(start - end)

                        angulo = np.arccos(
                            (np.power(a, 2) + np.power(b, 2) - np.power(c, 2))
                            / (2 * a * b))
                        angulo = np.degrees(angulo)
                        angulo = int(angulo)

                        # Se descartarán los defectos convexos encontrados de acuerdo a la distnacia
                        # entre los puntos inicial, final y más alelago, por el ángulo y d
                        if np.linalg.norm(start - end
                                          ) > 20 and angulo < 90 and d > 12000:
                            # Almacenamos todos los puntos iniciales y finales que han sido
                            # obtenidos
                            inicio.append(start)
                            fin.append(end)

                            # Visualización de distintos datos obtenidos
                            # cv2.putText(ROI,'{}'.format(angulo),tuple(far), 1, 1.5,color_angulo,2,cv2.LINE_AA)
                            # cv2.putText(ROI,'{}'.format(d),tuple(far), 1, 1.1,color_d,1,cv2.LINE_AA)
                            cv2.circle(ROI, tuple(start), 5, color_start, 2)
                            cv2.circle(ROI, tuple(end), 5, color_end, 2)
                            cv2.circle(ROI, tuple(far), 7, color_far, -1)
                            # cv2.line(ROI,tuple(start),tuple(far),color_start_far,2)
                            # cv2.line(ROI,tuple(far),tuple(end),color_far_end,2)
                            # cv2.line(ROI,tuple(start),tuple(end),color_start_end,2)
                    # Si no se han almacenado puntos de inicio (o fin), puede tratarse de
                    # 0 dedos levantados o 1 dedo levantado
                    if len(inicio) == 0:
                        minY = np.linalg.norm(ymin[0] - [x, y])
                        if minY >= 110:
                            fingers = fingers + 1
                            cv2.putText(ROI, '{}'.format(fingers),
                                        tuple(ymin[0]), 1, 1.7,
                                        (color_fingers), 1, cv2.LINE_AA)

                    # Si se han almacenado puntos de inicio, se contará el número de dedos levantados
                    for i in range(len(inicio)):
                        fingers = fingers + 1
                        cv2.putText(ROI, '{}'.format(fingers),
                                    tuple(inicio[i]), 1, 1.7, (color_fingers),
                                    1, cv2.LINE_AA)
                        if i == len(inicio) - 1:
                            fingers = fingers + 1
                            cv2.putText(ROI, '{}'.format(fingers),
                                        tuple(fin[i]), 1, 1.7, (color_fingers),
                                        1, cv2.LINE_AA)

                    # Se visualiza el número de dedos levantados en el rectángulo izquierdo
                    if fingers == 0:
                        cv2.putText(frame, 'Auxilio', (390, 45), 1, 2,
                                    (color_fingers), 2, cv2.LINE_AA)
                    else:
                        if fingers == 1:
                            cv2.putText(frame, 'Estoy bien!', (390, 45), 1, 2,
                                        (color_fingers), 2, cv2.LINE_AA)

                        else:
                            if fingers == 2:
                                if angulo > 60:
                                    cv2.putText(frame, 'Tengo hambre',
                                                (390, 45), 1, 2,
                                                (color_fingers), 2,
                                                cv2.LINE_AA)
                                else:
                                    if angulo < 40:
                                        cv2.putText(frame, 'Tengo sueño',
                                                    (390, 45), 1, 2,
                                                    (color_fingers), 2,
                                                    cv2.LINE_AA)
                            else:
                                if fingers == 3:
                                    cv2.putText(frame, 'Te quiero', (390, 45),
                                                1, 2, (color_fingers), 2,
                                                cv2.LINE_AA)
                                else:
                                    if fingers == 4:
                                        cv2.putText(frame, 'Gesto desconocido',
                                                    (300, 45), 1, 2,
                                                    (color_fingers), 2,
                                                    cv2.LINE_AA)
                                    else:
                                        cv2.putText(frame, 'Hola mundo!',
                                                    (300, 45), 1, 2,
                                                    (color_fingers), 2,
                                                    cv2.LINE_AA)

            cv2.imshow('th', th)
        cv2.imshow('Frame', frame)
        k = cv2.waitKey(20)
        if k == ord('i'):
            bg = cv2.cvtColor(frameAux, cv2.COLOR_BGR2GRAY)
        if k == 27:
            break

    cap.release()
    cv2.destroyAllWindows()
import numpy as np
from cv2 import cv2

img = cv2.imread('detect_blob.png', 1)
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

thresh_img = cv2.adaptiveThreshold(
    gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115,
    1)  #guassion threshold with output binary threshold type
#Make sure to binarize image before using contour functions
cv2.imshow("Adaptive Thresh Image", thresh_img)

#Contours
contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE,
                                       cv2.CHAIN_APPROX_SIMPLE)

img2 = img.copy()
index = -1  #if negative all contours are drawn, index of contour to be drawn
thickness = 4
color = (255, 0, 255)
cv2.drawContours(img2, contours, index, color, thickness)
cv2.imshow('Contours', img2)
print("Contours", contours)
cv2.waitKey(0)
cv2.destroyAllWindows()
def plot_test_results(trained_pipeline, report):
    hsv_img = trained_pipeline.training_data[
        trained_pipeline.test_img_name]['hsv_img'].copy()
    ground_truth = trained_pipeline.training_data[
        trained_pipeline.test_img_name]['regions']
    test_results = trained_pipeline.test_results

    # first, map ground truth indices by label
    gt_by_label_map = {}
    for i, gt in enumerate(ground_truth):
        if gt['label'] not in gt_by_label_map:
            gt_by_label_map[gt['label']] = []

        gt_by_label_map[gt['label']].append(gt['points'])

    tp_by_label_map = {}
    fp_by_label_map = {}
    fn_by_label_map = {}
    for k, v in report.items():
        if k not in tp_by_label_map:
            tp_by_label_map[k] = []
            fp_by_label_map[k] = []
            fn_by_label_map[k] = []

        for tp in v['tp']:
            if 'test_ind' in tp:
                tp_by_label_map[k].append(
                    test_results[tp['test_ind']]['contour'])

        for fp in v['fp']:
            if 'test_ind' in fp:
                fp_by_label_map[k].append(
                    test_results[fp['test_ind']]['contour'])

        for fn in v['fn']:
            if 'gt_ind' in fn:
                fn_by_label_map[k].append(ground_truth[fn['gt_ind']]['points'])

    # create separate set of images for each class label
    for class_label in sorted(report.keys()):
        # ground truth
        if class_label != 'background':
            new_img = cv2.cvtColor(hsv_img.copy(), cv2.COLOR_HSV2RGB)
            cv2.drawContours(new_img, gt_by_label_map[class_label], -1,
                             (0, 255, 0), 5)
            plt.figure(figsize=(8, 8))
            plt.imshow(new_img)
            plt.title("%s - %s" % (class_label, 'Ground Truth'))
            plt.show()

        # true positive
        new_img = cv2.cvtColor(hsv_img.copy(), cv2.COLOR_HSV2RGB)
        cv2.drawContours(new_img, tp_by_label_map[class_label], -1,
                         (0, 255, 0), 5)
        plt.figure(figsize=(8, 8))
        plt.imshow(new_img)
        plt.title("%s - %s" % (class_label, 'True Positive'))
        plt.show()

        # false negative
        new_img = cv2.cvtColor(hsv_img.copy(), cv2.COLOR_HSV2RGB)
        cv2.drawContours(new_img, fn_by_label_map[class_label], -1,
                         (0, 255, 0), 5)
        plt.figure(figsize=(8, 8))
        plt.imshow(new_img)
        plt.title("%s - %s" % (class_label, 'False Negative'))
        plt.show()

        # false positive
        new_img = cv2.cvtColor(hsv_img.copy(), cv2.COLOR_HSV2RGB)
        cv2.drawContours(new_img, fp_by_label_map[class_label], -1,
                         (0, 255, 0), 5)
        plt.figure(figsize=(8, 8))
        plt.imshow(new_img)
        plt.title("%s - %s" % (class_label, 'False Positive'))
        plt.show()
示例#12
0
    def contourAnalyze(self, contours, pname, **numContours):

        if ('num' in numContours):
            self.numContours = numContours['num']
            #print(self.numContours)

        #takes contours above {minArea} and below {maxArea}
        rcontours = []
        #holds the {# of contours} indices
        indList = []
        #holds the {# of contours} positions
        mxyList = []

        ind1 = -1

        for i in range(len(contours)):
            #------ Basic Declarations ---------------------

            p = contours[i]
            #desired area
            area = cv2.contourArea(contours[i])

            #-------------------------------------------------

            #------- Contour Calculations --------------------

            if area >= self.minArea and area <= self.maxArea:

                #increase the first indice for position saving
                ind1 = ind1 + 1
                indList.append(ind1)

                #make rotating boxes around points
                rect = cv2.minAreaRect(p)
                box = cv2.boxPoints(rect)
                box = np.int0(box)

                #put the box onto the original frame
                cv2.drawContours(self.frame, [box], 0, (0, 255, 0), 2)

                #store the position of the contoured objects
                #ASSUMES THAT NEW CONTOURS AREN'T BEING INTRODUCED
                m = cv2.moments(p)
                mx = int(m['m10'] / m['m00'])
                my = int(m['m01'] / m['m00'])
                mxyList.append([mx, my])
                cv2.circle(self.frame, (mx, my), 5, (0, 0, 255), 2)
                cv2.putText(self.frame, 'HEY', (mx, my),
                            cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 2)
                rcontours.append(p)

        if len(rcontours) != self.numContours:
            #print('\nduck\n')
            return False, rcontours

        elif len(rcontours) == self.numContours:
            #print('\nPEEPEE\n')
            self.save(pname, indList, mxyList, pos)

            #saves newly edited pos to file
            with open(pname, 'w+b') as file:
                pickle.dump(pos, file)

            #returns check and contours that meet area standards
            return True, rcontours
示例#13
0
def show_contours(img, contour, text, x, y):
    cv.drawContours(img, [contour], 0, [0, 0, 255], 2)
    cv.putText(img, text, (x, y), cv.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2)
    cv.imshow(window_source, img)
示例#14
0
    approx = cv2.approxPolyDP(c, 0.05 * peri, True)

    # if our approximated contour has four points, then
    # we can assume that we have found our screen
    if len(approx) == 4 and max_size > cv2.contourArea(c) > min_size:
        screenCnt = approx
        break

if screenCnt is None:
    detected = 0
    print("No plate detected")
else:
    detected = 1

if detected == 1:
    cv2.drawContours(img, [screenCnt], -1, (0, 255, 0), 3)

    # Masking the part other than the number plate
    mask = np.zeros(gray.shape, np.uint8)
    new_image = cv2.drawContours(mask, [screenCnt], 0, 255, -1, )
    new_image = cv2.bitwise_and(img, img, mask=mask)

    # Now crop
    (x, y) = np.where(mask == 255)
    (topx, topy) = (np.min(x), np.min(y))
    (bottomx, bottomy) = (np.max(x), np.max(y))
    Cropped = gray[topx:bottomx + 1, topy:bottomy + 1]
    
    # Print number
    text = pytesseract.image_to_string(Cropped, config='--psm 11')
    print("programming_fever's License Plate Recognition\n")
示例#15
0
                                       cv2.CHAIN_APPROX_SIMPLE)
"""
for cnt in contours:    
    area = cv2.contourArea(cnt)
    if (area > 50000) & (area < 52000):
        print(area)
        epsilon = 0.01*cv2.arcLength(cnt,True)
        approx = cv2.approxPolyDP(cnt,epsilon,True)
        cv2.drawContours(img, [approx],0, (0,255,0),3)
"""
#it is necessary to filter the contours via a parameter,
# in this case, we use the concept of area of ​​a geometric figure
for cnt in contours:
    area = cv2.contourArea(cnt)
    if (area > 95000) & (area < 100600):
        print(area)
        epsilon = 0.01 * cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, epsilon, True)
        cv2.drawContours(img, [approx], 0, (0, 255, 0), 3)
"""
for cnt in contours:
    epsilon = 0.01*cv2.arcLength(cnt,True)
    approx = cv2.approxPolyDP(cnt,epsilon,True)
    cv2.drawContours(img, [approx],0, (0,255,0), 3)
"""

cv2.imshow('img', img)  #display final result
cv2.imwrite('8_Detct_black_aera.jpg', img)
#cv2.imwrite("triangl_sh.jpg",img)#save image

cv2.waitKey(0)
edges = cv2.Canny(img,100,100)

plot_images(blur, edges)
cv2.imwrite("data/images/blr.png", laplacian)


image_pat = "{}/{}".format(images_dir, "blr.png")

edg = cv2.imread(image_pat)

_, cnts, new = cv2.findContours(edges.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

image_copy = image.copy()

_ = cv2.drawContours(image_copy, cnts, -1, (106,0,255),2)

plot_images(image, image_copy)

cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:1000]

image_copy = image.copy()
_ = cv2.drawContours(image_copy, cnts, -1, (255,0,255),2)


plot_images(image, image_copy)
plate = None

for c in cnts:
    perimeter = cv2.arcLength(c, True)
    edges_count = cv2.approxPolyDP(c, 0.02 * perimeter, True)
示例#17
0
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray Scale Image", gray)
cv2.waitKey(0)

gray = cv2.bilateralFilter(gray, 11, 17, 17)
#cv2.imshow("Smoother Image", gray)
#cv2.waitKey(0)

edged = cv2.Canny(gray, 170, 200)
cv2.imshow("Canny edge", edged)
cv2.waitKey(0)

cnts, new = cv2.findContours(edged.copy(), cv2.RETR_LIST,
                             cv2.CHAIN_APPROX_SIMPLE)
image1 = image.copy()
cv2.drawContours(image1, cnts, -1, (0, 255, 0), 3)
cv2.imshow("Canny after contouring", image1)
cv2.waitKey(0)

cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:30]
NumberPlateCount = None

image2 = image.copy()
cv2.drawContours(image2, cnts, -1, (0, 255, 0), 3)
#cv2.imshow("TOP 30 Contours", image2)
#cv2.waitKey(0)

count = 0
name = 1

for i in cnts:
示例#18
0
def get_contours(raw_img, img, img_contour, frame_w, frame_h, dead_zone,
                 area_min, green_trackbars):
    direction = 0
    area = 0
    crop_xywh = None

    contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_NONE)
    dead_zone_w = dead_zone
    dea_zone_h = dead_zone - 15

    for cnt in contours:

        area = cv2.contourArea(cnt)
        if area > area_min:

            cv2.drawContours(img_contour, cnt, -1, (255, 0, 255), 3)
            peri = cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)

            x, y, w, h = cv2.boundingRect(approx)
            crop_xywh = x, y, w, h

            if crop_xywh is not None:
                x, y, w, h = crop_xywh
                candidate_img = raw_img[y:y + h, x:x + w]
                candidate_img = cv2.resize(candidate_img, (320, 240))

                mask = np.ones(raw_img.shape[:2])
                mask = cv2.drawContours(mask, [cnt], -1, 0, cv2.FILLED)
                candidate_img2 = raw_img.copy()
                candidate_img2[mask.astype(np.bool), :] = 0

                candidate_img2 = candidate_img2[y:y + h, x:x + w]
                candidate_img2 = cv2.resize(candidate_img2, (320, 240))
            else:
                candidate_img = np.zeros((240, 320, 3), np.uint8)
                candidate_img2 = np.zeros((240, 320, 3), np.uint8)

            cand_contour = candidate_img.copy()
            data_green = green_trackbars.get_trackbar_values()
            area_min_green = data_green[-1]

            cand_dil, cand_res = prepare_img(data_green, candidate_img)
            correct_candidate = get_candidate_contours(cand_dil, cand_contour,
                                                       area_min_green)

            if not correct_candidate:
                no_candidate = np.zeros((240, 320, 3), np.uint8)
                candidate_img2 = np.zeros((240, 320, 3), np.uint8)
                stack_cand = stack_images(
                    1, ([no_candidate, cand_res, img_contour], [
                        cand_dil, candidate_img2,
                        np.zeros((240, 320, 3), np.uint8)
                    ]))
                cv2.imshow('candidate', stack_cand)

            elif correct_candidate:
                cv2.rectangle(img_contour, (x, y), (x + w, y + h), (0, 255, 0),
                              5)

                stack_cand = stack_images(
                    1, ([candidate_img, cand_res, img_contour], [
                        cand_dil, candidate_img2,
                        np.zeros((240, 320, 3), np.uint8)
                    ]))
                cv2.imshow('candidate', stack_cand)

                # cv2.putText(img_contour, "Points: " + str(len(approx)), (x + w + 20, y + 20), cv2.FONT_HERSHEY_COMPLEX, .7,
                #             (0, 255, 0), 2)
                # cv2.putText(img_contour, "Area: " + str(int(area)), (x + w + 20, y + 45), cv2.FONT_HERSHEY_COMPLEX, 0.7,
                #             (0, 255, 0), 2)
                # print(area)
                # cv2.putText(img_contour, " " + str(int(x)) + " " + str(int(y)), (x - 20, y - 45), cv2.FONT_HERSHEY_COMPLEX,
                #             0.7,
                #             (0, 255, 0), 2)

                cx = int(x + (w / 2))
                cy = int(y + (h / 2))
                # print(cx, cy)

                # if cx < int(frame_w / 2) - dead_zone_w:
                #     cv2.putText(img_contour, " GO LEFT ", (20, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 3)
                #     cv2.rectangle(img_contour, (0, int(frame_h / 2 - dea_zone_h)),
                #                   (int(frame_w / 2) - dead_zone_w, int(frame_h / 2) + dea_zone_h), (0, 0, 255),
                #                   cv2.FILLED)
                #     direction = 1
                # elif cx > int(frame_w / 2) + dead_zone_w:
                #     cv2.putText(img_contour, " GO RIGHT ", (20, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 3)
                #     cv2.rectangle(img_contour, (int(frame_w / 2 + dead_zone_w), int(frame_h / 2 - dea_zone_h)),
                #                   (frame_w, int(frame_h / 2) + dea_zone_h), (0, 0, 255), cv2.FILLED)
                #     direction = 2
                # elif cy < int(frame_h / 2) - dea_zone_h:
                #     cv2.putText(img_contour, " GO UP ", (20, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 3)
                #     cv2.rectangle(img_contour, (int(frame_w / 2 - dead_zone_w), 0),
                #                   (int(frame_w / 2 + dead_zone_w), int(frame_h / 2) - dea_zone_h), (0, 0, 255),
                #                   cv2.FILLED)
                #     direction = 3
                # elif cy > int(frame_h / 2) + dea_zone_h:
                #     cv2.putText(img_contour, " GO DOWN ", (20, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 3)
                #     cv2.rectangle(img_contour, (int(frame_w / 2 - dead_zone_w), int(frame_h / 2) + dea_zone_h),
                #                   (int(frame_w / 2 + dead_zone_w), frame_h), (0, 0, 255), cv2.FILLED)
                #     direction = 4
                # else:
                #     direction = 0

                cv2.line(img_contour, (int(frame_w / 2), int(frame_h / 2)),
                         (cx, cy), (0, 0, 255), 3)

                return direction, area, crop_xywh
    return direction, area, crop_xywh
示例#19
0
from cv2 import cv2
imagen=cv2.imread('contorno.jpg')
grises=cv2.cvtColor(imagen,cv2.COLOR_BGR2GRAY)
_,umbral=cv2.threshold(grises,100,255,cv2.THRESH_BINARY)
contorno,jerarquía = cv2.findContours(umbral,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(imagen,contorno,-1,(251, 63, 52),3)
#Mostrar
cv2.imshow('Imagen original',imagen)
#cv2.imshow('Imagen en grises',grises)
#cv2.imshow('Imagen Umbral',umbral)
cv2.waitKey(0)
cv2.destroyAllWindows()
示例#20
0
    moments = cv2.moments(max_contour)
    if moments['m00'] != 0:
        cx = int(moments['m10'] /
                 moments['m00'])  #Calculation for the center points of hand
        cy = int(moments['m01'] / moments['m00'])

    center = (cx, cy)

    cv2.circle(cropped, center, 10, [0, 0, 255], 2)

    if max_area != 0:

        epsilon = 0.25 * cv2.arcLength(max_contour, True)
        approx = cv2.approxPolyDP(max_contour, epsilon, True)

        cv2.drawContours(cropped, [max_contour], -1, (0, 255, 0), 2)
        hull = cv2.convexHull(max_contour, returnPoints=True)
        hull_area = cv2.contourArea(hull)

        cv2.drawContours(cropped, [hull], 0, (0, 0, 255), 2)
        hull = cv2.convexHull(max_contour, returnPoints=False)
        defects = cv2.convexityDefects(max_contour, hull)

        if defects is not None:
            count = 0
            for i in range(defects.shape[0]):
                s, e, f, d = defects[i, 0]

                start = tuple(max_contour[s][0])
                end = tuple(max_contour[e][0])
                far = tuple(max_contour[f][0])
示例#21
0
# ........gray_left = cv2.cvtColor(left_eye_image, cv2.COLOR_BGR2GRAY)
# ........gray_right = cv2.cvtColor(right_eye_image, cv2.COLOR_BGR2GRAY)
# ........gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# ........ret,thresh_left = cv2.threshold(gray_left,THRESH_CONST,255,cv2.THRESH_BINARY_INV)
# ........ret,thresh_right = cv2.threshold(gray_right,THRESH_CONST,255,cv2.THRESH_BINARY_INV)

# average the eye aspect ratio together for both eyes

        ear = (leftEAR + rightEAR) / 2.0

        # compute the convex hull for the left and right eye, then
        # visualize each of the eyes

        leftEyeHull = cv2.convexHull(leftEye)
        rightEyeHull = cv2.convexHull(rightEye)
        cv2.drawContours(frame, [leftEyeHull], -1, (0, 0xFF, 0), 1)
        cv2.drawContours(frame, [rightEyeHull], -1, (0, 0xFF, 0), 1)

        # check to see if the eye aspect ratio is below the blink
        # threshold, and if so, increment the blink frame counter

        if ear < EYE_AR_THRESH:
            COUNTER += 1
        else:

            # otherwise, the eye aspect ratio is not below the blink
            # threshold
            # if the eyes were closed for a sufficient number of
            # then increment the total number of blinks

            if COUNTER >= EYE_AR_CONSEC_FRAMES:
示例#22
0
from cv2 import cv2 as cv

img_color = cv.imread("datas/images/shapes.png")
img_gray = cv.cvtColor(img_color, cv.COLOR_BGR2GRAY)
ret, img_binary = cv.threshold(img_gray, 127, 255, 0)
contours, _ = cv.findContours(
    img_binary, cv.RETR_LIST,
    cv.CHAIN_APPROX_SIMPLE)  # findContours(img, mode, method)
# https://docs.opencv.org/4.4.0/d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0

for contour in contours:
    area = cv.contourArea(contour)
    cv.drawContours(
        img_color, [contour], 0, (255, 0, 0),
        1)  # contours가 list형태로 되어있어, 형변환 없이 contour도 list타입으로 받기 위해 []를 씌워줌

cv.imshow("Result", img_color)
cv.waitKey(0)
'''
What is contours?
A curve joining all the continuous points, havinig same color or intensity(강도,세기).
Contours are a useful tool for Shape Analysis and Object Detection and Recognition

1. better accuracy, use binary images. So before finding contours, apply threshold or canny edge detection.
2. FindContours function modifies the source images.
3. Findig contours is like finding white object from black background. So, object to be found should be white and background should be black.

Reference : https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contours_begin/py_contours_begin.html#contours-getting-started
'''
示例#23
0
       ret,frame2=cam.read()
       
       cv2.imshow('original frame',frame1)
       
       emailImg=cam.read()[1]
       frame1=frame1[290:480,320:490]
       frame2=frame2[290:480,320:490]
       black=np.zeros(frame1.shape,np.uint8)

       diff=cv2.absdiff(frame1,frame2)
       diff=cv2.cvtColor(diff,cv2.COLOR_BGR2GRAY)
       diff=cv2.GaussianBlur(diff,(5,5),0)
       ret,diff=cv2.threshold(diff,34,255,cv2.THRESH_BINARY)
       diff=cv2.dilate(diff,None,iterations=3)
       contours,_=cv2.findContours(diff,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
       cv2.drawContours(frame1,contours,-1,(0,255,255),2)
       
       path=f'opencv tut/{t.ctime(t.time())[11:19]}.png'.replace(':','')
       for c in contours:
            if cv2.contourArea(c)<7000:
               continue
            x,y,w,h=cv2.boundingRect(c)
            cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,255),4)
            cv2.rectangle(black,(x,y),(x+w,y+h),(0,255,255),-1) 

            if flag:
               pass
               cv2.imwrite(path,emailImg)
               sendmail(path) 
            flag=False
            #cv2.imwrite('hi.png',emailImg)
示例#24
0
def make_binary_mask(contour, img_dims):
    mask = np.zeros(img_dims, dtype=np.uint8)
    cv2.drawContours(mask, [contour], 0, 1, cv2.FILLED)

    # return boolean array
    return mask
示例#25
0
def drawContours(img_rgb, contours):
    for cnt in contours:
        area = cv2.contourArea(cnt)
        cv2.drawContours(img_rgb, [cnt], 0, (255,0,0), 1)
    return img_rgb
示例#26
0
def tracker(video_path,
            background_full,
            rois,
            threshold=5,
            display=True,
            area_min=0,
            area_max=1000,
            split_range=False):
    """ Function that takes a video path, a background file, rois, threshold and display switch. This then uses
    background subtraction and centroid tracking to find the XZ coordinates of the largest contour. Saves out a csv file
     with frame #, X, Y, contour area"""

    print("tracking {}".format(video_path))

    # As camera is often excluded, check here and buffer if not included
    if len(rois) == 1:
        rois['cam'] = 'unknown'

    # load video
    video = cv2.VideoCapture(video_path)

    if display:
        # create display window
        cv2.namedWindow("Live thresholded")
        cv2.namedWindow("Live")

    # as there can be multiple rois the writer, data and moviename are kept in lists
    data = list()
    frame_id = 0
    for roi in np.arange(0, len(rois) - 1):
        data.append(list())

    if split_range is False:
        total = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
        split_range = [0, total + 1]
        split_name = False
    else:
        split_name = True

    while video.isOpened():
        ret, frame = video.read()
        if not ret:
            print("reached end of video")
            video.release()
            break
        if frame_id in np.arange(split_range[0], split_range[1]):
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            frameDelta_full = cv2.absdiff(background_full, gray)

            # tracking
            cx = list()
            cy = list()
            contourOI = list()
            contourOI_ = list()
            for roi in range(0, len(rois) - 1):
                # for the frame define an ROI and crop image
                curr_roi = rois["roi_" + str(roi)]
                frameDelta = frameDelta_full[curr_roi[1]:curr_roi[1] +
                                             curr_roi[3],
                                             curr_roi[0]:curr_roi[0] +
                                             curr_roi[2]]
                image_thresholded = cv2.threshold(frameDelta, threshold, 255,
                                                  cv2.THRESH_TOZERO)[1]
                (contours, _) = cv2.findContours(image_thresholded,
                                                 cv2.RETR_EXTERNAL,
                                                 cv2.CHAIN_APPROX_SIMPLE)
                if len(contours) > 0:
                    contourOI_.append(max(contours, key=cv2.contourArea))
                    area = cv2.contourArea(contourOI_[roi])
                    if (area > area_min) and (area < area_max):
                        contourOI.append(cv2.convexHull(contourOI_[roi]))
                        M = cv2.moments(contourOI[roi])
                        cx.append(int(M["m10"] / M["m00"]))
                        cy.append(int(M["m01"] / M["m00"]))
                        data[roi].append((frame_id, cx[roi], cy[roi], area))
                    else:
                        print(
                            "no large enough contour found for roi {}!".format(
                                roi))
                        data[roi].append((frame_id, np.nan, np.nan, np.nan))
                        contourOI_[-1] = False
                        contourOI.append(False)
                        cx.append(np.nan)
                        cy.append(np.nan)
                else:
                    print("no contour found for roi {}!".format(roi))
                    data[roi].append((frame_id, np.nan, np.nan, np.nan))
                    contourOI_.append(False)
                    contourOI.append(False)
                    cx.append(np.nan)
                    cy.append(np.nan)

            if frame_id % 500 == 0:
                print("Frame {}".format(frame_id))
            if display:
                full_image_thresholded = (cv2.threshold(
                    frameDelta_full, threshold, 255, cv2.THRESH_TOZERO)[1])
                # Live display of full resolution and ROIs
                cv2.putText(full_image_thresholded,
                            "Framenum: {}".format(frame_id),
                            (30, full_image_thresholded.shape[0] - 30),
                            cv2.FONT_HERSHEY_SIMPLEX,
                            fontScale=0.5,
                            color=255)

                for roi in range(0, len(rois) - 1):
                    if np.all(contourOI_[roi] != False):
                        curr_roi = rois["roi_" + str(roi)]
                        # add in contours
                        corrected_contour = np.empty(contourOI_[roi].shape)
                        corrected_contour[:, 0,
                                          0] = contourOI_[roi][:, 0,
                                                               0] + curr_roi[0]
                        corrected_contour[:, 0,
                                          1] = contourOI_[roi][:, 0,
                                                               1] + curr_roi[1]
                        cv2.drawContours(full_image_thresholded,
                                         corrected_contour.astype(int), -1,
                                         255, 1)

                        # add in centroid
                        cv2.circle(
                            full_image_thresholded,
                            (cx[roi] + curr_roi[0], cy[roi] + curr_roi[1]), 8,
                            255, 1)

                cv2.imshow("Live thresholded", full_image_thresholded)
                cv2.imshow("Live", gray)
                cv2.waitKey(1)

                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break

        frame_id += 1

    # saving data
    print("Saving data output")
    date = datetime.datetime.now().strftime("%Y%m%d")

    for roi in range(0, len(rois) - 1):
        datanp = np.array(data[roi])
        if split_name is False:
            filename = video_path[
                0:-4] + "_tracks_{}_Thresh_{}_Area_{}_roi-{}.csv".format(
                    date, threshold, area_min, roi)
        else:
            range_s = str(split_range[0]).zfill(5)
            range_e = str(split_range[1]).zfill(5)
            filename = video_path[
                0:-4] + "_tracks_{}_Thresh_{}_Area_{}_Range{}-{}_.csv".format(
                    date, threshold, area_min, range_s, range_e)
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        np.savetxt(filename, datanp, delimiter=",")

    print("Tracking finished on video cleaning up")
    cv2.destroyAllWindows()
示例#27
0
img = cv.imread('Photos/cat.jpg')
cv.imshow('Cat', img)

# To draw contours
blank1 = np.zeros(img.shape, dtype='uint8')
# cv.imshow('Blank1',blank1)
blank2 = np.zeros(img.shape, dtype='uint8')
# cv.imshow('Blank2',blank2)

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow('Gray', gray)

canny = cv.Canny(gray, 125, 125)
cv.imshow('Canny Edges', canny)

contours, hierarchies = cv.findContours(canny, cv.RETR_LIST,
                                        cv.CHAIN_APPROX_NONE)
print(f'{len(contours)} contour(s) found in canny!')
cv.drawContours(blank1, contours, -1, (255, 255, 255), 1)
cv.imshow('Contours drawn for canny', blank1)

ret, thresh = cv.threshold(gray, 125, 255, cv.THRESH_BINARY)
cv.imshow('Thresh', thresh)

contours, hierarchies = cv.findContours(thresh, cv.RETR_LIST,
                                        cv.CHAIN_APPROX_NONE)
print(f'{len(contours)} contour(s) found in thresh!')
cv.drawContours(blank2, contours, -1, (255, 255, 255), 1)
cv.imshow('Contours drawn for thresh', blank2)

cv.waitKey(0)
示例#28
0
#variable para cargar la imagen
original = cv2.imread('monedassoles.jpg')
#pasar a escalas grises
gris = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
#es un suavizado para desenfoque para eliminar ruidos
gauss = cv2.GaussianBlur(gris, (valorGauss, valorGauss),
                         0)  #para el modelado gausiano se necesita una matriz
canny = cv2.Canny(gauss, 60, 100)
#contornos de afuera, se trabaja con matrices
kernel = np.ones((valorKernel, valorKernel), np.uint8)
cierre = cv2.morphologyEx(canny, cv2.MORPH_CLOSE, kernel)

#devuelven dos valores contornos y jerarquía
contornos, jerarquía = cv2.findContours(cierre.copy(), cv2.RETR_EXTERNAL,
                                        cv2.CHAIN_APPROX_SIMPLE)

print("monedas encontradas: {}".format(len(contornos)))

#dibuja el contorno de linea 19
cv2.drawContours(original, contornos, -1, (0, 0, 255), 2)

#Mostrar resultados
#cv2.imshow("Grises",gris)
#cv2.imshow("gauss",gauss)
#cv2.imshow("canny",canny)
#cv2.imshow("cierre",cierre)

#mostrar las imagenes
cv2.imshow("Resultado", original)
#para que no se cierre la imagen y quede hasta cerrar
cv2.waitKey(0)
示例#29
0
                            thresh=thresh,
                            maxval=max_val,
                            type=cv2.THRESH_BINARY_INV)
print(dst_bin.shape)

# find all contours in the image
contours, hierarchy = cv2.findContours(dst_bin, cv2.RETR_EXTERNAL,
                                       cv2.CHAIN_APPROX_NONE)

# # then find bounding box ROI
# new_image = dst_bin.copy()
# print(new_image.shape)

# print(contours)

cv2.drawContours(raw_img, contours, -1, (0, 255, 0), 1)

# cv2.imshow("out", new_image)
plt.imshow(raw_img[:, :, ::-1])
#plt.show()
#%%

for cnt in contours:
    x, y, w, h = cv2.boundingRect(cnt)
    print(x, y, w, h)

    # extract the ROI
    pad = 0
    print("gone")
    # roi = new_image[y - pad:y + h + pad, x - pad:x + w + pad]
示例#30
0
img = cv2.imread("fuzzy.png",1) 

hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)

hsv_split = np.concatenate((hsv[:,:,0],hsv[:,:,1],hsv[:,:,2]),axis=1)
cv2.imshow("HSV Split",hsv_split)

#Dilating Saturation channel and thresholding to get segmentation
kernel=np.ones((3,3),'uint8')
dilate=cv2.dilate(hsv[:,:,1],kernel,iterations=1)
cv2.imshow("S Dilation",dilate)
ret,dilate_thresh = cv2.threshold(dilate,200,255,cv2.THRESH_BINARY)
cv2.imshow("S Dilate Trheshold",dilate_thresh)


#Contours
canvas = np.ones(img.shape,'uint8') * 255
contours,heirarchy = cv2.findContours(dilate_thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
    area = cv2.contourArea(c)
    perim = cv2.arcLength(c,True)
    print("Perimeter: {}, Area: {}".format(perim,area))
    if area > 1000:
        cv2.drawContours(canvas,[c],-1,(rand.randint(0,255),0,rand.randint(0,255)),-1)

cv2.imshow("FINAL RESULT",canvas)


cv2.waitKey(0)
cv2.destroyAllWindows()