Ejemplo n.º 1
0
def get_candidate_contours(img, img_contour, area_min):
    area = 0
    # crop_xywh = None

    contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_NONE)

    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area > area_min:
            print(area, area_min)
            cv2.drawContours(img_contour, cnt, -1, (255, 0, 255), 7)
            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

            cv2.rectangle(img_contour, (x, y), (x + w, y + h), (0, 255, 0), 5)
        else:
            area = 0

    print(area)
    if area is not 0:
        return 1
    else:
        return 0
Ejemplo n.º 2
0
def approximationContour(img, contours, e=0.02):
    for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)
        epsilon = e*cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, epsilon, True)
        cv2.drawContours(img, [approx], 0, (0,255,255), 2)
    return img
Ejemplo n.º 3
0
def identify_countors(image):
    stations = []
    image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image_invert = cv2.bitwise_not(image_gray)
    contours, _ = cv2.findContours(image_invert, cv2.RETR_EXTERNAL,
                                   cv2.CHAIN_APPROX_NONE)

    for cnt in contours:
        approx = cv2.approxPolyDP(cnt, 0.02 * cv2.arcLength(cnt, True), True)
        M = cv2.moments(cnt)
        cx = int(M["m10"] / M["m00"])
        cy = int(M["m01"] / M["m00"])
        x, y, w, h = cv2.boundingRect(cnt)

        # detect if the square is rotationed
        # TODO: detect in some other way
        tilted = cnt.ravel()[0] == cx

        station = {
            "type": get_type_by_edges(len(approx), tilted),
            "pos": (x, y),
            "centroid": (cx, cy),
            "size": (w, h),
            "contour": cnt
        }
        stations.append(station)

    return stations
Ejemplo n.º 4
0
def getContours(img, img_rgb):
    contours, hierarchy = cv.findContours(img, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
    
    for cnt in contours:
        area = cv.contourArea(cnt)
        
        if area > 500:
            cv.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
            peri = cv.arcLength(cnt, True)
            approx = cv.approxPolyDP(cnt, 0.02*peri, True)
            
            cv.drawContours(img_rgb, [approx], 0, (255,0,0),5)
            cv.imshow('tmp', img_rgb)
            # cv.waitKey()

            objCor = len(approx)
            x, y, w, h = cv.boundingRect(approx)

            objectType = None
            if objCor == 4:
                objectType = "Rectangle"
            elif w == h:
                objectType = "Square"

            if objCor == 8:
                objectType = "Circle"
            
            if objectType:
                cv.rectangle(imgContour, (x, y), (x+w, y+h), (0, 255, 0), 2)
                cv.putText(imgContour, objectType,
                        (x+(w//2)-10, y+(h//2)-10), cv.FONT_HERSHEY_COMPLEX, 0.7,
                        (0, 0, 0), 2)
Ejemplo n.º 5
0
def getContours(img,
                cThr=[100, 100],
                showCannny=False,
                minArea=1000,
                filter=0,
                draw=False):
    imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    imgBlur = cv2.GaussianBlur(imgGray, (5, 5), 1)
    imgCanny = cv2.Canny(imgBlur, cThr[0], cThr[1])
    kernel = np.ones((5, 5))
    imgDial = cv2.dilate(imgCanny, kernel, iterations=3)
    imgThre = cv2.erode(imgDial, kernel, iterations=2)
    if showCannny: cv2.imshow('Canny', imgThre)
    contours, hiearchy = cv2.findContours(imgThre, cv2.RETR_EXTERNAL,
                                          cv2.CHAIN_APPROX_SIMPLE)
    finalContours = []
    for i in contours:
        area = cv2.contourArea(i)
        if area > minArea:
            peri = cv2.arcLength(i, True)
            approx = cv2.approxPolyDP(i, 0.02 * peri, True)
            bbox = cv2.boundingRect(approx)
            if filter > 0:
                if len(approx) == filter:
                    finalContours.append([len(approx), area, approx, bbox, i])
            else:
                finalContours.append([len(approx), area, approx, bbox, i])
    finalContours = sorted(finalContours, key=lambda x: x[1], reverse=True)
    if draw:
        for con in finalContours:
            cv2.drawContours(img, con[4], -1, (0, 0, 255), 3)
    return img, finalContours
Ejemplo n.º 6
0
def find_sudoku(image):
    # preprocessing
    gray_sudoku = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurred_sudoku = cv2.GaussianBlur(gray_sudoku, (7, 7), 0)
    thresh = cv2.adaptiveThreshold(blurred_sudoku, 255,
                                   cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                   cv2.THRESH_BINARY_INV, 11, 2)

    # find contours
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL,
                                   cv2.CHAIN_APPROX_SIMPLE)

    # get the sudoku contour
    sudoku_area = 0
    sudoku_contour = contours[0]
    for cnt in contours:
        area = cv2.contourArea(cnt)
        x, y, w, h = cv2.boundingRect(cnt)
        if (0.7 < float(w) / h < 1.3  # aspect ratio
                and area > 150 * 150  # minimal area
                and area > sudoku_area  # biggest area on screen
                and area > .5 * w * h):  # fills bounding rect
            sudoku_area = area
            sudoku_contour = cnt

    perimeter = cv2.arcLength(sudoku_contour, True)
    # define the accuracy here
    epsilon = 0.05 * perimeter
    approx = cv2.approxPolyDP(sudoku_contour, epsilon, True)

    # if it is not a sudoku board, just return the frame without doing anything
    if len(approx) != 4:
        return None

    return sudoku_contour
Ejemplo n.º 7
0
def getBoxPoint(contour):
    """ 多边形拟合凸包 """
    hull = cv2.convexHull(contour)
    epsilon = 0.02 * cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(hull, epsilon, True)
    approx = approx.reshape((len(approx), 2))
    return approx
Ejemplo n.º 8
0
def detectshape(c):
# initialize the shape name and approximate the contour
        shape = "unidentified"
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.04 * peri, True)

	# if the shape is a triangle, it will have 3 vertices
        if len(approx) == 3:
                shape = "triangle"

	# if the shape has 4 vertices, it is either a square or
	# a rectangle
        elif len(approx) == 4:
                # compute the bounding box of the contour and use the
		# bounding box to compute the aspect ratio
                (x, y, w, h) = cv2.boundingRect(approx)
                ar = w / float(h)

		# a square will have an aspect ratio that is approximately
		# equal to one, otherwise, the shape is a rectangle
                shape = "square" if ar >= 0.95 and ar <= 1.05 else "rectangle"

	# if the shape is a pentagon, it will have 5 vertices
        elif len(approx) == 5:
                shape = "pentagon"

	# otherwise, we assume the shape is a circle
        else:
                shape = "circle"

	# return the name of the shape
        return shape
Ejemplo n.º 9
0
    def contour(img):
        contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL,
                                               cv2.CHAIN_APPROX_NONE)

        for cnt in contours:
            area = cv2.contourArea(cnt)
            print(area)

            if area > 10:
                cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
                peri = cv2.arcLength(cnt, True)
                print(peri)
                approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
                print(len(approx))
                objCor = len(approx)
                x, y, w, h = cv2.boundingRect(approx)

                if objCor == 3:
                    objectType = "Tri"
                elif objCor == 4:
                    aspRatio = w / float(h)
                    if aspRatio > 0.95 and aspRatio < 1.05:
                        objectType = "Square"
                    else:
                        objectType = "Rectangle"
                elif objCor > 4:
                    objectType = "Circle"
                else:
                    objectType = "None"

                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.5, (10, 50, 20), 2)
Ejemplo n.º 10
0
def alineamiento(imagen,ancho,alto):
    imagen_alineada=None
    # le pasamos grises a la imagen
    grises=cv2.cvtColor(imagen, cv2.COLOR_BGR2GRAY)
    # devolvemos dos umbrales minimos y maximos
    tipoumbral,umbral=cv2.threshold(grises, 150,255, cv2.THRESH_BINARY)
    # mostramos el umbral
    cv2.imshow("Umbral", umbral)
    # contornos que devuelven dos valores, contorno y jerarquia
    contorno=cv2.findContours(umbral, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
    # ordenar los contornos son sorted
    # reverse ordena los puntos de menor a mayor, son para los eje x
    contorno=sorted(contorno,key=cv2.contourArea,reverse=True)[:1]
    # recorremos los cotornor
    for c in contorno:
        # la variable c esta recorriendo todos los contornos
        # epsilon ayuda a encontrar las areas
        # arcLenght sirve para sacar las areas
        epsilon=0.01*cv2.arcLength(c, True)
        # aca piden las curvas que va a analizar para que las curvas no tengan tando ruido
        approximacion=cv2.approxPolyDP(c, epsilon, True)
        # contamos objetos que tenemos en la lista
        # los 4 puntos forman un circulo
        if len(approximacion)==4:
            puntos=ordenarpuntos(approximacion)
            # convertimos los puntos en alto y ancho
            puntos1=np.float32(puntos)
            puntos2=np.float32([[0,0],[ancho,0],[0,alto],[ancho,alto]])
            # metodo de perspectiva
            # se mantiene fijo M en caso que la camara rote
            M = cv2.getPerspectiveTransform(puntos1, puntos2)
            # a la imagen alineada le pasamos la informacion
            imagen_alineada=cv2.warpPerspective(imagen, M, (ancho,alto))
    return imagen_alineada
Ejemplo n.º 11
0
def find_corners_of_largest_polygon(original, img):

    imgCopy = original.copy()
    cnts, hierarchy = cv2.findContours(img, cv2.RETR_TREE,
                                       cv2.CHAIN_APPROX_SIMPLE)
    cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5]
    '''c = cnts[2]
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)'''
    min_area = np.inf

    for c in cnts:
        # approximate the contour

        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02 * peri, True)

        # screenCnt = [[]]
        if len(approx) == 4:

            area = cv2.contourArea(c)
            if area < min_area:
                # del screenCnt[::]
                # screenCnt = approx

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

                if ((int(w / h)) == 1):

                    screenCnt = approx
                    min_area = area

    cv2.drawContours(imgCopy, [screenCnt], -1, (0, 255, 0), 3)

    # Top-left corner has minimum x+y
    s = []
    for x in screenCnt:
        for y in x:
            s.append(sum(y))

    d = np.array([])
    for x in screenCnt:
        for y in x:
            d = np.append(d, np.diff(y))

    rect = np.zeros((4, 2), dtype="float32")
    # Minimum sum is top-left corner
    rect[0] = screenCnt[s.index(min(s))]
    # Maximum is bottom-right
    rect[2] = screenCnt[s.index(max(s))]
    # Minimum difference is top-right point
    rect[1] = screenCnt[np.argmin(d)]
    # maximum difference is bottom left
    rect[3] = screenCnt[np.argmax(d)]

    # Thus the order of the points is top-left, top-right, bottom-right,bottom-left
    # print("rectangle", rect)
    # cv2.drawContours(imgCopy, [c], -1, (0, 255, 0), 3)
    # display_image('conotur waala image', imgCopy)
    return rect
Ejemplo n.º 12
0
def zoom_number(image, cont):
    inverted_threshold = filter_squares(image)
    contours = contours_numbers(inverted_threshold)
    largest_area = 0
    x = 0
    y = 0
    w = 0
    h = 0
    curve = 0
    for i, c in enumerate(contours):
        xTemp, yTemp, wTemp, hTemp = cv2.boundingRect(c)
        if( cv2.contourArea(c) > largest_area and \
            (hTemp < image.shape[0]*.9 and wTemp < image.shape[1]*.9)\
                and hTemp > 10 and wTemp > 10): #limites definidos, numero no es menor a 10 ni debe
            largest_area = cv2.contourArea(c)  # medir el 90% de la imagen
            curve = cv2.arcLength(c, True)
            x, y, w, h = cv2.boundingRect(c)
    # print("contourArea for",cont," is: ",curve,"image h:",image.shape[0],"image w:",image.shape[1])
    # print("contour h:",h," and w: ",w)

    # cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
    if (curve != 0):
        top_left_point = (x, y)
        top_right_point = (x + w, y)
        bottom_left_point = (x, y + h)
        bottom_right_point = (x + w, y + h)
        corners = np.float32([
            top_left_point, top_right_point, bottom_left_point,
            bottom_right_point
        ])
        result = transform(image, corners, 50, 50)
    else:
        result = image
    return result
Ejemplo n.º 13
0
def getContours(img):
    contours, hierachy = cv2.findContours(img, cv2.RETR_EXTERNAL,
                                          cv2.CHAIN_APPROX_NONE)
    for cnt in contours:
        area = cv2.contourArea(cnt)
        #print('Area: ', area)

        if area > 500:  # this check will confirm the area greater than threshold value to avoid noise
            cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
            peri = cv2.arcLength(cnt, True)
            #print('Perimeter:', peri)
            approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
            print('Approximate Corners: ', len(approx))
            objCorner = len(approx)
            x, y, w, h = cv2.boundingRect(approx)

            if objCorner == 3:
                objType = 'Triangle'
            elif objCorner == 4:
                aspRatio = w / float(h)
                if aspRatio > 0.95 and aspRatio < 1.05:
                    objType = 'Square'
                else:
                    objType = 'Rectangle'
            elif objCorner > 4:
                objType = 'Circle'
            else:
                objType = 'Other'

            cv2.rectangle(imgContour, (x, y), (x + w, y + h), (0, 255, 0), 2)
            cv2.putText(imgContour, objType,
                        (x + (w // 2) - 10, y + (h // 2) - 10),
                        cv2.FONT_HERSHEY_COMPLEX, 0.7, (0, 0, 0), 2)
Ejemplo n.º 14
0
def detect_holes(grey_frame, original_frame, frame_copy):
    thresh = cv.adaptiveThreshold(grey_frame, 1, 0, 0, 61, 10)
    contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE,
                                          cv.CHAIN_APPROX_NONE)
    for contour in contours:
        # area = cv.contourArea(contour)
        perimeter = cv.arcLength(contour, True)
        if len(contour) > 100 and 100 < perimeter < 300:
            # if len(contour) > 5 and 200 < area < 1000:
            x, y, w, h = cv.boundingRect(contour)
            img_c = frame_copy[y:y + h, x:x + w]
            img = cv.resize(img_c, IMAGE_SIZE)
            img_array = img_to_array(img)
            img_array = img_array.reshape(
                (1, ) + img_array.shape)  # Converting into 4 dimension array
            interpreter.set_tensor(input_details[0]['index'], img_array)
            interpreter.invoke()
            predictions = interpreter.get_tensor(output_details[0]['index'])
            if predictions[0][0] > 0.9:
                cv.rectangle(original_frame, (x, y), (x + w, y + h),
                             (0, 0, 255), 2)
                cv.imwrite(
                    new_dir + '/' + str(time.time()) + str(random()) + '.jpg',
                    img_c)
    return original_frame
Ejemplo n.º 15
0
def GetRightPos(image):
    # 边缘检测
    canny = cv2.Canny(image, 200, 400)

    # 轮廓提取
    img, contours, _ = cv2.findContours(canny, cv2.RETR_TREE,
                                        cv2.CHAIN_APPROX_SIMPLE)

    rightRectangles = []
    for i, contour in enumerate(contours):
        M = cv2.moments(contour)

        if M['m00'] == 0:
            cx, cy = 0, 0
        else:
            cx, cy = M['m10'] / M['m00'], M['m01'] / M['m00']

        if 1000 < cv2.contourArea(contour) < 1300 and 120 < cv2.arcLength(
                contour, True) < 400:
            if cx > 100:
                x, y, w, h = cv2.boundingRect(contour)  # 外接矩形
                rightRectangles.append((x, y, w, h))

    if len(rightRectangles) > 0:
        # 内侧方块
        current = min(rightRectangles, key=lambda s: s[2] * s[3])
        x, y, w, h = current[0], current[1], current[2], current[3]
        return x, y, w, h

    return 0, 0, 0, 0
Ejemplo n.º 16
0
def detect_holes(grey_frame, original_frame, frame, trackbars, count):
    thresh = cv.adaptiveThreshold(grey_frame, *trackbars)
    # ret, thresh = cv.threshold(grey_frame, 127, 140, 0)
    contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
    for contour in contours:
        # approx = cv.approxPolyDP(contour, 0.01 * cv.arcLength(contour, True), True)
        # area = cv.contourArea(contour)
        perimeter = cv.arcLength(contour, True)
        if len(contour) > 100 and 100 < perimeter < 300:
            # if len(contour) > 5 and 200 < area < 1000:
            x, y, w, h = cv.boundingRect(contour)
            img_c = original_frame[y:y + h, x:x + w]
            # if count % 30 == 0:
            #     cv.imwrite(new_dir + '/' + str(time.time()) + str(random()) + '.jpg', img_c)
            img = cv.resize(img_c, IMAGE_SIZE)
            img_array = img_to_array(img)
            img_array = img_array.reshape((1,) + img_array.shape)  # Converting into 4 dimension array
            interpreter.set_tensor(input_details[0]['index'], img_array)
            interpreter.invoke()
            predictions = interpreter.get_tensor(output_details[0]['index'])
            if predictions[0][0] > 0.9:
                # print(predictions[0][1])
                # if count % 30 == 0:
                # cv.imwrite(new_dir + '/' + str(time.time()) + str(random()) + '.jpg', img_c)
                cv.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
Ejemplo n.º 17
0
def ConvexHull_Cal(contour):

    IsTriangle = lambda a, b, c: a + b > c and a + c > b and b + c > a  #任意两边和必须大于第三边

    point_list = []
    convex_angle_ls = []
    concave_angle_ls = []

    epsilon = 0.003 * cv2.arcLength(contour, True)
    contour = cv2.approxPolyDP(contour, epsilon, True)  #轮廓近似,Douglas-Peucker算法
    hull = cv2.convexHull(contour, returnPoints=False)
    defects = cv2.convexityDefects(contour, hull)
    _, radius = cv2.minEnclosingCircle(contour)

    if defects is not None:
        for i in range(defects.shape[0]):
            s, e, f, _ = defects[i, 0]
            sta = tuple(contour[s][0])
            end = tuple(contour[e][0])
            far = tuple(contour[f][0])
            point_list.append([sta, far, end])

    #下面的角边标示含义见文件夹里的图片说明
    if len(point_list) >= 2:
        for it_1, it_2 in zip(point_list, point_list[1:] + point_list[:1]):
            CA = scfun.Eucledian_Distance(it_1[1], it_1[2])  #far to end
            AB = scfun.Eucledian_Distance(it_1[2], it_2[1])  #end to next far
            #凸包的角度
            if radius <= CA + AB < 2 * radius:
                BC = scfun.Eucledian_Distance(it_1[1],
                                              it_2[1])  #far to 2nd far,为底边
                if IsTriangle(CA, AB, BC):
                    angle = acos((CA**2 + AB**2 - BC**2) / (2 * CA * AB))
                    convex_angle_ls.append(angle)
            #凹陷的角度
            DC = scfun.Eucledian_Distance(it_1[0], it_1[1])  #sta to far
            if radius <= DC + CA < 2 * radius:
                DA = scfun.Eucledian_Distance(it_1[0],
                                              it_1[2])  #sta to end,为底边
                if IsTriangle(DC, CA, DA):
                    angle = acos((CA**2 + DC**2 - DA**2) / (2 * CA * DC))
                    concave_angle_ls.append(angle)

        convex_angle = [x for x in convex_angle_ls
                        if pi / 18 <= x <= pi / 6]  #凸包角度:10度至30度
        convex_len = len(convex_angle)
        concave_angle = [
            x for x in concave_angle_ls if pi / 18 <= x <= pi / 3.5
        ]
        concave_len = len(concave_angle)

        result = [convex_len, concave_len]

    else:
        result = [0, 0]

    return result
Ejemplo n.º 18
0
def approximationContour(img, contours, e=0.02):
    for cnt in contours:
        x, y, w, h = cv.boundingRect(cnt)
        print(f'x: {x}, y: {y}, w: {w}, h: {h}')
        epsilon = e*cv.arcLength(cnt, True)
        approx = cv.approxPolyDP(cnt, epsilon, True)
        print(len(approx))
        cv.drawContours(img, [approx], 0, (0,255,255), 2)
    return img
Ejemplo n.º 19
0
def smooth_contours(contours, peri_factor=0.007):
    smoothed_contours = []

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

        smoothed_contours.append(smooth_c)

    return smoothed_contours
Ejemplo n.º 20
0
def rectwithname(img, contours, e=0.02):
    result = img.copy()
    for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)
        epsilon = e*cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, epsilon, True)

#         if len(approx)<7:
        cv2.rectangle(result,(x,y),(x+w,y+h),(255,0,255),2)
    return result
Ejemplo n.º 21
0
def getContours(_img):
    contours, hierarchy = cv2.findContours(_img, cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_NONE)
    for cnt in contours:
        # area = cv2.contourArea(cnt)
        # cv2.drawContours(imgContour, cnt, -1, (255,0,0), 3)
        cnt_length = cv2.arcLength(cnt, True)
        cnt_vertexes_approx = cv2.approxPolyDP(cnt, 0.02 * cnt_length, True)
        x, y, w, h = cv2.boundingRect(cnt_vertexes_approx)
        cv2.rectangle(imgContour, (x, y), (x + w, y + h), (0, 255, 0), 3)
Ejemplo n.º 22
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
Ejemplo n.º 23
0
def do_rectangles(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    thresh = cv2.threshold(gray, 125, 255, cv2.THRESH_BINARY)[1]
    thresh = 255 - thresh
    cv2.imshow('thresh', thresh)
    cv2.waitKey()

    kernel = np.array(
        [[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1],
         [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1],
         [1, 1, 1, 1, 1, 1, 1]], np.uint8)
    kernel3 = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]], np.uint8)
    #dilation = cv2.dilate(thresh, kernel, iterations=4)
    #erosion = cv2.erode(dilation, kernel, iterations=2)
    #
    erosion = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel3)
    dilation = cv2.morphologyEx(erosion, cv2.MORPH_OPEN, kernel3)

    cv2.imshow('erosion7', erosion)
    cv2.imshow('dilation7', dilation)
    dilation = cv2.morphologyEx(dilation, cv2.MORPH_CLOSE, kernel)
    cv2.imshow('dilation3', dilation)
    cv2.waitKey()

    #exit()

    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
                            cv2.CHAIN_APPROX_NONE)

    cnts = imutils.grab_contours(cnts)
    disp = img.copy()
    clr = [0, 0, 0]
    for i in range(len(cnts)):
        idx = i % 3
        clr[idx] = np.random.randint(0, 256)
        #x, y, w, h = cv2.boundingRect(cnts[i])
        cv2.drawContours(disp, cnts, i, tuple(clr), 2)
        #cv2.rectangle(disp, (x, y), (x + w, y + h), clr, 2)

        rect = cv2.minAreaRect(cnts[i])
        box = cv2.boxPoints(rect)
        box = np.int0(box)
        #cv2.drawContours(disp, [box], 0, tuple(clr), 2)

    cv2.imshow('disp', disp)
    cv2.waitKey()

    for c in cnts:
        eps = 0.045 * cv2.arcLength(c, False)
        approx = cv2.approxPolyDP(c, eps, True)
        if len(approx) > 3:
            cv2.drawContours(img, [c], 0, (0, 255, 0), 2)
    cv2.imshow('img', img)
    cv2.waitKey()
Ejemplo n.º 24
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)
Ejemplo n.º 25
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
Ejemplo n.º 26
0
def biggestContour(contours):
    biggest = np.array([])
    max_area = 0
    for i in contours:
        area = cv2.contourArea(i)
        if area > 5000:
            peri = cv2.arcLength(i, True)
            approx = cv2.approxPolyDP(i, 0.02 * peri, True)
            if area > max_area and len(approx) == 4:
                biggest = approx
                max_area = area
    return biggest, max_area
Ejemplo n.º 27
0
def getBiggestcontour(contours):
    biggest = np.array([])
    max_area = 0
    for contour in contours:
        area = cv2.contourArea(contour)
        if area > 2000:
            peri = cv2.arcLength(contour, True)
            shape = cv2.approxPolyDP(contour, 0.02 * peri, True)
            if area > max_area and len(shape) == 4:
                biggest = shape
                max_area = area
    return biggest, max_area
Ejemplo n.º 28
0
 def getContours(self, mask):
     contours, heirarchy = cv2.findContours(mask, 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 > 200:
             # cv2.drawContours(self.imgResult, cnt, -1, (255, 0, 0), 2)
             perimeter = cv2.arcLength(cnt, True)
             approx = cv2.approxPolyDP(cnt, 0.02 * perimeter, True)
             x, y, w, h = cv2.boundingRect(approx)
     return x + w // 2, y
Ejemplo n.º 29
0
def getContour(img):
    
    contours,hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    for cntr in contours:
        area = cv2.contourArea(cntr)
        if area > 300:
            cv2.drawContours(imgContour, cntr, -1, (0,255,0), 1)
            perimeter = cv2.arcLength(cntr, True)
            approx = cv2.approxPolyDP(cntr, 0.01*perimeter, True)
            x,y,w,h = cv2.boundingRect(approx)
            points.append([x+w//2, y])
            cv2.circle(imgContour, (x+w//2, y), 10, (255, 0, 0), cv2.FILLED)
Ejemplo n.º 30
0
def GetCoords():
    COORDSTOSEND = []
    # Reading image
    font = cv2.FONT_HERSHEY_COMPLEX
    img2 = cv2.imread('PlayerTank.png', cv2.IMREAD_COLOR)
    # Reading same image in another
    # variable and converting to gray scale.
    img = cv2.imread('PlayerTank.png', cv2.IMREAD_GRAYSCALE)
    # Converting image to a binary image
    # ( black and white only image).
    _, threshold = cv2.threshold(img, 110, 255, cv2.THRESH_BINARY)
    # Detecting contours in image.
    contours, _ = cv2.findContours(threshold, cv2.RETR_TREE,
                                   cv2.CHAIN_APPROX_SIMPLE)
    tankNum = 0
    # Going through every contours found in the image.
    for cnt in contours:
        data = []
        approx = cv2.approxPolyDP(cnt, 0.009 * cv2.arcLength(cnt, True), True)

        # draws boundary of contours.
        #cv2.drawContours(img2, [approx], 0, (0, 0, 255), 5)
        # Used to flatted the array containing
        # the co-ordinates of the vertices.
        n = approx.ravel()
        i = 0

        for j in n:
            #delete x=j if it causes issues.
            x = j
            if (i % 2 == 0):
                x = n[i]
                y = n[i + 1]
                data.append((x, y))
                string = str(x) + " " + str(y)
            i = i + 1
        #print(data)
        x, y = np.mean(data, axis=0)
        string = str(x) + " " + str(y)
        if y < 650:
            print(string)
            COORDSTOSEND.append((x, y))
            cv2.putText(img2, str(tankNum), (int(x), int(y)), font, 4,
                        (0, 255, 0))
            tankNum = tankNum + 1
            cv2.drawContours(img2, [approx], 0, (0, 0, 255), 5)
    # Showing the final image.
    #cv2.imshow('image2', img2)
    cv2.imwrite('ImageWithPlayerCoords.png', img2)
    # Exiting the window if 'q' is pressed on the keyboard.
    #if cv2.waitKey(0) & 0xFF == ord('q'):
    #   cv2.destroyAllWindows()
    return COORDSTOSEND