Ejemplo n.º 1
0
def findend():
    global endpoint

    hsv_image = cv2.cvtColor(img_maze, cv2.COLOR_BGR2HSV)
  
   # define range of red color in HSV
    lower_red = np.array([0,100,100])
    upper_red = np.array([135,255,255])
   
    # Threshold the HSV image to get only blue colors
    mask = cv2.inRange(hsv_image, lower_red, upper_red)
    

    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(hsv_image,hsv_image, mask= mask)
    cimg=res
    res=cv2.cvtColor(res, cv2.COLOR_RGB2GRAY)

    circles = cv2.HoughCircles(res,cv2.HOUGH_GRADIENT,1,30,param1=50,param2=10,minRadius=0,maxRadius=0)
    #circles = np.uint16(np.around(circles))

    for i in circles[0,:]:
    # draw the outer circle
        cv2.circle(cimg,(i[0],i[1]),i[2],(255,0,0),2)
     # draw the center of the circle
        cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
        endpoint = (i[0],i[1])
Ejemplo n.º 2
0
    def _get_balls(self, filename, color, cam_id):
        # print('looking for ' + color)
        image = cv2.imread(filename)

        bounds = COLOR_BOUNDS[color]

        hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
        bright = cv2.inRange(hsv, bounds[0], bounds[1])
        blur = cv2.GaussianBlur(bright, (9, 9), 3, 3)

        # cv2.imshow('circled_orig', blur)
        # cv2.waitKey(0)

        detected_circles = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT,
                                            **HOUGH_PARAMS)
        balls = []

        if detected_circles is not None:
            for circle in detected_circles[0, :]:
                x = circle[0]
                y = circle[1]
                r = circle[2]
                # circled_orig = cv2.circle(image, (x, y), r, (0, 255, 0), thickness = 2)

                # locate detected balls
                distance = self._find_distance(x, y, r, cam_id)
                balls.append(distance)
                # balls.append((x, y, r, color))
                # balls.append()
            # cv2.imshow('circled_orig', circled_orig)
            # cv2.waitKey(0)
        # print('found')
        # print(balls)
        return balls
def get_balls(image, color, bounds, camera):

    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    bright = cv2.inRange(hsv, bounds[0], bounds[1])
    blur = cv2.GaussianBlur(bright, **GAUSS_PARAMS)

    # detected_circles = cv2.HoughCircles(blurred_mask, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
    detected_circles = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT,
                                        **HOUGH_PARAMS)
    balls = []

    if detected_circles is not None:
        for circle in detected_circles[0, :]:
            x = circle[0]
            y = circle[1]
            r = circle[2]

            # locate detected balls
            position, distance = find_position(x, y, r, camera)
            circled_orig = cv2.circle(image, (x, y),
                                      r, (0, 255, 0),
                                      thickness=1)

            font = cv2.FONT_HERSHEY_SIMPLEX
            # x = x - 10
            print(x, y)
            cv2.putText(circled_orig, str(format(distance, '.2f')), (x, y),
                        font, 0.5, (255, 255, 255), 2, cv2.LINE_AA)

            balls.append((x, y, r, color))

        display_image(circled_orig)

    return balls
Ejemplo n.º 4
0
	def _get_balls(self, image, color, bounds, cam_id = 1):

		# converting the input stream into HSV color space
		hsv_conv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

		bright_mask = cv2.inRange(hsv_conv_img, bounds[0], bounds[1])

		blurred_mask = cv2.GaussianBlur(bright_mask, (9, 9), 3, 3)

		# some morphological operations (closing) to remove small blobs
		erode_element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
		dilate_element = cv2.getStructuringElement(cv2.MORPH_RECT, (8, 8))
		eroded_mask = cv2.erode(blurred_mask, erode_element)
		dilated_mask = cv2.dilate(eroded_mask, dilate_element)

		detected_circles = cv2.HoughCircles(dilated_mask, cv2.HOUGH_GRADIENT, **HOUGH_PARAMS)
		balls = []

		if detected_circles is not None:
			for circle in detected_circles[0, :]:
				x = circle[0]
				y = circle[1]
				r = circle[2]
				circled_orig = cv2.circle(image, (x, y), r, (0, 255, 0), thickness=2)
				
				# locate detected balls
				# https_www.pyimagesearch.com/?url=https%3A%2F%2Fwww.pyimagesearch.com%2F2015%2F01%2F19%2Ffind-distance-camera-objectmarker-using-python-opencv%2F
				distance = self.find_position(x, y, r, cam_id)
				balls.append((x, y, r, color))
			cv2.imshow('circled_orig', circled_orig)
			cv2.waitKey(0)

		return balls
Ejemplo n.º 5
0
def houghCircle():
    image_1 = cv2.imread('원형이 있는 이미지.png')
    image_2 = image_1.copy()

    image_2 = cv2.GaussianBlur(image_2, (9, 9), 0)  # GaussianBlur로 이미지 흐리게 만들기
    image_gray = cv2.cvtColor(image_2, cv2.COLOR_BGR2GRAY)  # 이미지 흑백으로 만들기

    # 원본과 비율, 찾은 원형 모양 간 최소 중심거리, param1, param2를 조절하여 원 찾기
    circles = cv2.HoughCircles(image_gray,
                               cv2.HOUGH_GRADIENT,
                               1,
                               10,
                               param1=60,
                               param2=50,
                               minRadius=0,
                               maxRadius=0)

    if circles is not None:  # 이미지 안에 원형 모양이 있다면
        circles = np.unit16(np.around(circles))

        for i in circles[0, :]:
            cv2.circle(image_1, (i[0], i[1]), i[2], (255, 255, 0), 2)

        cv2.imshow('ori', image_2)
        cv2.imshow('HoughCircle', image_1)

        cv2.waitKey(0)
        cv2.destroyAllWindows()

    else:
        print("이미지 안에 원형 모양이 없음")
Ejemplo n.º 6
0
 def hough_circle(self, img):
     mode_of_operation = cv2.HOUGH_GRADIENT
     return cv2.HoughCircles(img,
                             mode_of_operation,
                             1,
                             20,
                             param1=200,
                             param2=20,
                             minRadius=0)
Ejemplo n.º 7
0
def process(filename):
    print(filename)

    filename = 'old.png'
    image = cv2.imread(filename)
    # display_image(image)
    # display_image(image)

    # convert the image to greyscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # apply blur for noise reduction
    gray = cv2.medianBlur(gray, 7)
    # display_image(gray)

    # print(gray.shape)
    # rows = gray.shape[0]

    # # apply Hough gradient
    # circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 400)
    # circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, rows / 8, param1=200, param2=37, minRadius=1, maxRadius=300)

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    img = cv2.medianBlur(gray, 17)
    # display_image(cimg)
    # detect circles in the image

    circles = cv2.HoughCircles(img,
                               cv2.HOUGH_GRADIENT,
                               1,
                               20,
                               param1=50,
                               param2=30,
                               minRadius=0,
                               maxRadius=0)

    balls = []
    print(circles)

    if circles is not None:
        circles = np.uint16(np.around(circles[0, :]).astype("int"))
        for (x, y, r) in circles:
            color = get_color(image, x, y, r)
            balls.append([x, y, r, color])
            center = (x, y)

            # marking detected circles
            cv2.circle(image, center, 1, (0, 100, 100), 2)
            cv2.circle(image, center, r, (255, 255, 255), 2)
    print(balls)
    print(len(balls))
    display_image(image)
def applyCircles(img):
    # PIL Image to OpenCV Image
    pilImg = img.convert('RGB')
    ocvImg = np.array(pilImg)
    img = ocvImg[:, :, ::-1].copy()
    gsImg = cv2.cvtColor(ocvImg[:, :, ::-1].copy(), cv2.COLOR_BGR2GRAY)
    # Find cirlces
    circles = cv2.HoughCircles(gsImg, cv2.HOUGH_GRADIENT, 1, 20, param1 = 200, param2 = 20, minRadius = 0)
    if circles is not None:
        draw_circle(circles,ocvImg)
        img = ocvImg
    # openCV to PIL
    return Image.fromarray(img)#cv2.cvtColor(img, cv2.COLOR_GRAY2RGB))
Ejemplo n.º 9
0
def do_circles(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    _, gray = cv2.threshold(gray, 125, 255, cv2.THRESH_BINARY)
    gray = 255 - gray
    cv2.imshow('bw', gray)
    cv2.waitKey()

    kernel = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]], np.uint8)

    kernel2 = 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]], np.uint8)
    erosion = cv2.dilate(gray, kernel2, iterations=5)
    cv2.imshow('dilate', erosion)
    cv2.waitKey()

    erosion = cv2.erode(erosion, kernel2, iterations=5)
    cv2.imshow('rode', erosion)
    cv2.waitKey()

    erosion = cv2.dilate(erosion, kernel2, iterations=5)
    cv2.imshow('dilate2', erosion)
    cv2.waitKey()

    erosion = cv2.erode(erosion, kernel2, iterations=5)
    cv2.imshow('rode2', erosion)
    cv2.waitKey()

    #erosion = cv2.dilate(erosion, kernel, iterations=2)
    #cv2.imshow('dilate', erosion)
    #cv2.waitKey()

    canny = cv2.Canny(erosion, 50, 150)
    cv2.imshow('canny', canny)
    cv2.waitKey()

    circles = cv2.HoughCircles(erosion,
                               cv2.HOUGH_GRADIENT,
                               2,
                               50,
                               param1=150,
                               param2=100,
                               minRadius=50)

    for i in circles[0, :]:
        # draw the outer circle
        cv2.circle(erosion, (i[0], i[1]), i[2], (255, 255, 255), 2)
        # draw the center of the circle
        cv2.circle(erosion, (i[0], i[1]), 2, (255, 255, 255), 3)

    cv2.imshow('circles', erosion)
    cv2.waitKey()
Ejemplo n.º 10
0
def process():
    """
	turn the image into hsv and make red mask to do CHT
	"""

    image = cv2.imread("camImage.png")
    #blur to improve circle detection through noise
    #get HSV mapping for red values
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

    #create mask for lower red HSV threshold
    mask_lower = cv2.inRange(hsv, RED_MIN_LOWER, RED_MAX_LOWER)

    #create mask for upper red HSV threshold
    mask_upper = cv2.inRange(hsv, RED_MIN_UPPER, RED_MAX_UPPER)

    #combine both masks
    mask = cv2.addWeighted(mask_lower, 1.0, mask_upper, 1.0, 0.0)

    kernel = np.ones((5, 5), np.uint8)

    #erode and dilate then dilate and erode
    mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
    mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)

    cv2.imwrite("hsvMask.png", mask)

    #apply Gaussian Blur to improve detection and remove some noise
    blur = cv2.GaussianBlur(mask, (11, 11), 0)
    cv2.imwrite("blurredImg.png", blur)

    #perform CHT
    circles = cv2.HoughCircles(blur, cv2.cv.CV_HOUGH_GRADIENT, 1, 40, 800, 150,
                               20, 0)

    try:
        circles = np.uint16(np.around(circles))
    except AttributeError:
        print("No Circles Found! Adjust parameters of CHT.")

    try:
        for i in circles[0, :]:
            # draw the outer circle
            cv2.circle(image, (i[0], i[1]), i[2], (0, 255, 0), 2)
            # draw the center of the circle
            cv2.circle(image, (i[0], i[1]), 2, (0, 0, 255), 3)
    except TypeError:
        print("No Circles Found! Adjust parameters of CHT")

    #write out image with drawn circles
    cv2.imwrite("detectedCircles.png", image)
def draw_circles(img):
    output = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
    circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1.2, minDist=100)#minDist=200, param1=30, param2=45, minRadius=0, maxRadius=0)
    if circles is not None:
        # convert the (x, y) coordinates and radius of the circles to integers
        circles = np.round(circles[0, :]).astype("int")

        for (x, y, r) in circles:
            # draw the circle in the output image, then draw a rectangle
            # corresponding to the center of the circle
            cv2.circle(output, (x, y), r, RGB_GREEN, 4)
            cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), RGB_GREEN, -1)
    
    return output
Ejemplo n.º 12
0
def find_circles(img, BOARD):
    param1, param2 = load_configs()
    blocksizes = get_block_size(img)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray_blurred = cv2.medianBlur(gray, 5)
    detected_circles = cv2.HoughCircles(gray_blurred,
                                        cv2.HOUGH_GRADIENT, 1, 30, param1=param1,
                                        param2=param2, minRadius=0, maxRadius=int(img.shape[0] / 8))

    if detected_circles is not None:
        detected_circles = np.uint16(np.around(detected_circles))
        for (x, y, r) in detected_circles[0, :]:
            output = img.copy()
            cv2.circle(output, (x, y), r, (0, 255, 0), 2)
            cv2.destroyAllWindows()
            BOARD[get_block_id_by_cords((x, y), blocksizes=blocksizes)]["Piece"] = img[y, x]
Ejemplo n.º 13
0
def houghCircle(I: np.ndarray, minRadius: float,
                maxRadius: float) -> np.ndarray:
    #https://www.youtube.com/watch?v=-o9jNEbR5P8
    I = cv2.cvtColor(I, cv2.COLOR_BGR2GRAY)
    I = blurImage1(I, 21)

    circ = cv2.HoughCircles(I,
                            cv2.CV_HOUGH_GRADIENT,
                            0.9,
                            120,
                            param1=50,
                            param2=30,
                            minRadius=minRadius,
                            maxRadius=maxRadius)
    roundCirc = np.uint16(np.around(circ))

    return roundCirc
Ejemplo n.º 14
0
def haugh_circle_transform_demo(image):  #霍夫圆检测
    dst = cv.pyrMeanShiftFiltering(image, 10, 100)  #对噪声敏感,所以降噪
    cimage = cv.cvtColor(dst, cv.COLOR_BGR2GRAY)
    circles = cv.HoughCircles(cimage,
                              cv.HOUGH_GRADIENT,
                              1,
                              20,
                              param1=50,
                              param2=30,
                              minRadius=0,
                              maxRadius=0)
    circles = np.uint16(np.around(circles))
    print(circles)
    for i in circles[0, :]:  #这里报错的原因不知道
        cv.circle(image, (i[0], i[1]), i[2], (0, 0, 0), 2)
        cv.circle(image, (i[0], i[1]), 2, (255, 0, 0), 2)
    cv.imshow("circles", image)
Ejemplo n.º 15
0
def initialize_config_colors(img):
    param1, param2 = load_configs()
    blocksizes = get_block_size(img)
    COLOR_TOP, COLOR_BOT = [], []

    # find circles
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray_blurred = cv2.medianBlur(gray, 5)
    detected_circles = cv2.HoughCircles(gray_blurred,
                                        cv2.HOUGH_GRADIENT, 1, 30, param1=param1,
                                        param2=param2, minRadius=0, maxRadius=int(img.shape[0] / 8))

    if detected_circles is not None:
        detected_circles = np.uint16(np.around(detected_circles))
        for (x, y, r) in detected_circles[0, :]:
            board_id = get_block_id_by_cords((x, y), blocksizes=blocksizes)
            color = list(img[y, x])
            if board_id < 40:
                COLOR_TOP.append(color)
            else:
                COLOR_BOT.append(color)

    if len(COLOR_TOP) < 12:
        return False

    if len(COLOR_BOT) < 12:
        return False

    if COLOR_TOP.count(COLOR_TOP[0]) != len(COLOR_TOP):
        return False

    if COLOR_BOT.count(COLOR_BOT[0]) != len(COLOR_BOT):
        return False

    # convert types
    color_top_value = tuple([int(i) for i in COLOR_TOP[0]])
    color_bot_value = tuple([int(i) for i in COLOR_BOT[0]])

    # prepare to save
    d = dict()
    d["COLOR_TOP"] = color_top_value
    d["COLOR_BOT"] = color_bot_value

    # save file
    json.dump(d, open(save_configs("color_config.txt"), 'w'))
    return True, d
Ejemplo n.º 16
0
def detectCircles(img,
                  param1=200,
                  param2=90,
                  minRadius=10,
                  maxRadius=130,
                  bias=15):
    roi = img.copy()
    img = cv.bilateralFilter(img, 9, 75, 75)  # Smoothing
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    # gray = cv.medianBlur(gray, 5)
    # gray = cv.equalizeHist(gray)
    circles = cv.HoughCircles(gray,
                              cv.HOUGH_GRADIENT,
                              1,
                              20,
                              param1=param1,
                              param2=param2,
                              minRadius=minRadius,
                              maxRadius=maxRadius)

    if circles is not None:
        circles = np.int32(np.around(circles))
        rs = []
        for c in circles[0, :]:
            rs.append(c[2])
        max_id = rs.index(max(rs))
        for c in circles[0, :]:
            if rs[max_id] == c[2]:
                # cv.circle(img, (c[0],c[1]), c[2], (0,0,255), 2)
                # cv.circle(img, (c[0],c[1]), 2, (255,0,0), 2)
                # 矩形框选
                ix = c[0] - c[2] - bias
                iy = c[1] - c[2] - bias
                ex = c[0] + c[2] + bias
                ey = c[1] + c[2] + bias
                if ix == -bias and iy == -bias and ex == bias and ey == bias:
                    return None, None, None
                if c[2] > 30:  # > 90
                    return 'locked', roi[iy:ey + 1,
                                         ix:ex + 1], [ix, iy, ex, ey]
                else:
                    return 'captured', roi[iy:ey + 1,
                                           ix:ex + 1], [ix, iy, ex, ey]
    else:
        cv.imshow('camera', img)
        return None, None, None
Ejemplo n.º 17
0
def find_circles(img):
    BOARD = generate_chessboard()
    param1, param2 = load_configs()
    blocksizes = get_block_size(img)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray_blurred = cv2.medianBlur(gray, 5)
    detected_circles = cv2.HoughCircles(gray_blurred,
                                        cv2.HOUGH_GRADIENT, 1, 30, param1=param1,
                                        param2=param2, minRadius=0, maxRadius=int(img.shape[0] / 8))

    if detected_circles is not None:
        detected_circles = np.uint16(np.around(detected_circles))
        output = img.copy()
        for (x, y, r) in detected_circles[0, :]:
            cv2.circle(output, (x, y), r, (0, 255, 0), 2)
            BOARD[get_block_id_by_cords((x, y), blocksizes=blocksizes)]["Piece"] = img[y, x]
            cv2.imwrite("savecircles.png", output)
    return BOARD
Ejemplo n.º 18
0
def obtain_circle_positions(img):
    try:
        circles = cv2.HoughCircles(
            img,
            cv2.HOUGH_GRADIENT,
            1.8,
            minDist=90,
            maxRadius=250,
            minRadius=20
        )  #minDist=200, param1=30, param2=45, minRadius=0, maxRadius=0)
    except Exception as e:
        print(e)

    print("Finding circles...")
    if circles is not None:
        # convert the (x, y) coordinates and radius of the circles to integers
        circles = np.round(circles[0, :]).astype("int")
    return circles
Ejemplo n.º 19
0
def find_circles(filename, dp, minDist, param1, param2, minRadius, maxRadius):
    if filename == "":
        no_file()
        return
    global circles_list
    circles_list.clear()
    og = mpimg.imread(filename)
    img = cv2.imread(filename, 0)
    img = cv2.medianBlur(img, 5)
    g_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

    circles = cv2.HoughCircles(img,
                               cv2.HOUGH_GRADIENT,
                               dp,
                               minDist,
                               param1=param1,
                               param2=param2,
                               minRadius=minRadius,
                               maxRadius=maxRadius)
    if circles is None:
        messagebox.showwarning(title="No circles",
                               message="No se ha encontrado ningún circulo")
        return
    circles = np.round(circles[0, :]).astype("int")
    i = 1
    for (x, y, r) in circles:
        cv2.circle(g_img, (x, y), r, (0, 255, 0), 4)
        cv2.rectangle(g_img, (x - 3, y - 3), (x + 3, y + 3), (0, 0, 255), -1)
        cv2.putText(g_img, f"C_{i}", (x - 30, y - r - 10),
                    cv2.FONT_HERSHEY_SIMPLEX, 1, (102, 17, 0), 2)
        cv2.putText(g_img, f"Radio = {r}", (x - 45, y + r + 20),
                    cv2.FONT_HERSHEY_SIMPLEX, .5, (102, 17, 0), 2)

        circles_list.append((f"Circulo {i}", x, y, r))
        i += 1

    f = plt.figure(num="Circulos encontrados", facecolor="#0a0b11")
    f.add_subplot(1, 2, 1)
    plt.imshow(og)
    f.add_subplot(1, 2, 2)
    plt.imshow(cv2.cvtColor(g_img, cv2.COLOR_BGR2RGB))
    plt.show(block=False)
    show_sorts()
Ejemplo n.º 20
0
def calibrate_params(filename="planszafullborder.jpg"):
    WINDOW_NAME = "Config"
    cv2.namedWindow(WINDOW_NAME)

    cv2.createTrackbar('param1', WINDOW_NAME, 10, 255, nothing)
    cv2.createTrackbar('param2', WINDOW_NAME, 10, 255, nothing)
    switch = ' \n1 : SAVE Config'
    cv2.createTrackbar(switch, WINDOW_NAME, 0, 1, nothing)

    img = load_image(filename)
    # img = resize(20, img)

    output = img.copy
    while (1):
        param1 = cv2.getTrackbarPos('param1', WINDOW_NAME)
        param2 = cv2.getTrackbarPos('param2', WINDOW_NAME)
        s = cv2.getTrackbarPos(switch, WINDOW_NAME)

        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray_blurred = cv2.medianBlur(gray, 5)
        detected_circles = cv2.HoughCircles(gray_blurred,
                                            cv2.HOUGH_GRADIENT, 1, 30, param1=param1,
                                            param2=param2, minRadius=0, maxRadius=int(img.shape[0] / 8))

        if detected_circles is not None:
            output = img.copy()
            detected_circles = np.uint16(np.around(detected_circles))
            for (x, y, r) in detected_circles[0, :]:
                cv2.circle(output, (x, y), r, (0, 255, 0), 4)

        cv2.imshow(WINDOW_NAME, output)
        k = cv2.waitKey(1) & 0xFF
        if k == 27:
            break
        if s == 1:
            d = dict()
            d["param1"] = param1
            d["param2"] = param2
            json.dump(d, open(save_configs("config.txt"), 'w'))
            break

    cv2.destroyAllWindows()
Ejemplo n.º 21
0
    def process(self, action: Action, mat_bgr: np.ndarray) -> np.ndarray:
        detected_circles: np.ndarray = cv.HoughCircles(
            mat_bgr,
            method=action.params['method'],
            dp=action.params['dp'],
            minDist=action.params['min_dist'],
            param1=action.params['param1'],
            param2=action.params['param2'],
            minRadius=action.params['min_radius'],
            maxRadius=action.params['max_radius'])
        res_img = np.copy(mat_bgr)
        if detected_circles is not None:
            circles = np.round(detected_circles[0, :]).astype("int")
            if len(circles) > 0:
                res_img = cv.cvtColor(res_img, cv.COLOR_GRAY2BGR)
            for (x, y, r) in circles:
                cv.circle(res_img, (x, y), r, (0, 255, 255),
                          2)  # yellow in BGR

        return res_img
 def detect_ball(self, frame, res):
     # Adapted from
     # https://stackoverflow.com/questions/42840526/opencv-python-red-ball-detection-and-tracking
     #
     # on the color-masked, blurred and morphed image I apply the cv2.HoughCircles-method to detect circle-shaped objects
     detected_circles = cv2.HoughCircles(res,
                                         cv2.HOUGH_GRADIENT,
                                         1,
                                         150,
                                         param1=100,
                                         param2=20,
                                         minRadius=20,
                                         maxRadius=200)
     if detected_circles is not None:
         for circle in detected_circles[0, :]:
             circled_orig = cv2.circle(frame, (circle[0], circle[1]),
                                       circle[2], (0, 255, 0),
                                       thickness=3)
         return circled_orig
     else:
         return frame
Ejemplo n.º 23
0
def process_instance(im, im_info):
    points = np.array(im_info['canonical_board']['tl_tr_br_bl'])

    matrix, _ = cv2.findHomography(points, reference_points)

    warped_im = cv2.warpPerspective(im, matrix, (1000, 1000))
    gray_im = cv2.cvtColor(warped_im, cv2.COLOR_BGR2GRAY)
    circles = cv2.HoughCircles(gray_im, cv2.HOUGH_GRADIENT, 1, 60, param1=400, param2=15, minRadius=30, maxRadius=40)

    checkers_count = {
        'top': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
        'bottom': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    }

    circles = np.uint16(np.around(circles))
    for i in circles[0,:]:
        cv2.circle(warped_im,(i[0],i[1]),i[2],(0,255,0),2)
        cv2.circle(warped_im,(i[0],i[1]),2,(0,0,255),3)

        x, y, _ = i

        if 480 < x < 530:
            continue

        if y < 400:
            spot = 'top'
        elif y > 600:
            spot = 'bottom'
        else:
            continue

        pip = math.floor(x/85)
        checkers_count[spot][pip] += 1

    plt.figure()
    plt.imshow(cv2.cvtColor(warped_im, cv2.COLOR_BGR2RGB))
    plt.show()

    return checkers_count, warped_im
Ejemplo n.º 24
0
def find_pieces(img):
    BOARD = generate_chessboard()
    param1, param2 = load_configs()
    color_dict = swap_dict_keys_and_vals(load_configs_dict())
    print(color_dict)
    blocksizes = get_block_size(img)

    # find circles
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray_blurred = cv2.medianBlur(gray, 5)
    detected_circles = cv2.HoughCircles(gray_blurred,
                                        cv2.HOUGH_GRADIENT, 1, 30, param1=param1,
                                        param2=param2, minRadius=0, maxRadius=int(img.shape[0] / 8))

    if detected_circles is not None:
        detected_circles = np.uint16(np.around(detected_circles))
        output = img.copy()
        for (x, y, r) in detected_circles[0, :]:
            board_id = get_block_id_by_cords((x, y), blocksizes=blocksizes)
            cv2.circle(output, (x, y), r, (0, 255, 0), 2)

            color_value = tuple(list(img[y + r - 20, x + r - 20]))
            BOARD[board_id]["Piece"] = color_dict[color_value]
            cv2.imwrite("savecircles.png", output)

            rectX = int(x - r)
            rectY = int(y - r)
            r = int(r)
            # area_to_check = img[rectX:(rectX + 2 * r), rectY+10:(rectY + 2 * r)]
            area_to_check = img[rectY+15:(rectY + 2 * r - 15), rectX+10:(rectX + 2 * r-10)]
            # area_to_check = img[y - r:(y + r), x - r:(x + r)]
            # cv2.imwrite(str(board_id) + ".png", area_to_check)
            crown_flag = is_crown(area_to_check)
            BOARD[board_id]["Crown"] = crown_flag

    return BOARD
Ejemplo n.º 25
0
def img_process_p1(img, type, anchor_loc, outputsize=(30, 30)):
    height, width = img.shape[:2]
    anchor_x, anchor_y = anchor_loc
    # print(anchor_x,anchor_y)
    if type.find('B') != -1:
        if anchor_x == 0 and anchor_y == 0:
            src = img[
                int(height *
                    P1_LOCATION[1]):int(height *
                                        (P1_LOCATION[1] + P1_LOCATION[3])),
                int(width *
                    P1_LOCATION[0]):int(width *
                                        (P1_LOCATION[0] + P1_LOCATION[2]))]
        else:
            src = img[int(anchor_y + height * P1_ANCHOR_RELATIVE_LOCATION_B[1]
                          ):int(anchor_y +
                                height * P1_ANCHOR_RELATIVE_LOCATION_B[1] +
                                height * P1_ANCHOR_RELATIVE_LOCATION_B[3]),
                      int(anchor_x + width * P1_ANCHOR_RELATIVE_LOCATION_B[0]
                          ):int(anchor_x +
                                width * P1_ANCHOR_RELATIVE_LOCATION_B[0] +
                                width * P1_ANCHOR_RELATIVE_LOCATION_B[2])]
    elif type.find('S') != -1:
        if anchor_x == 0 and anchor_y == 0:
            src = img[int(height * P1_LOCATION_S[1]):int(height *
                                                         (P1_LOCATION_S[1] +
                                                          P1_LOCATION_S[3])),
                      int(width * P1_LOCATION_S[0]):int(width *
                                                        (P1_LOCATION_S[0] +
                                                         P1_LOCATION_S[2]))]
        else:
            src = img[int(anchor_y + height * P1_ANCHOR_RELATIVE_LOCATION_S[1]
                          ):int(anchor_y +
                                height * P1_ANCHOR_RELATIVE_LOCATION_S[1] +
                                height * P1_ANCHOR_RELATIVE_LOCATION_S[3]),
                      int(anchor_x + width * P1_ANCHOR_RELATIVE_LOCATION_S[0]
                          ):int(anchor_x +
                                width * P1_ANCHOR_RELATIVE_LOCATION_S[0] +
                                width * P1_ANCHOR_RELATIVE_LOCATION_S[2])]
    else:
        raise ValueError(
            'parameter \'type\' must be in [\'B\' ,\'S\'] or [\'140B\',\'140S\',\'142B\',\'142S\']'
        )
    gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    height, width = gray.shape[:2]

    ret, thres_img = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)
    erode_img = eroded(thres_img, (3, 3))
    dilate_img = dilated(erode_img, (3, 3))
    # blur = cv2.GaussianBlur(gray,(17,17),0)
    canny = cv2.Canny(
        dilate_img,
        130,
        150,
        apertureSize=7,
    )
    # cv2.imshow('dilate_img1',dilate_img)
    # cv2.imshow('canny1',canny)

    # cv2.waitKey()
    # 霍夫圆检测
    circles = cv2.HoughCircles(thres_img,
                               cv2.HOUGH_GRADIENT,
                               dp=1,
                               minDist=5,
                               param1=200,
                               param2=16,
                               minRadius=20,
                               maxRadius=30)
    # print(circles)
    if circles is not None:

        if circles.shape[1] > 1:
            circle = circles[0][np.argmax(circles[0, :, 2])]
            # print(circles)
        else:
            circle = circles[0, 0, :]
        box_radius = 25
        circle_box = None
        for circle in circles[0]:
            cent_x, cent_y, _ = circle
            if cent_x > 3 * width / 16 and cent_x < 13 * width / 16 \
                    and cent_y > 25 * height / height and cent_y < 95 * height / height:
                # 获取包含螺丝的一个大概范围
                circle_box = gray[int(cent_y - box_radius):int(cent_y +
                                                               box_radius),
                                  int(cent_x - box_radius):int(cent_x +
                                                               box_radius)]
        if circle_box is not None:
            # print(circles)
            ret, thres_img2 = cv2.threshold(circle_box, 100, 255,
                                            cv2.THRESH_BINARY)
            contours, hierarchy = cv2.findContours(thres_img2, cv2.RETR_LIST,
                                                   cv2.CHAIN_APPROX_SIMPLE)
            length_rang = (30, 40)
            for contour in contours:
                x, y, w, h = cv2.boundingRect(contour)

                if w > length_rang[0] and w < length_rang[1] and \
                        h > length_rang[0] and h < length_rang[1]:  # and cv2.contourArea(contour) > w*h/2
                    # print(x,y,w,h)
                    result_img = circle_box[y:y + h, x:x + w]
                    result_img = cv2.resize(result_img, outputsize)

                    return result_img
Ejemplo n.º 26
0
def img_process_p2(img, type, anchor_loc, outputsize=(50, 50)):
    height, width = img.shape[:2]
    anchor_x, anchor_y = anchor_loc
    # print(anchor_x,anchor_y)
    if type.find('B') != -1:
        if anchor_x == 0 and anchor_y == 0:
            src = img[
                int(height *
                    P2_LOCATION[1]):int(height *
                                        (P2_LOCATION[1] + P2_LOCATION[3])),
                int(width *
                    P2_LOCATION[0]):int(width *
                                        (P2_LOCATION[0] + P2_LOCATION[2]))]
        else:
            src = img[int(anchor_y + height * P2_ANCHOR_RELATIVE_LOCATION_B[1]
                          ):int(anchor_y +
                                height * P2_ANCHOR_RELATIVE_LOCATION_B[1] +
                                height * P2_ANCHOR_RELATIVE_LOCATION_B[3]),
                      int(anchor_x + width * P2_ANCHOR_RELATIVE_LOCATION_B[0]
                          ):int(anchor_x +
                                width * P2_ANCHOR_RELATIVE_LOCATION_B[0] +
                                width * P2_ANCHOR_RELATIVE_LOCATION_B[2])]
    elif type.find('S') != -1:
        if anchor_x == 0 and anchor_y == 0:
            src = img[int(height * P2_LOCATION_S[1]):int(height *
                                                         (P2_LOCATION_S[1] +
                                                          P2_LOCATION_S[3])),
                      int(width * P2_LOCATION_S[0]):int(width *
                                                        (P2_LOCATION_S[0] +
                                                         P2_LOCATION_S[2]))]
        else:
            src = img[int(anchor_y + height * P2_ANCHOR_RELATIVE_LOCATION_S[1]
                          ):int(anchor_y +
                                height * P2_ANCHOR_RELATIVE_LOCATION_S[1] +
                                height * P2_ANCHOR_RELATIVE_LOCATION_S[3]),
                      int(anchor_x + width * P2_ANCHOR_RELATIVE_LOCATION_S[0]
                          ):int(anchor_x +
                                width * P2_ANCHOR_RELATIVE_LOCATION_S[0] +
                                width * P2_ANCHOR_RELATIVE_LOCATION_S[2])]

    else:
        raise ValueError(
            'parameter \'type\' must be in [\'B\' ,\'S\'] or [\'140B\',\'140S\',\'142B\',\'142S\']'
        )
    gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    height, width = gray.shape[:2]
    # cv2.imshow('gray2',gray)
    # hist = cv2.equalizeHist(gray)
    # cv2.imshow('hist2',hist)
    ret, thres_img = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
    blur = cv2.GaussianBlur(gray, (9, 9), 0)
    canny = cv2.Canny(blur, 100, 150, apertureSize=7)
    circles = cv2.HoughCircles(canny,
                               cv2.HOUGH_GRADIENT,
                               dp=1,
                               minDist=6,
                               param1=300,
                               param2=20,
                               minRadius=23,
                               maxRadius=28)
    # print(circles)
    # cv2.imshow('canny2',canny)
    # cv2.imshow('thres_img2',thres_img)
    # cv2.waitKey()

    if circles is not None:
        circles = np.mean(circles, axis=1, keepdims=True)
        for circle in circles[0, :]:
            cent_x, cent_y, radius = circle
            # print(circle)
            # if cent_x < 0.4*width or cent_x > 0.6*width \
            #     or cent_y < 0.4*height or cent_y > 0.6*height:
            #     continue

            circle_img = gray[int(cent_y - radius):int(cent_y + radius),
                              int(cent_x - radius):int(cent_x + radius)]
            # print(circle)
            # cv2.circle(img,(cent_x,cent_y),int(radius),(0,255,0),3)
            # cv2.imshow('img',img)
            # cv2.waitKey()
            # cv2.imshow('circle_img',circle_img)
            result_img = cv2.resize(circle_img, outputsize)
            return result_img
Ejemplo n.º 27
0
        cv2.circle(frame, (cX_right, cY_right), 1, (0, 0, 255), -1)

        # Finding Hough Circles in left and right eye images
        gray_left = cv2.cvtColor(left_eye_image, cv2.COLOR_BGR2GRAY)
        equ_left = cv2.equalizeHist(gray_left)
        equ_left_resized = cv2.resize(equ_left, (24, 8),
                                      interpolation=cv2.INTER_AREA)
        gray_right = cv2.cvtColor(right_eye_image, cv2.COLOR_BGR2GRAY)
        equ_right = cv2.equalizeHist(gray_right)
        equ_right_resized = cv2.resize(equ_right, (24, 8),
                                       interpolation=cv2.INTER_AREA)
        #circles_left = cv2.HoughCircles(equ_left,cv2.HOUGH_GRADIENT,1,gray_left.shape[0]/8,param1=250,param2=15,minRadius=gray_left.shape[1]/8,maxRadius=gray_left.shape[0]/3)
        circles_left = cv2.HoughCircles(equ_left,
                                        cv2.HOUGH_GRADIENT,
                                        1,
                                        20,
                                        param1=50,
                                        param2=30,
                                        minRadius=0,
                                        maxRadius=0)
        if isinstance(circles_left, np.ndarray):
            circles_left = np.uint16(np.around(circles_left))
            mean_values_left = []
            for i in circles_left[0, :]:
                ##                                width = equ_left.shape[0]
                ##                                height = equ_left.shape[1]
                ##                                circle_img = np.zeros((height,width), np.uint8)
                # cv2.circle(circle_img,(i[0],i[1]),i[2],1,thickness=-1)
                ##                                masked_data = cv2.bitwise_and(gray_left, gray_left, mask=circle_img)
                ##                                mean_val = cv2.mean(equ_left,mask = masked_data)
                # mean_values_left.append(mean_val)
                ##                        max_index_left = [i for i, j in enumerate(mean_values_left) if j == min(mean_values_left)]
Ejemplo n.º 28
0
# A circle is represented mathematically as (x-x_{center})^2 + (y - y_{center})^2 = r^2 where (x_{center},y_{center}) is the center of the circle, and r is the radius of the circle. From equation, we can see we have 3 parameters, so we need a 3D accumulator for hough transform, which would be highly ineffective. So OpenCV uses more trickier method, Hough Gradient Method which uses the gradient information of edges.

# The function we use here is cv2.HoughCircles(). It has plenty of arguments which are well explained in the documentation. So we directly go to the code.

from cv2 import cv2
import numpy as np

img = cv2.imread('resource/opencv_logo.png', 0)
img = cv2.medianBlur(img, 5)
cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img,
                           cv2.HOUGH_GRADIENT,
                           1,
                           20,
                           param1=50,
                           param2=30,
                           minRadius=0,
                           maxRadius=0)

circles = np.uint16(np.around(circles))[0]
for i in circles:
    cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
    cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)

cv2.imshow('detected circles', cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
Ejemplo n.º 29
0
#canny= cv2.Canny(gray, 100, 200)

#cv2.imshow('output', gray)
#cv2.waitKey(0)
#cv2.destroyAllWindows()

min_value = 0  #usually zero
max_value = 300
#input('Max value: ') #maximum reading of the gauge

#Using Hough cirlces to find the cirlces in the image
#detect circles
#restricting the search from 35-48% of the possible radii gives fairly good results across different samples.  Remember that
#these are pixel values which correspond to the possible radii search range.

circle_img = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, np.array([]),
                              100, 50, int(height * 0.35), int(height * 0.50))
a, b, c = circle_img.shape
circle_img

a, b, c = circle_img.shape
a, b, c

for (x, y, r) in circle_img[0, :]:
    cv2.circle(output2, (x, y), r, (0, 255, 0), 3)
    cv2.circle(output2, (x, y), 2, (0, 255, 0), 3)
    print(x, y, r)

cv2.imshow('output0', output2)
cv2.waitKey(0)
cv2.destroyAllWindows()
Ejemplo n.º 30
0
# Carrega imagens
todas_iris = [cv2.imread(file) for file in glob.glob("imagens/*.jpg")]

for i in range(0, len(todas_iris)):
    print('processamento imagem ' + str(i) + " de " + str(len(todas_iris)))

    # Faz imagem ficar cinza e aplica blur
    img = todas_iris[i]
    img_cinza = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_cinza = cv2.GaussianBlur(img_cinza, (5, 5), 0)

    # Procura circulos da iris e pupila
    iris = cv2.HoughCircles(img_cinza,
                            cv2.HOUGH_GRADIENT,
                            1,
                            40,
                            param1=50,
                            param2=30,
                            minRadius=180,
                            maxRadius=190)
    pupila = cv2.HoughCircles(img_cinza,
                              cv2.HOUGH_GRADIENT,
                              1.1,
                              20,
                              param1=10,
                              param2=50,
                              minRadius=30,
                              maxRadius=50)

    # Pega o tamanho da imagem pra fazer uma mascara
    height, width, z = img.shape
    mask = np.zeros((height, width), np.uint8)