Python cv2.isContourConvex() Examples

The following are 22 code examples of cv2.isContourConvex(). 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: squares.py    From OpenCV-Python-Tutorial with MIT License 9 votes vote down vote up
def find_squares(img):
    img = cv2.GaussianBlur(img, (5, 5), 0)
    squares = []
    for gray in cv2.split(img):
        for thrs in xrange(0, 255, 26):
            if thrs == 0:
                bin = cv2.Canny(gray, 0, 50, apertureSize=5)
                bin = cv2.dilate(bin, None)
            else:
                retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
            bin, contours, hierarchy = cv2.findContours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
            for cnt in contours:
                cnt_len = cv2.arcLength(cnt, True)
                cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)
                if len(cnt) == 4 and cv2.contourArea(cnt) > 1000 and cv2.isContourConvex(cnt):
                    cnt = cnt.reshape(-1, 2)
                    max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
                    if max_cos < 0.1:
                        squares.append(cnt)
    return squares 
Example #2
Source File: detect_tables.py    From namsel with MIT License 6 votes vote down vote up
def find_boxes(tiff_fl, blur=False):
    im = Image.open(tiff_fl).convert('L')
    a = np.asarray(im)
    if blur:
        a = cv.GaussianBlur(a, (5, 5), 0)
    contours, hierarchy = cv.findContours(a.copy(), mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_SIMPLE)
    border_boxes = []
#     n = np.ones_like(a)
    for j,cnt in enumerate(contours):
        cnt_len = cv.arcLength(cnt, True)
        orig_cnt = cnt.copy()
        cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True)
        if len(cnt) == 4 and ((a.shape[0]-3) * (a.shape[1] -3)) > cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt):
            cnt = cnt.reshape(-1, 2)
            max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
            if max_cos < 0.1:
                b = cv.boundingRect(orig_cnt)
                x,y,w,h = b
                border_boxes.append(b)
#                 cv.rectangle(n, (x,y), (x+w, y+h), 0)
#                 cv.drawContours(n, [cnt], -1,0, thickness = 5)
#     Image.fromarray(n*255).show()
    return border_boxes 
Example #3
Source File: ocr_controller.py    From JusticeAI with MIT License 6 votes vote down vote up
def _find_document_corners(resized_img):
    contours = _compute_all_contours(resized_img)
    resized_height, resized_width = _get_img_dimensions(resized_img)
    full_resized_image_area = resized_height * resized_width

    # Default to the smallest possible document area and save any larger document areas
    largest_document_area = full_resized_image_area * ALIGNMENT_PERCENT_AREA_DOCUMENT_MUST_COVER

    # Default to largest: no modification to the image if no document is found
    largest_document_corners = _get_corner_array(resized_height, resized_width)

    for contour in contours:
        contour_perimeter = cv2.arcLength(contour, True)
        approximate_polygonal_contour = cv2.approxPolyDP(contour, 0.03 * contour_perimeter, True)

        # All pages have 4 corners and are convex
        if (len(approximate_polygonal_contour) == 4 and
                cv2.isContourConvex(approximate_polygonal_contour) and
                cv2.contourArea(approximate_polygonal_contour) > largest_document_area):
            largest_document_area = cv2.contourArea(approximate_polygonal_contour)
            largest_document_corners = approximate_polygonal_contour

    return largest_document_corners 
Example #4
Source File: squares.py    From PyCV-time with MIT License 5 votes vote down vote up
def find_squares(img):
    img = cv2.GaussianBlur(img, (5, 5), 0)
    squares = []
    for gray in cv2.split(img):
        for thrs in xrange(0, 255, 26):
            if thrs == 0:
                bin = cv2.Canny(gray, 0, 50, apertureSize=5)
                bin = cv2.dilate(bin, None)
            else:
                retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
            contours, hierarchy = cv2.findContours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
            for cnt in contours:
                cnt_len = cv2.arcLength(cnt, True)
                cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)
                if len(cnt) == 4 and cv2.contourArea(cnt) > 1000 and cv2.isContourConvex(cnt):
                    cnt = cnt.reshape(-1, 2)
                    max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
                    if max_cos < 0.1:
                        squares.append(cnt)
    return squares 
Example #5
Source File: find_polygon.py    From PyCV-time with MIT License 5 votes vote down vote up
def imgproc(frame):
    
    # convert color to gray scale and show it
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('gray', gray)
    
    blur = cv2.blur(gray, (5,5))
    edge = cv2.Canny(blur, 30, 100)
    edge = cv2.blur(edge, (2,2))
    cv2.imshow('blured edge', edge)
    
    
    # convert image to black and white and show it
    thresh1, thresh = cv2.threshold(edge, 60, 255, cv2.THRESH_BINARY)
    cv2.imshow('thresh', thresh)
    
    # find contours!
    contours, hry = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    
    # draw all the contours
    cpframe = frame.copy()
    cv2.drawContours(cpframe, contours, -1, (0,255,0), 3)
    cv2.imshow('cpframe', cpframe)
    
    # ================== TODO ===================
    
    # Modify these code to suit your need
    contours = [ctr for ctr in contours if cv2.contourArea(ctr) > 100]
    contours = [cv2.approxPolyDP(ctr, 5 , True) for ctr in contours]
    contours = [ctr for ctr in contours if cv2.isContourConvex(ctr)]
    #contours = [ctr for ctr in contours if len(ctr) == 3]
    #contours = [ctr for ctr in contours if len(ctr) == 4]
    contours = [ctr for ctr in contours if is_circle(ctr)]
    
    # ============================================
    
    
    # draw on the frame
    cv2.drawContours(frame, contours, -1, (0,255,0), 3)
    
    return frame 
Example #6
Source File: _whale176-square.py    From PyCV-time with MIT License 5 votes vote down vote up
def imgproc(frame):
    # convert color to gray scale and show it
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('gray', gray)

    blur = cv2.blur(gray, (5, 5))
    edge = cv2.Canny(blur, 10, 100)
    edge = cv2.blur(edge, (2, 2))
    cv2.imshow('blured edge', edge)

    # convert image to black and white and show it
    thresh1, thresh = cv2.threshold(edge, 60, 120, cv2.THRESH_BINARY)
    cv2.imshow('thresh', thresh)

    # find contours!
    contours, hry = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # draw all the contours
    cpframe = frame.copy()
    cv2.drawContours(cpframe, contours, -1, (0, 255, 0), 3)
    cv2.imshow('cpframe', cpframe)

    # ================== TODO ===================

    # Modify these code to suit your need
    contours = [ctr for ctr in contours if cv2.contourArea(ctr) > 100]
    contours = [cv2.approxPolyDP(ctr, 5, True) for ctr in contours]
    contours = [ctr for ctr in contours if len(ctr) == 4]

    edges = [LA.norm(a - b) for a, b in zip(simp_ctr, np.roll(simp_ctr, 2))]
    ratios = [(1 - e / edges[0]) ** 2 for e in edges]

    print(contours)
    # squares = [square for square in contours if find_square(contours)]
    contours = [ctr for ctr in contours if cv2.isContourConvex(ctr)]

    # ============================================

    # draw on the frame
    cv2.drawContours(frame, contours, -1, (0, 255, 0), 3)
    return frame 
Example #7
Source File: whale176-triangle.py    From PyCV-time with MIT License 5 votes vote down vote up
def imgproc(frame):
    # convert color to gray scale and show it
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('gray', gray)

    blur = cv2.blur(gray, (5, 5))
    edge = cv2.Canny(blur, 10, 100)
    edge = cv2.blur(edge, (2, 2))
    cv2.imshow('blured edge', edge)

    # convert image to black and white and show it
    thresh1, thresh = cv2.threshold(edge, 60, 120, cv2.THRESH_BINARY)
    cv2.imshow('thresh', thresh)

    # find contours!
    contours, hry = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # draw all the contours
    cpframe = frame.copy()
    cv2.drawContours(cpframe, contours, -1, (0, 255, 0), 3)
    cv2.imshow('cpframe', cpframe)

    # ================== TODO ===================

    # Modify these code to suit your need
    contours = [ctr for ctr in contours if cv2.contourArea(ctr) > 100]
    contours = [cv2.approxPolyDP(ctr, 5, True) for ctr in contours]
    contours = [ctr for ctr in contours if len(ctr) == 3]
    contours = [ctr for ctr in contours if cv2.isContourConvex(ctr)]

    # ============================================

    # draw on the frame
    cv2.drawContours(frame, contours, -1, (0, 255, 0), 3)
    return frame 
Example #8
Source File: whale176-circle.py    From PyCV-time with MIT License 5 votes vote down vote up
def imgproc(frame):
    # convert color to gray scale and show it
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('gray', gray)

    blur = cv2.blur(gray, (5, 5))
    edge = cv2.Canny(blur, 10, 100)
    edge = cv2.blur(edge, (2, 2))
    cv2.imshow('blured edge', edge)

    # convert image to black and white and show it
    thresh1, thresh = cv2.threshold(edge, 60, 120, cv2.THRESH_BINARY)
    cv2.imshow('thresh', thresh)

    # find contours!
    contours, hry = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # draw all the contours
    cpframe = frame.copy()
    cv2.drawContours(cpframe, contours, -1, (0, 255, 0), 3)
    cv2.imshow('cpframe', cpframe)

    # ================== TODO ===================

    # Modify these code to suit your need
    contours = [ctr for ctr in contours if cv2.contourArea(ctr) > 20]
    contours = [cv2.approxPolyDP(ctr, 5, True) for ctr in contours]
    contours = [ctr for ctr in contours if len(ctr) > 10]
    contours = [ctr for ctr in contours if cv2.isContourConvex(ctr)]

    # ============================================

    # draw on the frame
    cv2.drawContours(frame, contours, -1, (0, 255, 0), 3)
    return frame 
Example #9
Source File: whale176-rectangle.py    From PyCV-time with MIT License 5 votes vote down vote up
def imgproc(frame):
    # convert color to gray scale and show it
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('gray', gray)

    blur = cv2.blur(gray, (5, 5))
    edge = cv2.Canny(blur, 10, 100)
    edge = cv2.blur(edge, (2, 2))
    cv2.imshow('blured edge', edge)

    # convert image to black and white and show it
    thresh1, thresh = cv2.threshold(edge, 60, 120, cv2.THRESH_BINARY)
    cv2.imshow('thresh', thresh)

    # find contours!
    contours, hry = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # draw all the contours
    cpframe = frame.copy()
    cv2.drawContours(cpframe, contours, -1, (0, 255, 0), 3)
    cv2.imshow('cpframe', cpframe)

    # ================== TODO ===================

    # Modify these code to suit your need
    contours = [ctr for ctr in contours if cv2.contourArea(ctr) > 100]
    contours = [cv2.approxPolyDP(ctr, 5, True) for ctr in contours]
    contours = [ctr for ctr in contours if len(ctr) == 4]
    contours = [ctr for ctr in contours if cv2.isContourConvex(ctr)]

    # ============================================

    # draw on the frame
    cv2.drawContours(frame, contours, -1, (0, 255, 0), 3)
    return frame 
Example #10
Source File: find_polygon.py    From PyCV-time with MIT License 5 votes vote down vote up
def imgproc(frame):
    
    # convert color to gray scale and show it
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('gray', gray)
    
    blur = cv2.blur(gray, (5,5))
    edge = cv2.Canny(blur, 30, 100)
    edge = cv2.blur(edge, (2,2))
    cv2.imshow('blured edge', edge)
    
    
    # convert image to black and white and show it
    thresh1, thresh = cv2.threshold(edge, 60, 255, cv2.THRESH_BINARY)
    cv2.imshow('thresh', thresh)
    
    # find contours!
    contours, hry = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    
    # draw all the contours
    cpframe = frame.copy()
    cv2.drawContours(cpframe, contours, -1, (0,255,0), 3)
    cv2.imshow('cpframe', cpframe)
    
    # ================== TODO ===================
    
    # Modify these code to suit your need
    contours = [ctr for ctr in contours if cv2.contourArea(ctr) > 100]
    contours = [cv2.approxPolyDP(ctr, 5 , True) for ctr in contours]
    contours = [ctr for ctr in contours if cv2.isContourConvex(ctr)]
    
    # ============================================
    
    
    # draw on the frame
    cv2.drawContours(frame, contours, -1, (0,255,0), 3)
    
    return frame 
Example #11
Source File: toolbox_opencv.py    From remi with Apache License 2.0 5 votes vote down vote up
def on_new_image_listener(self, emitter):
        try:
            self.image_source = emitter
            if emitter.img is None:
                return
            _retrieval_mode = self.contour_retrieval_mode[self.retrieval_mode] if type(self.retrieval_mode) == str else self.retrieval_mode
            _approximation_method = self.contour_approximation_method[self.approximation_method] if type(self.approximation_method) == str else self.approximation_method
            major = cv2.__version__.split('.')[0]
            img = emitter.img.copy()
            if major == '3':
                img, self.contours, self.hierarchy = cv2.findContours(img, _retrieval_mode, _approximation_method)
            else:
                self.contours, self.hierarchy = cv2.findContours(img, _retrieval_mode, _approximation_method)
            filtered_contours_indices = []
            for ic in range(0, len(self.contours)):
                c = self.contours[ic]
                if not (self.__discard_convex and cv2.isContourConvex(c)):
                    if not (self.__discard_non_convex and not cv2.isContourConvex(c)):
                        l = cv2.arcLength(c, True)
                        if l>self.__min_arc_length and l<self.__max_arc_length:
                            area = cv2.contourArea(c)
                            if area>self.__min_contour_area and area<self.__max_contour_area:
                                #https://answers.opencv.org/question/21101/circularity-of-a-connected-component/
                                roundness = (4.0*area) / (math.pi* (l/math.pi)**2)  #4 Area / (pi Max-diam^2)
                                if roundness>self.__min_roundness and roundness<self.__max_roundness:
                                    filtered_contours_indices.append(ic)

            #drawing selected contours
            img.fill(255)
            for i in filtered_contours_indices:
                img = cv2.drawContours(img, self.contours, i, 0, 1, cv2.LINE_AA)
            self.set_image_data(img)
            self.on_new_contours_result()
        except Exception:
            print(traceback.format_exc()) 
Example #12
Source File: find_contour.py    From PyCV-time with MIT License 5 votes vote down vote up
def imgproc(frame):
    
    # convert color to gray scale and show it
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('gray', gray)
    
    # convert image to black and white and show it
    thresh1, thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY)
    cv2.imshow('thresh', thresh)
    
    # find contours!
    contours, hry = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    
    # draw all the contours
    cpframe = frame.copy()
    cv2.drawContours(cpframe, contours, -1, (0,255,0), 3)
    cv2.imshow('cpframe', cpframe)
    
    # do various tests and modification
    contours = [ctr for ctr in contours if cv2.contourArea(ctr) > 100]
    contours = [cv2.approxPolyDP(ctr, 5 , True) for ctr in contours]
    contours = [ctr for ctr in contours if cv2.isContourConvex(ctr)]
    
    # draw on the frame
    cv2.drawContours(frame, contours, -1, (0,255,0), 3)
    
    return frame 
Example #13
Source File: process_image.py    From RealTime-DigitRecognition with GNU General Public License v3.0 5 votes vote down vote up
def get_output_image(path):
  
    img = cv2.imread(path,2)
    img_org =  cv2.imread(path)

    ret,thresh = cv2.threshold(img,127,255,0)
    im2,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

    for j,cnt in enumerate(contours):
        epsilon = 0.01*cv2.arcLength(cnt,True)
        approx = cv2.approxPolyDP(cnt,epsilon,True)
        
        hull = cv2.convexHull(cnt)
        k = cv2.isContourConvex(cnt)
        x,y,w,h = cv2.boundingRect(cnt)
        
        if(hierarchy[0][j][3]!=-1 and w>10 and h>10):
            #putting boundary on each digit
            cv2.rectangle(img_org,(x,y),(x+w,y+h),(0,255,0),2)
            
            #cropping each image and process
            roi = img[y:y+h, x:x+w]
            roi = cv2.bitwise_not(roi)
            roi = image_refiner(roi)
            th,fnl = cv2.threshold(roi,127,255,cv2.THRESH_BINARY)

            # getting prediction of cropped image
            pred = predict_digit(roi)
            print(pred)
            
            # placing label on each digit
            (x,y),radius = cv2.minEnclosingCircle(cnt)
            img_org = put_label(img_org,pred,x,y)

    return img_org 
Example #14
Source File: find_polygons.py    From PyCV-time with MIT License 4 votes vote down vote up
def find_polygons(gray_image_in, edge_num, tolerance=0.1, area_threshold=100, convex_only=True, edge_threshold=60, orientation=1.0):
    """find contours that appears to be a """
    img = gray_image_in.copy()
    lo, hi = 100, 150
    
    # cv2.imshow('img', img)
    edge = cv2.Canny(img, lo, hi)
    # imshow('edge', edge)
    thresh1, dst = cv2.threshold(edge,edge_threshold,255, cv2.THRESH_BINARY)
    # imshow('thresh', dst)
    ctr, hry = cv2.findContours(dst, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    # cv2.imshow('fndctr', dst)
    
    if hry is None: return []
    hry = hry[0]
    
    polygons = []
    for cnt in ctr:

        # kill the contour if it doesn't look like a square
        cnt = cnt.reshape(-1,2)
        epsilon = tolerance * 2 * ((3.14 * cv2.contourArea(cnt)) ** 0.5)
        tmp = cv2.approxPolyDP(cnt,epsilon,True)

        if len(tmp) != edge_num: continue
        if convex_only and not cv2.isContourConvex(tmp): continue 
        if cv2.contourArea(tmp) < area_threshold: continue
        
        # now sort the points in counter clock wise so we can eliminate similar solutions
        cross_product = np.cross(tmp[1] - tmp[0], tmp[2] - tmp[1])[0]
        if cross_product * orientation > 0:
            tmp = np.flipud(tmp)
        
        # rearrange the points so that the returned point array always start with
        # the point that is closest to origin
        tmp = tmp.reshape(-1,2)
        distance_from_origin = map(lambda pt: pt[0] ** 2 + pt[1] ** 2, tmp)
        val, idx = min((val, idx) for (idx, val) in enumerate(distance_from_origin))
        
        if idx > 0:
            up, down = np.vsplit(tmp, [idx])
            tmp = np.vstack((down, up))
        
        polygons.append(tmp)
    
    return polygons 
Example #15
Source File: Video_find_square_0702.py    From PyCV-time with MIT License 4 votes vote down vote up
def find_square(frame_in):
    frame_out = frame_in.copy()
    frame_gray = cv2.cvtColor(frame_in, cv2.COLOR_BGR2GRAY)
    #thresh = threshold(frame_gray,110)
    thresh = adap_threshold(frame_gray)
    frame_blur = cv2.blur(thresh, (3,3))
    #cv2.imshow('Threhold',thresh)
    contours, hry = cv2.findContours(frame_blur, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    #identify squares
    squares = []
    for cnt in contours:
        # Calculate the perimeter
        cnt_len = cv2.arcLength(cnt, True)
        # Simpler Contour approximation 
        cnt = cv2.approxPolyDP(cnt, 0.01 * cnt_len, True)
        if  cv2.contourArea(cnt) > 10 and len(cnt) == 4 and cv2.isContourConvex(cnt) :
            cnt = cnt.reshape(-1, 2) # cnt is divided into two column 
            max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
            if max_cos < 0.1 and equal(cnt[0], cnt[1], cnt[2],0.2):
                 squares.append(cnt)
    cv2.drawContours(frame_out , squares, -1, (0,255,0), 2)
   
    return frame_out 
Example #16
Source File: find_polygons.py    From PyCV-time with MIT License 4 votes vote down vote up
def find_polygons(gray_image_in, edge_num, tolerance=0.1, area_threshold=100, convex_only=True, edge_threshold=60, orientation=1.0):
    """find contours that appears to be a """
    img = gray_image_in.copy()
    lo, hi = 100, 150
    
    # cv2.imshow('img', img)
    edge = cv2.Canny(img, lo, hi)
    # imshow('edge', edge)
    thresh1, dst = cv2.threshold(edge,edge_threshold,255, cv2.THRESH_BINARY)
    # imshow('thresh', dst)
    ctr, hry = cv2.findContours(dst, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    # cv2.imshow('fndctr', dst)
    
    if hry is None: return []
    hry = hry[0]
    
    polygons = []
    for cnt in ctr:

        # kill the contour if it doesn't look like a square
        cnt = cnt.reshape(-1,2)
        epsilon = tolerance * 2 * ((3.14 * cv2.contourArea(cnt)) ** 0.5)
        tmp = cv2.approxPolyDP(cnt,epsilon,True)

        if len(tmp) != edge_num: continue
        if convex_only and not cv2.isContourConvex(tmp): continue 
        if cv2.contourArea(tmp) < area_threshold: continue
        
        # now sort the points in counter clock wise so we can eliminate similar solutions
        cross_product = np.cross(tmp[1] - tmp[0], tmp[2] - tmp[1])[0]
        if cross_product * orientation > 0:
            tmp = np.flipud(tmp)
        
        # rearrange the points so that the returned point array always start with
        # the point that is closest to origin
        tmp = tmp.reshape(-1,2)
        distance_from_origin = map(lambda pt: pt[0] ** 2 + pt[1] ** 2, tmp)
        val, idx = min((val, idx) for (idx, val) in enumerate(distance_from_origin))
        
        if idx > 0:
            up, down = np.vsplit(tmp, [idx])
            tmp = np.vstack((down, up))
        
        polygons.append(tmp)
    
    return polygons 
Example #17
Source File: find_polygons.py    From PyCV-time with MIT License 4 votes vote down vote up
def find_polygons(gray_image_in, edge_num, tolerance=0.1, area_threshold=100, convex_only=True, edge_threshold=60, orientation=1.0):
    """find contours that appears to be a """
    img = gray_image_in.copy()
    lo, hi = 100, 150
    
    # cv2.imshow('img', img)
    edge = cv2.Canny(img, lo, hi)
    # imshow('edge', edge)
    thresh1, dst = cv2.threshold(edge,edge_threshold,255, cv2.THRESH_BINARY)
    # imshow('thresh', dst)
    ctr, hry = cv2.findContours(dst, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    # cv2.imshow('fndctr', dst)
    
    if hry is None: return []
    hry = hry[0]
    
    polygons = []
    for cnt in ctr:

        # kill the contour if it doesn't look like a square
        cnt = cnt.reshape(-1,2)
        epsilon = tolerance * 2 * ((3.14 * cv2.contourArea(cnt)) ** 0.5)
        tmp = cv2.approxPolyDP(cnt,epsilon,True)

        if len(tmp) != edge_num: continue
        if convex_only and not cv2.isContourConvex(tmp): continue 
        if cv2.contourArea(tmp) < area_threshold: continue
        
        # now sort the points in counter clock wise so we can eliminate similar solutions
        cross_product = np.cross(tmp[1] - tmp[0], tmp[2] - tmp[1])[0]
        if cross_product * orientation > 0:
            tmp = np.flipud(tmp)
        
        # rearrange the points so that the returned point array always start with
        # the point that is closest to origin
        tmp = tmp.reshape(-1,2)
        distance_from_origin = map(lambda pt: pt[0] ** 2 + pt[1] ** 2, tmp)
        val, idx = min((val, idx) for (idx, val) in enumerate(distance_from_origin))
        
        if idx > 0:
            up, down = np.vsplit(tmp, [idx])
            tmp = np.vstack((down, up))
        
        polygons.append(tmp)
    
    return polygons 
Example #18
Source File: find_arrows.py    From PyCV-time with MIT License 4 votes vote down vote up
def imgproc(frame):
    
    # convert color to gray scale and show it
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('gray', gray)
    
    blur = cv2.blur(gray, (5,5))
    edge = cv2.Canny(blur, 10, 100)
    edge = cv2.blur(edge, (2,2))
    cv2.imshow('blured edge', edge)
    
    
    # convert image to black and white and show it
    thresh1, thresh = cv2.threshold(edge, 60, 120, cv2.THRESH_BINARY)
    cv2.imshow('thresh', thresh)
    
    # find contours!
    contours, hry = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    
    # draw all the contours
    cpframe = frame.copy()
    cv2.drawContours(cpframe, contours, -1, (0,255,0), 3)
    cv2.imshow('cpframe', cpframe)
    
    # ================== TODO ===================
    
    # Modify these code to suit your need
    contours = [ctr for ctr in contours if cv2.contourArea(ctr) > 100]
    contours = [cv2.approxPolyDP(ctr, 5, True) for ctr in contours]
    heptagons = [ctr for ctr in contours if len(ctr) == 7]
    arrows = [hepta for hepta in heptagons if isArrow(hepta)]
    #tips = [ tip(a) for a in arrows ]
    
    #contours = [ctr for ctr in contours if cv2.isContourConvex(ctr)]
    
    # ============================================
    
    
    # draw on the frame
    #cv2.drawContours(frame, heptagons, -1, (0,255,0), 3)
    cv2.drawContours(frame, arrows, -1, (255, 0, 0), -1)
    # draw tips
    #for t in tips:
    #    cv2.circle(frame, tuple(t), 5, (0, 0, 255), -1)

    return frame 
Example #19
Source File: squares.py    From PyCV-time with MIT License 4 votes vote down vote up
def find_squares(img):
    img = cv2.GaussianBlur(img, (5, 5), 0)
    squares = []
    for gray in cv2.split(img):
        for thrs in xrange(0, 255, 26):
            if thrs == 0:
                bin = cv2.Canny(gray, 0, 50, apertureSize=5)
                bin = cv2.dilate(bin, None)
            else:
                retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
            bin, contours, hierarchy = cv2.findContours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
            for cnt in contours:
                cnt_len = cv2.arcLength(cnt, True)
                cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)
                if len(cnt) == 4 and cv2.contourArea(cnt) > 1000 and cv2.isContourConvex(cnt):
                    cnt = cnt.reshape(-1, 2)
                    max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
                    if max_cos < 0.1:
                        squares.append(cnt)
    return squares 
Example #20
Source File: signatureExtractor.py    From signature_extractor with MIT License 4 votes vote down vote up
def getPageFromImage(img):
    imgSize = np.shape(img)

    gImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # bImg = cv2.medianBlur(src = gImg, ksize = 11)
    bImg = gImg.copy()

    threshold, _ = cv2.threshold(src = bImg, thresh = 0, maxval = 255, type = cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    cannyImg = cv2.Canny(image = bImg, threshold1 = 0.5 * threshold, threshold2 = threshold)

    _, contours, _ = cv2.findContours(image = cannyImg.copy(), mode = cv2.RETR_TREE, method = cv2.CHAIN_APPROX_SIMPLE)

    # There is no page in the image
    if len(contours) == 0:
        print 'No Page Found'
        return img

    maxRect = Rect(0, 0, 0, 0)
    coordinates = []
    for contour in contours:
        # Detect edges
        # Reference - http://docs.opencv.org/3.1.0/dd/d49/tutorial_py_contour_features.html
        epsilon = cv2.arcLength(contour, True)
        corners = cv2.approxPolyDP(contour, 0.1 * epsilon, True)
        x, y, w, h = cv2.boundingRect(points = contour)
        currentArea = w * h
        # currentArea = cv2.contourArea(contour)

        # check if length of approx is 4
        if len(corners) == 4 and currentArea > maxRect.getArea():
            maxRect.set(x, y, w, h)
            print cv2.isContourConvex(contour)
            # maxRect.setArea(currentArea)

    contoursInPage = 0
    for contour in contours:
        x, y, _, _ = cv2.boundingRect(points = contour)
        if (x > maxRect.x and x < maxRect.x + maxRect.w) and (y > maxRect.y and y < maxRect.y + maxRect.h):
                contoursInPage += 1

    maxContours = 5
    if contoursInPage <= maxContours:
        print 'No Page Found'
        return img

    return img[maxRect.y : maxRect.y + maxRect.h, maxRect.x : maxRect.x + maxRect.w] 
Example #21
Source File: pageExtractor.py    From signature_extractor with MIT License 4 votes vote down vote up
def getPageFromImage(img):
    imgSize = np.shape(img)

    gImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # bImg = cv2.medianBlur(src = gImg, ksize = 11)
    bImg = gImg.copy()

    threshold, _ = cv2.threshold(src = bImg, thresh = 0, maxval = 255, type = cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    cannyImg = cv2.Canny(image = bImg, threshold1 = 0.5 * threshold, threshold2 = threshold)

    _, contours, _ = cv2.findContours(image = cannyImg.copy(), mode = cv2.RETR_TREE, method = cv2.CHAIN_APPROX_SIMPLE)

    maxRect = Rect(0, 0, 0, 0)
    coordinates = []
    bestContour = 0
    index = 0
    for contour in contours:
        epsilon = cv2.arcLength(contour, True)
        corners = cv2.approxPolyDP(contour, 0.1 * epsilon, True)
        x, y, w, h = cv2.boundingRect(points = contour)
        currentArea = w * h

        if len(corners) == 4 and currentArea > maxRect.getArea():
            maxRect.set(x, y, w, h)
            bestContour = index

        index += 1

    contoursInPage = 0
    for contour in contours:
        x, y, _, _ = cv2.boundingRect(points = contour)
        if (x > maxRect.x and x < maxRect.x + maxRect.w) and (y > maxRect.y and y < maxRect.y + maxRect.h):
                contoursInPage += 1

    maxContours = 5
    if contoursInPage <= maxContours:
        print 'No Page Found'

    print bestContour
    print len(contours)
    print cv2.isContourConvex(contours[bestContour])
    cv2.drawContours(img, contours, bestContour, (0, 0, 255))

    cv2.imshow('Page', img)
    cv2.waitKey(0) 
Example #22
Source File: detect.py    From python-ar-markers with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def detect_markers(img):
    width, height, _ = img.shape
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    edges = cv2.Canny(gray, 10, 100)
    contours, hierarchy = cv2.findContours(edges.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[-2:]

    # We only keep the long enough contours
    min_contour_length = min(width, height) / 50
    contours = [contour for contour in contours if len(contour) > min_contour_length]
    warped_size = 49
    canonical_marker_coords = array(((0, 0),
                                     (warped_size - 1, 0),
                                     (warped_size - 1, warped_size - 1),
                                     (0, warped_size - 1)),
                                    dtype='float32')

    markers_list = []
    for contour in contours:
        approx_curve = cv2.approxPolyDP(contour, len(contour) * 0.01, True)
        if not (len(approx_curve) == 4 and cv2.isContourConvex(approx_curve)):
            continue

        sorted_curve = array(cv2.convexHull(approx_curve, clockwise=False),
                             dtype='float32')
        persp_transf = cv2.getPerspectiveTransform(sorted_curve, canonical_marker_coords)
        warped_img = cv2.warpPerspective(img, persp_transf, (warped_size, warped_size))
        warped_gray = cv2.cvtColor(warped_img, cv2.COLOR_BGR2GRAY)

        _, warped_bin = cv2.threshold(warped_gray, 127, 255, cv2.THRESH_BINARY)
        marker = warped_bin.reshape(
            [MARKER_SIZE, warped_size / MARKER_SIZE, MARKER_SIZE, warped_size / MARKER_SIZE]
        )
        marker = marker.mean(axis=3).mean(axis=1)
        marker[marker < 127] = 0
        marker[marker >= 127] = 1

        try:
            marker = validate_and_turn(marker)
            hamming_code = extract_hamming_code(marker)
            marker_id = int(decode(hamming_code), 2)
            markers_list.append(HammingMarker(id=marker_id, contours=approx_curve))
        except ValueError:
            continue
    return markers_list