示例#1
0
def getContours(img):
    contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_NONE)
    x, y, w, h = 0, 0, 0, 0
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if (area > 500):
            #cv2.drawContours(imgResult, cnt, -1, (255,0,0), 3)
            peri = cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
            x, y, w, h = cv2.boundingRect(approx)
    return (x + w) // 2, y
示例#2
0
def getContours(img):
    contours, hierarchy = cv.findContours(img, cv.RETR_EXTERNAL,
                                          cv.CHAIN_APPROX_NONE)
    print('hierarchy : ', hierarchy)
    for cnt in contours:
        x, y, w, h = cv.boundingRect(cnt)
        print(x, y, w, h)
        epsilon = 0.02 * cv.arcLength(cnt, True)
        approx = cv.approxPolyDP(cnt, epsilon, True)
        print(len(approx))
        cv.drawContours(img_color_approx, [approx], 0, (0, 255, 255), 2)
        cv.imshow("result approx", img_color_approx)
示例#3
0
def getContours(_img):
    rects = []
    contours, hierarchy = cv2.findContours(_img, cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_NONE)
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area > 500:
            cnt_length = cv2.arcLength(cnt, True)
            cnt_vertexes_approx = cv2.approxPolyDP(cnt, 0.02 * cnt_length,
                                                   True)
            rects.append(cv2.boundingRect(cnt_vertexes_approx))
    return rects
def getContours(img):
    contours, hierarchy = cv2.findContours(
        img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE
    )  #RETR_EXTERNAL retrieve extreame outer contours/corners. CHAIN_APPROX_NONE means return ALL the contours that has been found. Don't return the compress one
    for cnt in contours:
        area = cv2.contourArea(cnt)
        # print(area)

        #giving minimum threshold for the area so that it doesn't detect the noise
        if area > 500:  #if area is greater than 500 px:
            cv2.drawContours(
                imgContour, cnt, -1, (255, 0, 0), 3
            )  #it will draw the contours each time. Putting contour index -1 to draw all the contours, then we are making it blue, defining thickness as 3

            #calculating the curve length, it will help us to get the approximate the corner of the shape
            peri = cv2.arcLength(cnt, True)  #true means shapes are closed
            # print(peri)

            #approximate how many corner points we have
            approx = cv2.approxPolyDP(
                cnt, 0.02 * peri, True
            )  #epsilon = 0.02*peri. You can tune this value as you want

            # print(len(approx))  #anything above 4 is circle

            #getting object corners
            objCor = len(approx)

            #gives x,y and widht and height of the objects
            x, y, w, h = cv2.boundingRect(approx)

            #categorizing whether circle, rectangular or square
            if objCor == 3:  #triangle
                objectType = "Tri"
            elif objCor == 4:
                aspRatio = w / float(h)
                if aspRatio > 0.95 and aspRatio < 1.05:
                    objectType = 'Square'
                else:
                    objectType = 'Rantangle'
            elif objCor > 4:
                objectType = 'Circles'
            else:
                objectType = "None"

            #adding ractangle around the shapes
            cv2.rectangle(imgContour, (x, y), (x + w, y + h), (0, 255, 0), 2)

            cv2.putText(
                imgContour, objectType, (x + (w // 2) - 10, y + (h // 2) - 10),
                cv2.FONT_HERSHEY_COMPLEX, 0.7, (0, 0, 0), 2
            )  #x+(w//2)....calculates the center of the shape and put the text on it
示例#5
0
def smooth_contours_on_mask(mask):
    height = mask.shape[0]
    width = mask.shape[1]
    contours, _hierarchy = cv2.findContours(mask[:, :, 0].astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_TC89_L1)
    smoothened = []

    for cnt in contours:
        epsilon = 0.003*cv2.arcLength(cnt,True)
        smoothened.append(cv2.approxPolyDP(cnt, epsilon, True))
    final_mask = np.zeros((height, width, 3))
    cv2.drawContours(final_mask, smoothened, -1, (1, 1, 1), -1)
    
    return final_mask
示例#6
0
def checkIfRectangle(image, singleContour):
    #dependent on the global 'image' variable
    M = cv2.moments(singleContour)
    contourPerimeter = cv2.arcLength(singleContour, True)
    approximation = cv2.approxPolyDP(singleContour, 0.09 * contourPerimeter,
                                     True)

    if len(approximation) == 4:
        if M['m00'] > 100:
            groupX = np.sort([x[0][0] for x in approximation])
            groupY = np.sort([x[0][1] for x in approximation])

            if image[groupY[0] + 3][groupX[3] -
                                    3][0] == 112 or image[groupY[0] +
                                                          3][groupX[3] -
                                                             3][1] == 112:

                #########getting what we want
                xPosMouse = int(np.mean(groupX))
                yPosMouse = int(groupY[0] + yPosArrange *
                                (groupY[3] - groupY[0]))

                mouse.click(button='right', coords=(xPosMouse, yPosMouse))
                keyboard.send_keys('o')
                sleep(.3)

                with mss.mss() as sct:
                    img = sct.grab({
                        'top': 144,
                        'left': 14,
                        'height': 1,
                        'width': 1
                    })

                    if img.pixel(0, 0) != (236, 233, 216):
                        return False,

                    else:
                        keyboard.send_keys('{ESC}')
                        return True, (groupX[3], groupY[3]), (xPosMouse,
                                                              yPosMouse)
                        # first for checking whether it is a rectangle
                        # second for writing tag number on the taglistpicture.png
                        # third for moving mouse pointer to do the capture

            else:
                return False,
        else:
            return False,
    else:
        return False,
示例#7
0
def getContours(img):
    biggest = np.array([])
    maxArea = 0
    imgCanny = cv2.Canny(img, 200, 200)
    contours, hierarchy = cv2.findContours(imgCanny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area > 5000:
            peri = cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, 0.02*peri, True)
            if area > maxArea and len(approx) == 4:
                biggest = approx
                maxArea = area
    return biggest
示例#8
0
def getContour(img, imgContour):
    contour, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL,
                                          cv2.CHAIN_APPROX_NONE)
    global h
    for cnt in contour:
        area = cv2.contourArea(cnt)
        peri = cv2.arcLength(cnt, True)  # True shows that the shape is closed
        approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
        area = cv2.contourArea(cnt)
        if 4 <= len(approx) <= 7 and area > area_min:
            cv2.drawContours(imgContour, cnt, -1, (255, 0, 255), 3)
            x, y, w, h = cv2.boundingRect(approx)
            cv2.rectangle(
                imgContour, (x, y), (x + w, y + h), (0, 255, 0), 3
            )  # rectangle must match with the contour for knowing the standard in parallel
示例#9
0
def searchRect(img, contours, e=0.02):
    max_area = 0
    max_approx = 0

    for cnt in contours:
        epsilon = e * cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, epsilon, True)

        if len(approx) == 4:
            print(f'{cv2.contourArea(cnt)}')
            if max_area < cv2.contourArea(cnt):
                max_approx = approx
                max_area = cv2.contourArea(cnt)

    return max_approx
def getContour(img, imgContour):
    contour, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL,
                                          cv2.CHAIN_APPROX_NONE)
    found = False
    for cnt in contour:
        area = cv2.contourArea(cnt)
        peri = cv2.arcLength(cnt, True)  # True shows that the shape is closed
        approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
        area = cv2.contourArea(cnt)
        if 4 <= len(approx) <= 7 and area > area_min:
            found = True
            cv2.drawContours(imgContour, cnt, -1, (255, 0, 255), 7)
            x, y, w, h = cv2.boundingRect(approx)
            cv2.rectangle(imgContour, (x, y), (x + w, y + h), (0, 255, 0), 5)
    return found
def getContours(img):
    biggest = np.array([])
    maxArea = 0
    contours,hierarchy = cv.findContours(img,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_NONE)
    for cnt in contours:
        area = cv.contourArea(cnt)
        if area>5000:
            #cv.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
            peri = cv.arcLength(cnt,True)
            approx = cv.approxPolyDP(cnt,0.02*peri,True)
            if area >maxArea and len(approx) == 4:
                biggest = approx
                maxArea = area
    cv.drawContours(imgContour, biggest, -1, (255, 0, 0), 20)
    return biggest
示例#12
0
def getContours(img):
    """
    get the bound box and return it's top middle point.
    """
    contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_NONE)
    x, y, w, h = 0, 0, 0, 0
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area > 500:
            #cv2.drawContours(imgResult, cnt, -1, (255, 0, 0), 3)
            peri = cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
            x, y, w, h = cv2.boundingRect(approx)
    return x + w // 2, y
示例#13
0
def contour1():
    ret, thr = cv2.threshold(imgray, 127, 255, 0)
    contours, _ = cv2.findContours(thr, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cv2.imshow('threshold', thr)

    cnt = contours[0]
    cv2.drawContours(img, [cnt], 0, (0, 0, 0), 1)

    epsilon1 = 0.01 * cv2.arcLength(cnt, True)
    epsilon2 = 0.1 * cv2.arcLength(cnt, True)

    approx1 = cv2.approxPolyDP(cnt, epsilon1, True)
    approx2 = cv2.approxPolyDP(cnt, epsilon2, True)
    """
        cv2.approxPolyDP() 함수는 인자로 주어진 곡선 또는 다각형을 epsilon 값에 따라 
        꼭지점수를 줄여 새로운 곡선이나 다각형을 생성하여 리턴합니다.
        
        cv2.approxPolyDP() 함수는 세 개의 인자를 가집니다.
            cnt: Numpy Array 형식의 곡선 또는 다각형. 우리의 예에서는 Contour를 입력함
            epsilon: 근사 정확도를 위한 값. 이 값은 오리지널 커브와 근사 커브간 거리의 최대값으로 사용
            True: 세 번째 인자가 True이면 폐곡선, False이면 양끝이 열려있는 곡선임을 의미

            여기서 중요한 값이 epsilon 입니다. epsilon의 크기에 따라 근사되는 결과가 다르게 나옵니다.
            우리의 예제에서는 근사값으로 epsilon1, epsilon2를 사용했는데, 
            코드를 보시면 cv2.arcLength() 함수의 리턴값에 일정한 숫자를 곱한 값을 이용했습니다.
            즉, 오리지널 Contour의 둘레 길이의 1%를 epsilon1, 둘레 길이의 10%를 epsilon2 값으로 할당헀죠~
        """

    cv2.drawContours(img1, [approx1], 0, (0, 255, 0), 3)
    cv2.drawContours(img2, [approx2], 0, (0, 255, 0), 3)

    cv2.imshow('contour', img)
    cv2.imshow('Approx1', img1)
    cv2.imshow('Approx2', img2)

    impDef.close_window()
示例#14
0
def biggestContour(contours):
    biggest = np.array([])  # empty array to store the corner_points
    max_area = 0
    for i in contours:
        area = cv2.contourArea(i)
        if area > 50:
            peri = cv2.arcLength(
                i, True)  # Arclrngth/Perimeter(if closed) of the curve
            corner_points = cv2.approxPolyDP(
                i, 0.02 * peri, True
            )  # Gives a approx curve with fewer points to get corner points of that object
            if area > max_area and len(corner_points) == 4:
                biggest = corner_points
                max_area = area
    return biggest, max_area
def fix_perspective(img, save=True, out_name='./output/fixed'):
    """ 对图像进行自动透视修正 """
    contours = contour_demo(img)
    # 轮廓唯一,以后可以扩展
    # print(contours)
    contour = contours[0]
    # 求周长,可在后面的转换中使用周长和比例
    # print('周长:', cv.arcLength(contour, True))
    img_copy = img.copy()
    # 使用approxPolyDP,将轮廓转换为直线,22为精度(越高越低),TRUE为闭合
    approx = cv.approxPolyDP(contour, 22, True)
    n = []
    # 生产四个角的坐标点
    for x, y in zip(approx[:, 0, 0], approx[:, 0, 1]):
        n.append((x, y))
    # 左上,左下,右下,右上
    # p1: [[ 370.  356.], [ 402. 2981.], [2360. 2775.], [2151.  466.]]
    # <class 'numpy.ndarray'>
    # 原始四点坐标
    p1 = np.array(n, dtype=np.float32)
    # 对应四点坐标,左上,左下,右下,右上
    # p2 = np.array([(0, 0), (0, 1500), (1000, 1500), (1000, 0)],
    #               dtype=np.float32)
    # 自动计算 p2:
    LT = p1[0]
    LB = p1[1]
    RB = p1[2]
    # 高度 = 开方((左上纵坐标-左下纵坐标)^2 + (左上横坐标-左下横坐标))
    height = np.sqrt((LB[1] - LT[1])**2 + (LB[0] - LT[0])**2)
    # 左下和右下点的距离
    width = np.sqrt((LB[1] - RB[1])**2 + (LB[0] - RB[0])**2)
    # 对应四点坐标,左上,左下,右下,右上
    p2 = np.array([(0, 0), (0, height), (width, height), (width, 0)],
                  dtype=np.float32)
    # print('目标点:', p2)
    try:
        M = cv.getPerspectiveTransform(p1, p2)  # 变换矩阵
    except cv.error:
        print('无法矫正透视')
        return
    # 使用透视变换
    result = cv.warpPerspective(img_copy, M, (0, 0))
    # 重新截取
    result = result[:int(p2[1][1] + 1), :int(p2[2][0] + 1)]
    if save:
        cv.imwrite(f'{out_name}.png', result)
        print(f'{out_name}.png saved')
    return result
def draw_contours(img):
    # TODO: Maybe use average or std dev of areas to filter the contours

    output = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
    contours, _ = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    filtered_cnt = []
    for cnt in contours:
        perimeter = cv2.arcLength(cnt, True)
        perimeter_points = cv2.approxPolyDP(cnt, 0.01 * perimeter, True)
        area = cv2.contourArea(cnt)
        if (10 < len(perimeter_points) < 20) and (1000 < area < 90000):
            filtered_cnt.append(cnt)
            cv2.drawContours(output, perimeter_points, -1, RGB_BLUE, 10)

    cv2.drawContours(output, filtered_cnt, -1, RGB_RED, 2)
    return output
示例#17
0
文件: contour.py 项目: kayfour/IPCV
def rectwithname(img, contours, e=0.02):
    result = img.copy()
    for cnt in contours:
        x, y, w, h = cv.boundingRect(cnt)
        epsilon = e*cv.arcLength(cnt, True)
        approx = cv.approxPolyDP(cnt, epsilon, True)

        if len(approx)==3:
            text = "triangle"
        elif len(approx)==4:
            text = "square" if w == h else 'rectangle'
        else:
            text = "circle"
        cv.rectangle(result,(x,y),(x+w,y+h),(255,0,255),2)
        cv.putText(result, text, (x, y-5), cv.FONT_HERSHEY_COMPLEX, 0.5,(0, 0, 0), 1)
    return result
    def detail(self):
        details = {
            "Vertices" : 0,
            "Perimeter" : 0,
            "SumOfAngles" : 0,
            "DistFromCentre" : 0
            }
        
        #Prints the results to screen
        #print("Number Of Objects Detected: "+str(len(self.contours)))
        for cnt in self.contours:
            #Approx is the amount of edges in the shape (circles just have a lot of faces))
            approx = cv2.approxPolyDP(cnt,0.015*cv2.arcLength(cnt,True),True)
            #approx is used for specific functions, cnt is used for the drawing.

            #print(len(approx))
            centre = self.getCentre(cnt)
            #print("Corners: "+str(self.getCorners(approx)))
            details["Vertices"] = (self.getCorners(approx))
            #print("Angle Of Shape: "+str(self.getOrientation(cnt, self.img)))
            
            if len(self.getEdgeLengths(approx)) < 9:
                #print("Lengths Of Edges: "+str(self.getEdgeLengths(approx)))
                details["Perimeter"] = (self.getEdgeLengths(approx))
            else:
                Perimeter = 0
                for i in self.getEdgeLengths(approx):
                    Perimeter += i
                #print("Lengths Of Edges: " + str(Perimeter))
                details["Perimeter"] = (Perimeter)
            if len(self.getEdgeLengths(approx)) < 42:
                #print("Sum of Angles: "+str(self.sumOfAngles(approx)))
                details["SumOfAngles"] = (self.sumOfAngles(approx))
            if len(self.DistanceFromCentre(approx)) < 42:
                details["DistFromCentre"] = (self.DistanceFromCentre(approx))
                #print("Distance From Center Of Object: "+str(self.DistanceFromCentre(approx)))
            else:
                #print("Distance From Center Of Object: "+str(self.DistanceFromCentre(approx)[0]))
                details["DistFromCentre"] = (self.DistanceFromCentre(approx))
            

            #Draw the object on the image. show() should be called after detail()
            cv2.drawContours(self.img,[cnt],0,-1)
            #cv2.circle(self.img, (centre[0], centre[1]), 3, (255, 0, 0), -1)
        
            return details
def get_contours(origin, img):
    # window_title = "im"

    # 获取轮廓
    # img = cv2.imread(image_path)

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    blur = cv2.GaussianBlur(gray, (3, 3), 0)

    edges = cv2.Canny(blur, 10, 200)  # Edge detection
    edges = cv2.dilate(edges, None)  # 默认(3x3)
    edges = cv2.erode(edges, None)

    # Find contours in edges(binary image)
    contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    contours = sorted(contours, key=cv2.contourArea, reverse=True)
    max_contour = contours[0]

    epsilon = 0.001 * cv2.arcLength(max_contour, True)
    approx = cv2.approxPolyDP(max_contour, epsilon, True)
    # print(approx)
    box = cv2.minAreaRect(approx)
    center, wh, angle = box
    angle = int(abs(angle))
    wh = (int(wh[0]), int(wh[1]))

    center = (int(center[0]), int(center[1]))
    # print(center, wh, angle)
    # cv2.putText(
    #     img, "{}".format(angle), center, cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2,
    # )

    box = cv2.boxPoints(box)
    # 坐标转换成大图坐标系
    center = np.array(center) + np.array(origin)
    box = np.array(box) + np.array(origin)
    box = np.int0(box)

    # cv2.drawContours(img, [box], -1, 255, 2)

    # cv2.imshow(window_title, img)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    # return 中心点、角度、最大轮廓、宽高
    return center, angle, box, wh
示例#20
0
def find_big_square(dilatation):
    contours, _ = cv2.findContours(dilatation.copy(), cv2.RETR_EXTERNAL,
                                   cv2.CHAIN_APPROX_SIMPLE)[-2:]
    print(f"num contours: {len(contours)}")
    contours = sorted(contours, key=cv2.contourArea,
                      reverse=True)[:10]  # areas mas grandes primero
    big_square = None
    maxPerimeter = 0

    for contour in contours:
        perimeter = cv2.arcLength(contour, True)  # largo del contour
        approx = cv2.approxPolyDP(
            contour, 0.02 * perimeter,
            True)  #constante 0.02 # aproxima a lineas rectas
        if len(approx) == 4:
            if perimeter > maxPerimeter:  # para conseguir el contorno mas grande
                maxPerimeter = perimeter
                big_square = approx
    return big_square
示例#21
0
def Contours(threshold, ratio, orig): # Funkcija za pronalazak kontura papira

	cnts = cv2.findContours(threshold.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) #
	cnts = imutils.grab_contours(cnts)												  # Manipuliranje slike kako bismo izvukli njezine kotnure
	cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]					  #

	for c in cnts: # prolazimo kroz sve pronađene konture na slici
		peri = cv2.arcLength(c, True)  					#
		approx = cv2.approxPolyDP(c, 0.02 * peri, True) # Aproksimacija kontura

		# ako naša aproksimirana kotura ima 4 točke
		# možemo pretpostaviti da smo našli naš papir
		if len(approx) == 4:
			screenCnt = approx
			break
	
	
	cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2) # crtamo obrub papira
	Perspective_transform(orig, screenCnt, ratio) # Pozivamo funkciju za 2D transoformaciju pronađenog papira
示例#22
0
def abstructCard(img):
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    print(gray)
    gray_mean = np.mean(gray)
    _, thresh = cv.threshold(gray, gray_mean - 10, 255, cv.THRESH_BINARY_INV)
    img1 = img.copy()
    #cv.imshow('gray',gray)
    #cv.imshow('thresh', thresh)
    cv.imshow('th3', thresh)
    canny = cv.Canny(thresh, 100, 150)
    #cv.imshow('canny',canny)
    image, coutous, hierarchy = cv.findContours(thresh, cv.RETR_TREE,
                                                cv.CHAIN_APPROX_SIMPLE)
    cv.drawContours(img, coutous, -1, (0, 0, 255), 5)
    coutous_Area = []
    for item in coutous:
        #print('item shaoe = ',item.shape)
        coutous_Area.append(cv.contourArea(item))
    index = coutous_Area.index(max(coutous_Area))
    rec_area = 0
    x1 = 0
    y1 = 0
    w1 = 0
    h1 = 0
    for i, item in enumerate(coutous_Area):
        if (item > 200):
            epsilon = 0.1 * cv.arcLength(coutous[i], True)
            approx = cv.approxPolyDP(coutous[i], epsilon, True)
            cv.drawContours(img, coutous, i, (0, 255, 0), 3)
            x, y, w, h = cv.boundingRect(coutous[i])
            area = w * h
            if (rec_area < area):
                rec_area = area
                x1 = x
                y1 = y
                w1 = w
                h1 = h
    rec = cv.rectangle(img, (x1, y1), (x1 + w1, y1 + h1), (0, 255, 0), 2)
    #cv.imshow('rectangle',rec)
    result = img1[y1:y1 + h1, x1:x1 + w1, :]

    cv.imshow("card", result)
    cv.imshow('img', img)
示例#23
0
def getContour(img,
               kernel=(5, 5),
               threshold=[100, 100],
               iters=3,
               area_min=50000,
               fillter=4,
               draw=False,
               show=False):
    imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    imgblur = cv2.medianBlur(imgray, 3)
    # imgblur = cv2.adaptiveThreshold(imgblur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, \
    # cv2.THRESH_BINARY, 11, 2)
    imgCanny = cv2.Canny(imgblur, threshold[0], threshold[1], 3, 3, True)
    # imgdialte = cv2.dilate(imgCanny,(5,5),iterations= 3)
    # imgdialte = cv2.morphologyEx(imgCanny, cv2.MORPH_OPEN, kernel)
    # imgThre = cv2.erode(imgdialte,(3,3),iterations = 1)

    if show:
        # cv2.imshow("blur", imgblur)
        # cv2.imshow("dialte",imgdialte)
        # cv2.imshow("imgThre",imgThre)
        cv2.imshow('Canny', imgCanny)
        cv2.imshow('ori', img)
    Contour, hiecherary = cv2.findContours(imgCanny, cv2.RETR_TREE,
                                           cv2.CHAIN_APPROX_SIMPLE)
    Final_Contour = []
    for i in Contour:
        area = cv2.contourArea(i)
        if area > area_min:
            peri = cv2.arcLength(i, True)
            approx = cv2.approxPolyDP(i, 0.02 * peri, True)
            bbox = cv2.boundingRect(approx)
            if fillter > 0:
                if len(approx) == fillter:
                    Final_Contour.append([len(approx), area, approx, bbox, i])
            else:
                Final_Contour.append([len(approx), area, approx, bbox, i])
    Final_Contour = sorted(Final_Contour, key=lambda x: x[1], reverse=True)
    if draw:
        for con in Final_Contour:
            cv2.drawContours(img, con[4], -1, (0, 255, 255), 3)
    return img, Final_Contour
def alineamiento(imagen, ancho, alto):
    imagen_alineada = None
    grises = cv2.cvtColor(imagen, cv2.COLOR_BGR2GRAY)
    tipoUmbral, umbral = cv2.threshold(grises, 150, 255, cv2.THRESH_BINARY)
    cv2.imshow("Umbral", umbral)
    contorno = cv2.findContours(umbral, cv2.RETR_EXTERNAL,
                                cv2.CHAIN_APPROX_SIMPLE)[0]
    contorno = sorted(contorno, key=cv2.contourArea, reverse=True)[:1]

    for c in contorno:
        epsilon = 0.01 * cv2.arcLength(c, True)
        aproximacion = cv2.approxPolyDP(c, epsilon, True)
        if len(aproximacion) == 4:
            puntos = ordenarPuntos(aproximacion)
            puntos1 = np.float32(puntos)
            puntos2 = np.float32([[0, 0], [ancho, 0], [0, alto], [ancho,
                                                                  alto]])
            M = cv2.getPerspectiveTransform(puntos1, puntos2)
            imagen_alineada = cv2.warpPerspective(imagen, M, (ancho, alto))
    return imagen_alineada
示例#25
0
def get_contour_corners(contours, corner_amt=4, max_iter=200):
    coeff = 1
    while max_iter > 0 and coeff >= 0:
        max_iter = max_iter - 1
        # Maximum distance from contour to approximated contour
        epsilon = coeff * cv2.arcLength(contours, True)

        # Approximation of a contour shape, True means curve is closed
        approx = cv2.approxPolyDP(contours, epsilon, True)

        # Checks curves for convexity defects
        hull = cv2.convexHull(approx)
        if len(hull) == corner_amt:
            return hull
        else:
            if len(hull) > corner_amt:
                coeff += .01
            else:
                coeff -= .01
    return None
def smooth_contours_on_mask(mask):
    """Smoothing sharp contours on the given mask.
    mask: [height, width] of type float. Full image-size binary mask.

    Returns a final mask of size [height, width, depth] with smoothened contours.
    """
    height = mask.shape[0]
    width = mask.shape[1]
    contours, _hierarchy = cv2.findContours(mask[:, :, 0].astype(np.uint8),
                                            cv2.RETR_TREE,
                                            cv2.CHAIN_APPROX_TC89_L1)
    smoothened = []

    for cnt in contours:
        epsilon = 0.003 * cv2.arcLength(cnt, True)
        smoothened.append(cv2.approxPolyDP(cnt, epsilon, True))
    final_mask = np.zeros((height, width, 3))
    cv2.drawContours(final_mask, smoothened, -1, (1, 1, 1), -1)

    return final_mask
示例#27
0
  def get_paper_contour(self, orig):
    # resize the image for faster computation.
    image = orig.copy()
    ratio = image.shape[0] / 500.0
    image = imutils.resize(image, height = 500)

    # Process the image to find edges
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.bilateralFilter(gray, 11, 17, 17)
    edges = cv2.Canny(gray, 50, 150)

    if self.PRINT_PROCESS:
      self.showarr(gray)
      self.showarr(edges)

    # Get the ballotContour from the edges -- the largest connected rectangle.
    _, contours, _ = cv2.findContours(edges.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    contours = sorted(contours, key = cv2.contourArea, reverse=True)[:5]
    ballotContour = None
    for c in contours:
      # approximate the contour
      perimeter = cv2.arcLength(c, True)
      approx = cv2.approxPolyDP(c, 0.02 * perimeter, True)
    
      # if our approximated contour has four points, then
      # we can assume that we have found our screen
      if len(approx) == 4:
        ballotContour = approx
        break

    if ballotContour is None:
      raise ValueError('Could not determine ballot border. Make sure the ballot is on a solid dark background, fully in the image.')

    # Draw the contour
    if self.PRINT_PROCESS:
      cv2.drawContours(image, [ballotContour], -1, (0, 255, 0), 1)
      self.showarr(image)

    # Reshape, scale, and return
    ballotContour = ballotContour.reshape(4,2) * ratio
    return ballotContour
def edgeFinding(image):
    """[The inputted image goes through multiple tranforms to find the contours and edge points of every hazard sign in the 
        image, these edge points are stored in a list and returned to the calling function for further maipulation. This function
        does not change the actual image in anyway]
    
    Arguments:
        image -- [the image containing the hazard labels]
    
    Returns:
        [array] -- [the set of points that correlate to the corners of each hazard label in the input image.]
    """
    print(image.shape)
    finalPoints = []
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    thresh = adaptiveThreshold(gray)

    gaus = cv2.GaussianBlur(thresh, (5, 5), 0)

    bilat = bilatFilter(gaus)

    cannied = canny(bilat)

    _, contours, heir = cv2.findContours(cannied, cv2.RETR_EXTERNAL,
                                         cv2.CHAIN_APPROX_SIMPLE)

    holder = []
    for contour in contours:
        epsilon = 0.1 * cv2.arcLength(contour, True)
        poly = cv2.approxPolyDP(contour, epsilon, True)
        area = cv2.contourArea(poly)
        if len(poly) == 4 and area > 50000:
            holder.append(poly)
    for contour in holder:
        for point in contour:
            cv2.circle(cannied, (point[0][0], point[0][1]), 3, [255, 0, 0], 20)
        points = np.float32([[contour[0][0][0], contour[0][0][1]],
                             [contour[1][0][0], contour[1][0][1]],
                             [contour[2][0][0], contour[2][0][1]],
                             [contour[3][0][0], contour[3][0][1]]])
        finalPoints.append(points)
    return finalPoints
示例#29
0
def get_dipstick_contour(contours):
    """ Searches contours for contour with four vertex points, rectangle/square shape.
    When a rectangle/square is detected compute the bounding box and aspect ratio to
    confirm its the rectangle dipstick.
    """
    dipstick_contour = None
    for contour in contours:
        perimeter = cv.arcLength(contour, True)
        approx = cv.approxPolyDP(contour, 0.015 * perimeter, True)

        if len(approx) == 4:
            (x, y, width, height) = cv.boundingRect(approx)
            aspect_ratio = float(width) / height

            if aspect_ratio > 1.05:
                dipstick_contour = contour
                break
            elif aspect_ratio < 0.95:
                return None, 'vertical'

    return dipstick_contour, 'complete'
示例#30
0
def apply_find_contours(image, n_points, min_area, n_candidates):
    """find the contours in the image.

    finds the contours in the image that are approximated by an n_points
    polygon, and are greater than min_area. it will sort the contours based on
    initial area but only approximate polygons for the larget n_candidates.

    :param image: input image
    :type image: cv2 image
    :param n_points: number of points the approximated polygon should have
    :type n_points: integer
    :param min_area: minimum area the polygon should have
    :type min_area: integer
    :param n_candidates: number of contours to check
    :type n_candidates: integer
    :return: contours that meet the point and area requirements
    :rtype: list[points]
    """
    # RETR_EXTERNAL returns the contours from the top level heirarchy
    _, cnts, _ = cv2.findContours(image.copy(), cv2.RETR_EXTERNAL,
                                  cv2.CHAIN_APPROX_SIMPLE)

    # sort based on the contour area
    cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:n_candidates + 1]

    # list to store the four pointed contours
    n_point_conts = []

    # process each contour
    for c in cnts:
        # approximate the contour
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.017 * peri, True)
        area = cv2.contourArea(approx)

        # check the number of points and the area
        if len(approx) == n_points and area > min_area:
            n_point_conts.append(approx)

    return n_point_conts