コード例 #1
0
    def image_callback(self, ros_img):
        # Convert received image message to OpenCv image
        cv_image = bridge.imgmsg_to_cv2(ros_img,
                                        desired_encoding="passthrough")
        output = cv_image.copy()
        gray_img = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)
        hsv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV)

        # red range here doesn't work well, needs to wrap around 255 0 or something like that, fix is to combine mask
        # lower = np.array([0, 100, 100])
        # upper = np.array([20, 255, 255])

        # red range here works better,but not using fix proposed from online forums
        # lower = np.array([0, 50, 20])
        # upper = np.array([5, 255, 255])

        circles = cv2.HoughCircles(gray_img, cv2.HOUGH_GRADIENT, 1.7, 5)
        if circles is not None:
            # convert the (x, y) coordinates and radius of the circles to integers
            circles = np.round(circles[0, :]).astype("int")
            # loop over the (x, y) coordinates and radius of the circles
            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, (255, 0, 255), 4)

        # yellow
        lower = np.array([22, 93, 0], dtype="uint8")
        upper = np.array([45, 255, 255], dtype="uint8")

        mask = cv2.inRange(hsv_image, lower, upper)

        cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL,
                                cv2.CHAIN_APPROX_SIMPLE)
        cnt = cnts[0]

        # find centroid location
        M = cv2.moments(cnt)
        if M['m00'] > 0:
            xbar = int(M['m10'] / M['m00'])
            ybar = int(M['m01'] / M['m00'])
            global xbar, ybar

        # temp=self.convert_image_pixel_to_cm()

        cnts = cnts[0] if len(cnts) == 2 else cnts[1]

        # print len(cnts), " contours"
        for c in cnts:
            x, y, w, h = cv2.boundingRect(c)
            cv2.rectangle(cv_image, (x, y), (x + w, y + h), (12, 255, 12), 2)
            cv2.rectangle(cv_image, (318, 198), (322, 202), (0, 0, 255), 1)
            reticle = [320, 200]  # reticle centered location
            # prevents robot from crawling
            if xbar > reticle[0]:
                adjust_high_X = True
                adjust_low_X = False

            if xbar < reticle[0]:
                adjust_high_X = False
                adjust_low_X = True

            # positve y is in conventional negative direction
            if ybar > reticle[1]:
                adjust_high_Y = True
                adjust_low_Y = False

            if ybar < reticle[1]:
                adjust_high_Y = False
                adjust_low_Y = True

        global adjust_high_X, adjust_low_X, adjust_high_Y, adjust_low_Y
        cv2.imshow("output", cv_image)
        # cv2.imshow('Image', cv_image)  # display image
        cv2.waitKey(1)
コード例 #2
0
#kernel = np.ones((2.6,2.7),np.uint8)
#gray = cv2.erode(gray,kernel,iterations = 1)
# gray = erosion

#gray = cv2.dilate(gray,kernel,iterations = 1)
# gray = dilation

# get the size of the final image
# img_size = gray.shape
# print img_size

# detect circles in the image
circles = cv2.HoughCircles(gray,
                           cv2.HOUGH_GRADIENT,
                           1,
                           260,
                           param1=30,
                           param2=65,
                           minRadius=0,
                           maxRadius=0)
# print circles

# ensure at least some circles were found
if circles is not None:
    # convert the (x, y) coordinates and radius of the circles to integers
    circles = np.round(circles[0, :]).astype("int")

    # loop over the (x, y) coordinates and radius of the circles
    for (x, y, r) in circles:
        # draw the circle in the output image, then draw a rectangle in the image
        # corresponding to the center of the circle
        cv2.circle(output, (x, y), r, (0, 255, 0), 4)
コード例 #3
0
    img_raw = img_raw[:, :, :3]
    img_h, img_w = img_raw.shape[:2]
    if img_h > img_w:
        ratiox = DIM1 / img_w
        ratioy = DIM2 / img_h
        img_raw = cv2.resize(img_raw, (DIM1, DIM2))
    else:
        ratiox = DIM2 / img_w
        ratioy = DIM1 / img_h
        img_raw = cv2.resize(img_raw, (DIM2, DIM1))

    gray = cv2.cvtColor(img_raw, cv2.COLOR_BGR2GRAY)
    circles = cv2.HoughCircles(gray,
                               cv2.HOUGH_GRADIENT,
                               1,
                               100,
                               param1=hough_upper_threshold,
                               param2=hough_lower_threshold,
                               minRadius=hough_min_radius,
                               maxRadius=hough_max_radius)

    if circles is not None:
        # convert the (x, y) coordinates and radius of the circles to integers
        circles = np.round(circles[0, :]).astype("int")
        # copy the image, for painting we will use another
        drawn_image = img_raw.copy()
        # loop over the found circles
        for i in range(len(circles)):
            # get one
            (x, y, r) = circles[i]
            # draw the circle in the output image, then draw a rectangle corresponding to the center of the circle
            cv2.rectangle(drawn_image, (x - r, y - r), (x + r, y + r),
コード例 #4
0
border_size = 2
center_color = (0, 128, 255)

image = cv2.imread("image/ball.jpg")
output = image.copy()
im_color = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
# cv2.inRange()
cv2.imshow("output", np.hstack([image, im_color]))
gray = cv2.cvtColor(output, cv2.COLOR_BGR2GRAY)
cv2.imwrite("image/grayBall.jpg", gray)
edged = cv2.Canny(
    gray, first_threshold, second_threshold
)  # find borders use canny-algoritm на вход подаются 2 пороговых значения
cv2.imwrite("image/borders.jpg", edged)
circles = cv2.HoughCircles(
    gray, cv2.HOUGH_GRADIENT, acc, 2, 100
)  # save resolution, 100 - Minimum distance between the centers of the detected circles Hough transform1-same resolution
if circles is not None:
    circles = np.round(circles[0, :]).astype(
        "int"
    )  # convert the (x, y) coordinates and radius of the circles to integers
    for (
            x, y, r
    ) in circles:  # loop over the (x, y) coordinates and radius of the 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, (0, 255, 0), border_size)
        cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), center_color, -1)

    #cv2.imshow("output", np.hstack([image, output]))
    cv2.waitKey(0)
コード例 #5
0
#Filtro Gaussiano
imgGaussian = cv2.GaussianBlur(imgGray, (11, 11), 1)

#Filtro de Sobel
imgSobelEixoX = cv2.Sobel(imgGaussian, cv2.CV_8U, 1, 0, ksize=5)
imgSobelEixoY = cv2.Sobel(imgGaussian, cv2.CV_8U, 0, 1, ksize=5)
imgSobel = imgSobelEixoX + imgSobelEixoY

#Filtro de Canny
imgCanny = cv2.Canny(img, 100, 200)

#Detecção de Círculos
circles = cv2.HoughCircles(imgGray,
                           cv2.HOUGH_GRADIENT,
                           1,
                           20,
                           param1=65,
                           param2=50,
                           minRadius=0,
                           maxRadius=0)
detected_circles = np.uint16(np.around(circles))

#Desenhando os cículos encontrados na cópia da imagem
for (x, y, r) in detected_circles[0, :]:
    cv2.circle(imgCopy, (x, y), r, (0, 255, 255), 2)
    cv2.circle(imgCopy, (x, y), 2, (0, 0, 255), 2)

cv2.imshow("Imagem Original / Círculos encontrados", np.hstack([img, imgCopy]))
cv2.waitKey(0)
cv2.destroyAllWindows()
コード例 #6
0
import cv2 as cv
import numpy as np

src = cv.imread("./pictures/circles.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
gray = cv.GaussianBlur(gray, (9, 9), 2, 2)
dp = 1
param1 = 100
param2 = 50

circles = cv.HoughCircles(gray, cv.HOUGH_GRADIENT, dp, 10, None, param1,
                          param2, 20, 100)
print("circles type: ", type(circles))
for c in circles[0, :]:
    print(c)
    cx, cy, r = c
    cv.circle(src, (cx, cy), 2, (0, 255, 0), 2, 8, 0)
    cv.circle(src, (cx, cy), r, (0, 0, 255), 2, 8, 0)

# show
cv.imshow("hough line demo", src)
cv.imwrite("contours_analysis.png", src)
cv.waitKey(0)
cv.destroyAllWindows()
コード例 #7
0
import cv2

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())

# load the image, clone it for output, and then convert it to grayscale
image = cv2.imread(args["image"])
output = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV)[1]
cv2.imshow("image", gray)
cv2.waitKey(0)

# detect circles in the image
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 3000)
# ensure at least some circles were found
if circles is not None:
    # convert the (x, y) coordinates and radius of the circles to integers
    circles = np.round(circles[0, :]).astype("int")
    # loop over the (x, y) coordinates and radius of the circles
    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, (0, 255, 0), 4)
        cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255),
                      -1)
    # show the output image
    cv2.imshow("output", np.hstack([image, output]))
    cv2.waitKey(0)
コード例 #8
0
    cv2.line(drawing, (x1, y1), (x2, y2), (0, 0, 255))

cv2.imshow('hough lines', np.hstack((img, drawing)))
cv2.waitKey(0)

# 统计概率霍夫线变换
drawing = np.zeros(img.shape[:], dtype=np.uint8)
lines = cv2.HoughLinesP(edges, 0.8, np.pi / 180, 90, minLineLength=50, maxLineGap=10)

# 将检测的线画出来
for line in lines:
    x1, y1, x2, y2 = line[0]
    cv2.line(drawing, (x1, y1), (x2, y2), (0, 255, 0), 1, lineType=cv2.LINE_AA)
cv2.imshow('probabilistic hough lines', np.hstack((img, drawing)))
cv2.waitKey(0)

# 3. 霍夫圆变换
drawing = np.zeros(img.shape[:], dtype=np.uint8)

circles = cv2.HoughCircles(edges, cv2.HOUGH_GRADIENT, 1, 20, param2=30)
circles = np.int0(np.around(circles))

# 将检测的圆画出来
for i in circles[0, :]:
    cv2.circle(drawing, (i[0], i[1]), i[2], (0, 255, 0), 2)  # 画出外圆
    cv2.circle(drawing, (i[0], i[1]), 2, (0, 0, 255), 3)  # 画出圆心

cv2.imshow('circle', np.hstack((img, drawing)))
cv2.waitKey(0)
コード例 #9
0
import cv2
import numpy as np

count = 0
img = cv2.imread('./3.jpg', 0)
cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
blur = cv2.blur(img, (5, 5))

circles = cv2.HoughCircles(blur,
                           cv2.HOUGH_GRADIENT,
                           param1=50,
                           param2=50,
                           dp=1.94,
                           minDist=20,
                           minRadius=12,
                           maxRadius=25)
circles = np.uint16(np.around(circles))

color_img = cv2.imread("./3.jpg")
red = (0, 0, 255)
for x, y, r in circles[0]:
    cv2.circle(color_img, (x, y), r, red, 2)
    count += 1

cv2.imshow(f'Holes in tree: {count}', color_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
コード例 #10
0
if exp_type == brightloom:
    subframe1 = stim_end_frame + 3
    subframe2 = stim_end_frame + 47
video.set(cv2.CAP_PROP_POS_FRAMES, subframe1)
ok, frame = video.read()
first_frame = frame.copy()
video.set(cv2.CAP_PROP_POS_FRAMES, subframe2)
ok, frame = video.read()
last_frame = frame.copy()
img_output = np.zeros((last_frame.shape[0], last_frame.shape[1], 3), np.uint8)

# set scale
scale = frame.copy()
petri_dish = 560
gray_scale = cv2.cvtColor(scale, cv2.COLOR_BGR2GRAY)
circles = cv2.HoughCircles(gray_scale, cv2.HOUGH_GRADIENT, 1.2, 800, param1=50,param2=30,minRadius=80,maxRadius=pdmaxrad)

# determine scale using detected petri dish size
if circles is not None:
    # grab circle properties
    circles = np.round(circles[0, :]).astype("int")
    largest_r = 0
    # loop over the circles
    for (x, y, r) in circles:
        # draw the circle in the output image
        cv2.circle(scale, (x, y), r, (0, 255, 0), 4)
        cv2.rectangle(scale, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
        if largest_r < r:
            largest_r = r
    petri_dish = r * 2
    # show the output image
コード例 #11
0
    def camera(self, argv):
        distance = 0
        _, frame = self.src.read()  #reads the frames from the camera
        #gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
        blur_frame = cv.GaussianBlur(frame, (3, 3), 0)
        hsv = cv.cvtColor(
            blur_frame,
            cv.COLOR_BGR2HSV)  #converts the colorspace from BGR to HSV

        lower_blue = np.array([98, 75, 121])
        upper_blue = np.array([108, 141, 255])

        # Threshold the HSV image to get only blue colors

        mask = cv.inRange(
            hsv, lower_blue, upper_blue
        )  #filters out all colors that are out of the blue color range,

        # Bitwise-AND mask and original image
        #res = cv.bitwise_and(frame, frame, mask=mask)               #puts the

        #cv.imshow('frame', frame)
        #cv.imshow('mask', mask)

        #cv.imshow('res', res)

        rows = hsv.shape[0]  #tar ut alla rader fran bilden(640x480)
        blur = cv.GaussianBlur(mask, (3, 3), 0)

        circles = cv.HoughCircles(blur,
                                  cv.HOUGH_GRADIENT,
                                  1,
                                  rows / 1,
                                  param1=150,
                                  param2=15,
                                  minRadius=0,
                                  maxRadius=0)

        if circles is not None:
            circles = np.uint16(np.around(circles))
            for i in circles[0, :]:
                center = (i[0], i[1])

                # circle center
                cv.circle(blur, center, 1, (0, 100, 100), 3)
                # circle outline
                radius = i[2]
                cv.circle(blur, center, radius, (255, 0, 255), 3)
                distance = (center[0] - 80)
            # gopreturn distance
        # print(radius)
        cv.line(blur, (80, 0), (80, 120), (255, 0, 0), 5)
        print(distance)
        cv.imshow("detected circles", blur)

        X = distance * 1.25

        # Todo fix Y
        Y = 0
        ##print('hej')
        k = cv.waitKey(5) & 0xFF
        if k == 27:

            #break

            cv.destroyAllWindows()
            #p.stop()
            GPIO.cleanup()
            robot.motorStop()

        return X  ##, Y
コード例 #12
0
ファイル: center_distance_4.py プロジェクト: raaang/Braillez
        # if int(mnt['m00']) != 0:
        #     cx = int(mnt['m10'] / mnt['m00'])
        #     cy = int(mnt['m01'] / mnt['m00'])
        #     cv.circle(thresh1, (cx, cy), 2, (255, 0, 0), -1)
            # by_김주희_기울기 및 거리 구하기위해 중심 값 배열로 만듦 _200819
            # center_point.append([cx,cy])
            # center_y.append(cy)
            # rect_center = rect_center + [cx, cy]
cr = closing_2
cr = closing_2[:, :, 0]
# # cr[:, :, 1] = closing
# # cr[:, :, 2] = closing

# circles = cv.HoughCircles(cr,cv.HOUGH_GRADIENT,1,5,param1=50,param2=35,minRadius=1,maxRadius=0)
# circles = cv.HoughCircles(cr,cv.HOUGH_GRADIENT,1, 5)
circles = cv.HoughCircles(cr,cv.HOUGH_GRADIENT,1,100,param1=10,param2=35)

print(circles)
for c in circles[0, :]:
    center = (c[0], c[1])
    radius = c[2]

    # 바깥원
    cv.circle(closing_2, center, radius, (0, 255, 0), 2)

    # 중심원
    cv.circle(closing_2, center, 2, (0, 0, 255), 3)


plt.subplot(221)
plt.imshow(img, cmap='gray')
コード例 #13
0
def get_lens_edge(filename, crib, pixels_per_mm):
    # lens details preparation
    radius = crib * pixels_per_mm / 2

    # image preprocessing
    unprocessed_image = cv2.imread(filename, 0)
    height, width = unprocessed_image.shape
    mask = np.zeros((height, width), np.uint8)
    preprocessed_image = prep_circle_find(unprocessed_image, 2)
    edges = cv2.Canny(preprocessed_image, 150, 200)

    # find circles and process image
    try:
        radii = []
        found_circles = cv2.HoughCircles(edges,
                                         cv2.HOUGH_GRADIENT,
                                         1,
                                         500,
                                         param1=50,
                                         param2=30,
                                         minRadius=int(.98 * radius),
                                         maxRadius=int(1.05 * radius))
        for each_circle in found_circles[0, :]:
            radii.append((each_circle[2] - radius) / radius)
            ##define outer and inner radius
            outer_radius = int(each_circle[2] - 10 - (.25 * (radius - 520)))
            inner_radius = int(outer_radius * (.95))
            cv2.circle(mask, (each_circle[0], each_circle[1]),
                       outer_radius, (255, 255, 255),
                       thickness=-1)
            cv2.circle(mask, (each_circle[0], each_circle[1]),
                       inner_radius, (0, 0, 0),
                       thickness=-1)
            #debug print statements for edge shape analysis values
            # print('predicted circle radius = ' + str(radius))
            # print('found circle radius = ' + str(each_circle[2]))
            #print('Adjusted outer radius: ' + str(outer_radius))
            #print('Adjusted inner radius: ' + str(inner_radius))
            ##-----------------------------
        masked_data = cv2.bitwise_and(unprocessed_image,
                                      unprocessed_image,
                                      mask=mask)
        masked_preprocessed_data = cv2.bitwise_and(preprocessed_image,
                                                   preprocessed_image,
                                                   mask=mask)
        contours = cv2.findContours(masked_preprocessed_data,
                                    cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        x, y, w, h = cv2.boundingRect(contours[0])
        crop = masked_data[y:y + h, x:x + w]
        blur_crop = cv2.blur(crop, (4, 4))
        erode_crop = cv2.erode(blur_crop, (3, 3), iterations=1)
        ret_crop, thresh_crop = cv2.threshold(erode_crop, 190, 255,
                                              cv2.THRESH_BINARY)

        pi = np.pi
        edge_area = pi / 4 * ((outer_radius)**2 - inner_radius**2)

        return edge_area, radii, thresh_crop, crop, preprocessed_image
    except TypeError:
        cv2.imwrite(
            'cropped_results\\' +
            re.sub(r'.png', '', os.path.basename(filename)) +
            '_failed_no_circle_found.png', unprocessed_image)
        pass
コード例 #14
0
ファイル: tank.py プロジェクト: hugueds/tank-stickers
    def find_in_circle(self, frame: np.ndarray, erode=False):

        g_frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
        ys, ye, xs, xe = self.get_roi(frame)
        g_frame = self.__eliminate_non_roi(g_frame, ys, ye, xs, xe)

        _filter = self._filter

        if _filter == 'threshold':
            blur = cv.GaussianBlur(g_frame, tuple(self.blur), 0)
            _, mask = cv.threshold(blur, self.threshold, 255,
                                   cv.THRESH_BINARY_INV)
        elif _filter == 'adaptative':
            mask = cv.adaptiveThreshold(g_frame, 255,
                                        cv.ADAPTIVE_THRESH_MEAN_C,
                                        cv.THRESH_BINARY, 5, 2)
        else:
            cut_frame = frame.copy()
            cut_frame = self.__eliminate_non_roi(cut_frame, ys, ye, xs, xe)
            if _filter == 'hsv':
                cvt_frame = cv.cvtColor(cut_frame, cv.COLOR_BGR2HSV)
                lower = np.array((self.table_hsv[0][0], self.table_hsv[0][1],
                                  self.table_hsv[0][2]), np.uint8)
                higher = np.array((self.table_hsv[1][0], self.table_hsv[1][1],
                                   self.table_hsv[1][2]), np.uint8)
            else:
                cvt_frame = cv.cvtColor(cut_frame, cv.COLOR_RGB2LAB)
                lower = np.array((self.table_hsv[0][0], self.table_hsv[0][1],
                                  self.table_hsv[0][2]), np.uint8)
                higher = np.array((self.table_hsv[1][0], self.table_hsv[1][1],
                                   self.table_hsv[1][2]), np.uint8)
            mask = cv.inRange(cvt_frame, lower, higher)

        if erode:
            mask = cv.erode(mask, None, iterations=2)
            mask = cv.dilate(mask, None, iterations=2)

        if self.debug_tank:
            cv.imshow('debug_tank', mask)

        self.circles = cv.HoughCircles(mask,
                                       cv.HOUGH_GRADIENT,
                                       param1=self.params[0],
                                       param2=self.params[1],
                                       minDist=self.min_dist,
                                       dp=self.radius[0],
                                       minRadius=self.radius[1],
                                       maxRadius=self.radius[2])
        self.found = False
        self.x, self.y, self.w, self.h = 0, 0, 0, 0
        if self.circles is not None:
            circles = np.uint16(np.around(self.circles))
            for x, y, r in circles[0, :]:
                calc_x = int(x -
                             r) if (x - r) > 0 and x < frame.shape[1] else 0
                calc_y = int(y -
                             r) if (y - r) > 0 and y < frame.shape[0] else 0
                if (calc_x > 0 and calc_x < frame.shape[1]) and (
                        calc_y > 0 and calc_y < frame.shape[0]):
                    self.w, self.h = 2 * abs(r), 2 * abs(r)
                    self.x, self.y = calc_x, calc_y
                    self.found = True
                    self.image = frame[self.y:self.y + self.h,
                                       self.x:self.x + self.w]
コード例 #15
0
from resizeimage import resizeimage

img = cv2.imread('office3.jpg', 0)
#img=cv2.resize(zx, (960,540))
#img=resizeimage.resize_cover(zx,[200,100])
img = cv2.medianBlur(img, 5)
cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

cond = True
param = 10

while (cond):
    circles = cv2.HoughCircles(img,
                               cv2.HOUGH_GRADIENT,
                               1,
                               40,
                               param1=100,
                               param2=param,
                               minRadius=0,
                               maxRadius=0)
    circles = np.uint16(np.around(circles))
    if (circles[0].size / 3 > 0 and circles[0].size / 3 < 3):
        cond = False
    elif (circles[0].size / 3 == 0):
        parm -= 10
    else:
        param += 10
print param

for i in circles[0, :]:
    # draw the outer circle
    print(i[0], i[1])
コード例 #16
0
ファイル: houghcircles.py プロジェクト: AIpha00/crypto
import sys

if __name__ == '__main__':
    print(__doc__)

    try:
        fn = sys.argv[1]
    except IndexError:
        fn = "../data/board.jpg"

    src = cv.imread(fn, 1)
    img = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
    img = cv.medianBlur(img, 5)
    cimg = src.copy()  # numpy function

    circles = cv.HoughCircles(img, cv.HOUGH_GRADIENT, 1, 10, np.array([]), 100,
                              30, 1, 30)

    if circles is not None:  # Check if circles have been found and only then iterate over these and add them to the image
        a, b, c = circles.shape
        for i in range(b):
            cv.circle(cimg, (circles[0][i][0], circles[0][i][1]),
                      circles[0][i][2], (0, 0, 255), 3, cv.LINE_AA)
            cv.circle(cimg, (circles[0][i][0], circles[0][i][1]), 2,
                      (0, 255, 0), 3, cv.LINE_AA)  # draw center of circle

        cv.imshow("detected circles", cimg)

    cv.imshow("source", src)
    cv.waitKey(0)
コード例 #17
0
def main():
    """
    Example entry point; please see Enumeration example for more in-depth
    comments on preparing and cleaning up the system.

    :return: True if successful, False otherwise.
    :rtype: bool
    """
    # Retrieve singleton reference to system object
    system = PySpin.System.GetInstance()

    # Retrieve list of cameras from the system
    cam_list = system.GetCameras()

    num_cameras = cam_list.GetSize()

    print 'Number of cameras detected: %d' % num_cameras

    # Finish if there are no cameras
    if num_cameras == 0:

        # Clear camera list before releasing system
        cam_list.Clear()

        # Release system instance
        system.ReleaseInstance()

        print 'Not enough cameras!'
        raw_input('Done! Press Enter to exit...')
        return False

    # Run address of each camera
    cam = cam_list.GetByIndex(0)

    # Retrieve TL device nodemap and print device information
    nodemap_tldevice = cam.GetTLDeviceNodeMap()

    # Initialize camera
    cam.Init()

    # Retrieve GenICam nodemap
    nodemap = cam.GetNodeMap()

    # Acquire images
    # In order to access the node entries, they have to be casted to a pointer type (CEnumerationPtr here)
    node_acquisition_mode = PySpin.CEnumerationPtr(
        nodemap.GetNode('AcquisitionMode'))

    if not PySpin.IsAvailable(node_acquisition_mode) or not PySpin.IsWritable(
            node_acquisition_mode):
        print 'Unable to set acquisition mode to continuous (enum retrieval). Aborting...'
        return False

    # Retrieve entry node from enumeration node
    node_acquisition_mode_continuous = node_acquisition_mode.GetEntryByName(
        'Continuous')
    if not PySpin.IsAvailable(
            node_acquisition_mode_continuous) or not PySpin.IsReadable(
                node_acquisition_mode_continuous):
        print 'Unable to set acquisition mode to continuous (entry retrieval). Aborting...'
        return False

    # Retrieve integer value from entry node
    acquisition_mode_continuous = node_acquisition_mode_continuous.GetValue()

    # Set integer value from entry node as new value of enumeration node
    node_acquisition_mode.SetIntValue(acquisition_mode_continuous)

    cam.TLStream.StreamBufferHandlingMode.SetValue(
        PySpin.StreamBufferHandlingMode_NewestFirst)

    print 'Acquisition mode set to continuous...'

    #  Begin acquiring images
    #
    #  *** NOTES ***
    #  What happens when the camera begins acquiring images depends on the
    #  acquisition mode. Single frame captures only a single image, multi
    #  frame catures a set number of images, and continuous captures a
    #  continuous stream of images. Because the example calls for the
    #  retrieval of 10 images, continuous mode has been set.
    #
    #  *** LATER ***
    #  Image acquisition must be ended when no more images are needed.
    cam.BeginAcquisition()

    print 'Acquiring images...'

    #  Retrieve device serial number for filename
    #
    #  *** NOTES ***
    #  The device serial number is retrieved in order to keep cameras from
    #  overwriting one another. Grabbing image IDs could also accomplish
    #  this.
    device_serial_number = ''
    node_device_serial_number = PySpin.CStringPtr(
        nodemap_tldevice.GetNode('DeviceSerialNumber'))

    if PySpin.IsAvailable(node_device_serial_number) and PySpin.IsReadable(
            node_device_serial_number):
        device_serial_number = node_device_serial_number.GetValue()
        print 'Device serial number retrieved as %s...' % device_serial_number

    cv2.namedWindow('PyCapImg', cv2.WINDOW_GUI_NORMAL)
    cv2.resizeWindow('PyCapImg', 500, 550)

    while cv2.waitKey(1) & 0xFF != 27:
        try:
            image_result = cam.GetNextImage()

            if image_result.IsIncomplete():
                print 'Image incomplete with image status %d ...' % image_result.GetImageStatus(
                )

            else:

                #  Convert image to mono 8
                #
                #  *** NOTES ***
                #  Images can be converted between pixel formats by using
                #  the appropriate enumeration value. Unlike the original
                #  image, the converted one does not need to be released as
                #  it does not affect the camera buffer.
                #
                #  When converting images, color processing algorithm is an
                #  optional parameter.
                image_converted = image_result

                filename = 'Acquisition.bmp'

                #  Save image
                #
                #  *** NOTES ***
                #  The standard practice of the examples is to use device
                #  serial numbers to keep images of one device from
                #  overwriting those of another.
                image_converted.Save(filename)
                print 'Image saved at %s' % filename

                #  Release image
                #
                #  *** NOTES ***
                #  Images retrieved directly from the camera (i.e. non-converted
                #  images) need to be released in order to keep from filling the
                #  buffer.
                image_result.Release()
                print ''

                im = cv2.imread(filename, 3)

                "Convert BGR to HSV"
                hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
                #define range of blue color in HSV
                lower_red = np.array([86, 80, 80])
                upper_red = np.array([120, 255, 255])
                lower_green = np.array([40, 70, 70])
                upper_green = np.array([90, 255, 255])
                lower_blue = np.array([110, 50, 50])
                upper_blue = np.array([130, 255, 255])

                "opencv filters"
                mask = cv2.inRange(
                    hsv, lower_green, upper_green
                )  # Threshold the HSV image to get only blue colors
                mask = cv2.morphologyEx(
                    mask, cv2.MORPH_OPEN,
                    np.ones(OPEN_KERNEL_SHAPE,
                            dtype=np.uint8))  # Close operation for denoise

                # Bitwise-AND mask and original image
                #res = cv2.bitwise_and(im,im, mask= mask)

                "Blur the corrected result for denoising and debanding"
                mask = cv2.GaussianBlur(mask, (5, 5), 0)
                edges = cv2.Canny(mask, 250, 300)

                "detect circles"
                circles = cv2.HoughCircles(edges,
                                           cv2.HOUGH_GRADIENT,
                                           dp=2,
                                           minDist=MINDIST,
                                           param1=25,
                                           param2=30,
                                           minRadius=MINR,
                                           maxRadius=MAXR)
                print circles

                "put circles on the image"
                if circles is not None and len(circles) > 0:
                    circles = circles[0]
                    for (x, y, r) in circles:
                        x, y, r = int(x), int(y), int(r)
                        cv2.circle(im, (x, y), r, (255, 0, 0), 10)

                cv2.imshow('PyCapImg', im)

        except PySpin.SpinnakerException as ex:
            print 'Error: %s' % ex
            return False

    # Release reference to camera
    # NOTE: Unlike the C++ examples, we cannot rely on pointer objects being automatically
    # cleaned up when going out of scope.
    # The usage of del is preferred to assigning the variable to None.
    del cam

    # Clear camera list before releasing system
    cam_list.Clear()

    # Release system instance
    system.ReleaseInstance()
コード例 #18
0
def emphasize_lines(img, distances, estimatedRadius):
    '''
    Emphasize all of the straight lines in the image and get rid of unnecessary noise.

    Parameters:
        {Numpy.array} img - The image to edit
        {list} distances - [
                              {List} [
                                        {Number} x coordinate of the point,
                                        {Number} y coordinate of the point,
                                        {Number} The distance of the point from the bull'seye point
                                     ]
                              ...
                           ]
        {Number} estimatedRadius - A rough estimation of the target's radius,
                                   that will be used if for some reason it cannot be calculated on the fly.

    Returns:
        {Number} The target's current radius [px].
        {Numpy.array} An image with the lines emphasized.
    '''

    # find the target's outer ring
    circles = cv2.HoughCircles(img,
                               cv2.HOUGH_GRADIENT,
                               1,
                               20,
                               param1=50,
                               param2=30,
                               minRadius=0,
                               maxRadius=int(estimatedRadius * 1.05))

    # use largest detected circle
    if type(circles) != type(None):
        outerCircle = sorted(circles[0], key=lambda x: x[2])[::-1][0]
        radius = outerCircle[2]

    # use a rough estimation of the target's radius as a fallback
    else:
        radius = estimatedRadius

    # zero out all pixels outside of the outer ring
    img[distances[1] > radius] = 0

    # apply thresh and morphology
    _, img = cv2.threshold(img, 20, 0xff, cv2.THRESH_BINARY)
    img = cv2.morphologyEx(img, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))

    # find the straight segments in the image
    lines = cv2.HoughLinesP(img,
                            2,
                            np.pi / 180,
                            120,
                            minLineLength=20,
                            maxLineGap=0)
    img_copy = np.zeros(img.shape, dtype=img.dtype)

    if type(lines) != type(None):
        for line in lines:
            for x1, y1, x2, y2 in line:
                cv2.line(img_copy, (x1, y1), (x2, y2), (0xff, 0xff, 0xff), 5)

    return radius, img_copy
コード例 #19
0
import cv2
import numpy as np
import os.path
"""
Circle Detection - Hough Circles
cv2.HoughCircles(image, method, dp, MinDist, param1, param2, minRadius, MaxRadius)

Method - currently only cv2.HOUGH_GRADIENT available
dp - Inverse ratio of accumulator resolution
MinDist - the minimum distance between the center of detected circles
param1 - Gradient value used in the edge detection
param2 - Accumulator threshold for the HOUGH_GRADIENT method (lower allows more circles 
to be detected (false positives))
minRadius - limits the smallest circle to this size (via radius)
MaxRadius - similarly sets the limit for the largest circles
"""

image = cv2.imread(os.path.dirname(__file__) + '/../images/bottlecaps.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

blur = cv2.medianBlur(gray, 5)

circles = cv2.HoughCircles(blur, cv2.cv.CV_HOUGH_GRADIENT, 1.5, 10)
#circles = cv2.HoughCircles(gray, cv.CV_HOUGH_GRADIENT, 1, 10)

circles = np.uint16(np.around(
    circles))  # np.around 'Evenly round to the given number of decimals'

for i in circles[0, :]:
    # draw the outer circle
    cv2.circle(image, (i[0], i[1]), i[2], (255, 0, 0), 2)
from matplotlib import pyplot as plt
import math

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "Path to the image")
args = vars(ap.parse_args())

# load the image, clone it for output, and then convert it to grayscale
img = cv2.imread(args["image"])
output = img.copy()
output2 = img.copy()

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# detect circles in the image
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 100, param1=50,param2=60,minRadius=150,maxRadius=170)
radius = circles[0][0][2]

circles = np.uint16(np.around(circles))
for i in circles[0,:]:
    # draw the outer circle
    circle = cv2.circle(gray,(i[0],i[1]),i[2],(0, 255, 0),5)
    # draw the center of the circle
    cv2.circle(gray,(i[0],i[1]),2,(0, 255, 0),10)
#plt.imshow(gray)
cv2.line(gray,(i[0],i[1]),(math.ceil(i[0]+radius),i[1]),(0,255,0),5)
#plt.imshow(gray)


mask = np.zeros(img.shape[:2],np.uint8)
コード例 #21
0
def detect2(img_read, pt1, pt2, w):

        try:

            t1 = time.time()
            
            crop_img  = img_read[pt1[1]:pt2[1], pt1[0]:pt2[0]]
            
            distance = conf["distance"]
            
            #skp, tkp = cvlib.findKeyPoints(crop_img , target, distance)
 
            crop_img = cv2.medianBlur(crop_img, conf["blur_level"])
            
            gray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)

            circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, 
                          conf["dp"],#29, ## dp
                          conf["minDist"],#100, ## minDist
                          conf["param1"],#param1=70, 
                          conf["param2"],#param2=80, ## 
                          conf["minRadius"],#minRadius=20,
                          conf["maxRadius"]) #maxRadius=0)

            j = 0
            
            if DEBUG == "true": 
                cv2.rectangle(img_read, pt1, pt2, (0,255,0))

            """
            if DEBUG == "false":
                
                if circles == None:
        
                    #print "None."
                    save(0,0,0)
                    return 0
                    
                else:
                    
                    circles = np.uint16(np.around(circles))
                
                    save(circles)
                
                    return 1                
            """ 
            #print circles
            #print type(circles)
            if circles == None:
                #print "none"
                if DEBUG == "true": 
                    cv2.imshow("camera", img_read)
                save(0,0,0)

            else:                
                
                circles = np.uint16(np.around(circles))
                
                #x = circles[0][0][0]
                #y = circles[0][0][1]
                #r = circles[0][0][2]
                #print "else"
                for i in circles[0,:]:
                    
                    if supress(i, w):
                        
                        j = j + 1
                        
                        save(1,1,1)
                        #print i[2], i
                        if DEBUG == "true": 
                            cv2.circle(img_read,(pt1[0]+i[0],pt1[1]+i[1]),i[2],(0,255,0),2)
                            cv2.circle(img_read,(pt1[0]+i[0],pt1[1]+i[1]),2,(0,0,255),3)                       
                        
                        #cp = [ i[0], i[1] ]
                        
                        #print cp
                
                if DEBUG == "true":        
                    cv2.imshow("camera", img_read)
            
        except Exception as ex:
            #print(ex)
            #print(traceback.format_exc())
            logger.debug(ex)
コード例 #22
0
ファイル: circle_detection.py プロジェクト: bsunder10/opencv
import cv2
import numpy as np

img = cv2.imread('images/circle.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray_blurred = cv2.blur(gray, (3, 3))

#Circle Detection
detected_circle = cv2.HoughCircles(gray_blurred,
                                   cv2.HOUGH_GRADIENT,
                                   1,
                                   20,
                                   param1=50,
                                   param2=30,
                                   minRadius=1,
                                   maxRadius=40)

if detected_circle is not None:
    detected_circle = np.uint16(np.around(detected_circle))
    for pt in detected_circle[0, :]:
        a, b, r = pt[0], pt[1], pt[2]
        cv2.circle(img, (a, b), r, (0, 255, 0), 3)

        #For Center of circle
        cv2.circle(img, (a, b), 1, (255, 0, 1), 3)

    cv2.imshow('show', img)
    cv2.waitKey(0)

cv2.destroyAllWindows()
コード例 #23
0
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.2, 2)

    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
        roi_gray = gray[y:y + h, x:x + w]
        roi_color = img[y:y + h, x:x + w]

        eyes = eye_cascade.detectMultiScale(roi_gray)

        gray = cv2.medianBlur(gray, 5)
        rows = gray.shape[0]
        circles = cv2.HoughCircles(gray,
                                   cv2.HOUGH_GRADIENT,
                                   1,
                                   rows / 8,
                                   param1=100,
                                   param2=30,
                                   minRadius=1,
                                   maxRadius=30)
        font = cv2.FONT_HERSHEY_SIMPLEX

        if circles is not None:
            circles = np.uint16(np.around(circles))
            for i in circles[0, :]:
                center = (i[0], i[1])
                # circle center
                cv2.circle(img, center, 1, (0, 100, 100), 3)
                # circle outline
                radius = i[2]
                cv2.circle(img, center, radius, (255, 0, 255), 3)
コード例 #24
0
ファイル: cvideo.py プロジェクト: hamels2/Project-Work
    # resize the frame, blur it, and convert it to the HSV
    # color space
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # construct a mask for the color "green", then perform
    # a series of dilations and erosions to remove any small
    # blobs left in the mask
    termination = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1)
    mask = cv2.inRange(hsv, Orange1Lower, Orange1Upper)
    thresh = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(thresh, (9, 9), 0)

    mask = cv2.erode(mask, None, iterations=2)
    mask = cv2.dilate(mask, None, iterations=2)

    circles = cv2.HoughCircles(blurred, cv2.HOUGH_GRADIENT, 1, 2000, 25, 250,
                               10, 10)  # ret=[[Xpos,Ypos,Radius],...]

    if (circles is not None):
        ##mask = cv2.inRange(hsv, OrangeLower, OrangeUpper)
        ##mask = cv2.erode(mask, None, iterations=2)
        ##mask = cv2.dilate(mask, None, iterations=2)
        circles = np.uint16(np.around(circles))

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

    # find contours in the mask and initialize the current
    # (x, y) center of the ball
コード例 #25
0
import cv2
import numpy as np
import matplotlib as plt
image = cv2.imread("fifth.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
circles = cv2.HoughCircles(image,
                           cv2.cv.CV_HOUGH_GRADIENT,
                           2,
                           32,
                           param1=200,
                           param2=100)

if circles is not None:

    circles = np.round(circles[0, :]).astype("int")

    for (x, y, r) in circles:

        cv2.circle(circles, (x, y), r, (0, 255, 0), 4)

        img = np.hstack([image])

    cv2.imshow("circles", img)

cv2.waitKey(0)
cv2.destroyAllWindows()
コード例 #26
0
ファイル: Double_angles.py プロジェクト: Infiniteas/StoveBot
#     *   Detects Circles in Images   *
#     *                               *
#     *********************************

img = cv2.imread("./images/double4.jpg", cv2.IMREAD_COLOR)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
output = img.copy()

# Blur using 3 * 3 kernel.
gray_blurred = cv2.blur(gray, (3, 3))

# Apply Hough transform on the blurred image.
detected_circles = cv2.HoughCircles(gray_blurred,
                                    cv2.HOUGH_GRADIENT,
                                    1,
                                    40,
                                    param1=50,
                                    param2=30,
                                    minRadius=295,
                                    maxRadius=300)

# Draw circles that are detected.
if detected_circles is not None:
    # Convert the circle parameters a, b and r to integers.
    detected_circles = np.uint16(np.around(detected_circles))

    if detected_circles[0][0][0] < 1000:
        xl, yl, rl = detected_circles[0][0][0], detected_circles[0][0][
            1], detected_circles[0][0][2]
        xr, yr, rr = detected_circles[0][1][0], detected_circles[0][1][
            1], detected_circles[0][1][2]
    else:
コード例 #27
0
def return_circles_values(img):
    img = cv2.medianBlur(img,5)

    circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,2,200, param1=35,param2=20,minRadius=5,maxRadius=50)
    return circles
コード例 #28
0
while True:
    ret, frame = cap.read()
    assert ret  # TODO REMOVE THIS AAAAA

    blurred = cv2.GaussianBlur(frame, (7, 7), 0)
    hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)

    mask = cv2.inRange(hsv, yellow[0], yellow[1])
    morph = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((5, 5), np.uint8))

    edges = cv2.Canny(morph, 10, 200, 3)
    bedges = cv2.GaussianBlur(edges, (7, 7), 0)
    circles = cv2.HoughCircles(bedges,
                               cv2.HOUGH_GRADIENT,
                               2,
                               100,
                               maxRadius=100)

    display = frame.copy()
    if (isinstance(circles, np.ndarray) and len(circles)) or circles != None:
        circles = np.uint16(np.around(circles))[0]
        drawCircles(display, circles)

    cv2.imshow('frame', display)
    cv2.imshow('Edges', morph)

    key = cv2.waitKey(1 if running else 0)
    if key & 0xff == ord('q'):
        break
    elif key > 0:
コード例 #29
0
for file in directory:
    print(file)
file_name = input("Filename with extension: ")
path = os.getcwd() + '/001/L/%s' % (file_name)
image_read = cv2.imread(path)
output = image_read.copy()
image_test = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
image_test = cv2.GaussianBlur(image_test, (7, 7), 1)
cv2.imshow("imagetest", image_test)
image_test = cv2.Canny(image_test, 80, 100, apertureSize=3)
cv2.imshow("image_test", image_test)

circles = cv2.HoughCircles(image_test,
                           cv2.HOUGH_GRADIENT,
                           1,
                           50,
                           param1=50,
                           param2=50,
                           minRadius=0,
                           maxRadius=0)
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, (0, 255, 0), 2)
    cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)

cv2.imshow('detected circles', output)
cv2.waitKey(0)
コード例 #30
0
import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while (1):
    _, frame = cap.read()
    #frame = cv2.blur(fr,(5,5))
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    #gray = cv2.medianBlur(gray,5)
    cimg = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
    circles = cv2.HoughCircles(gray,
                               cv2.cv.CV_HOUGH_GRADIENT,
                               1,
                               25,
                               param1=60,
                               param2=28,
                               minRadius=10,
                               maxRadius=30)

    if circles is None:
        continue

    circles = np.uint16(np.around(circles))

    for i in circles:
        print len(i)
        for j in i:
            cv2.circle(cimg, (j[0], j[1]), j[2], (0, 255, 0), 2)
            cv2.circle(cimg, (j[0], j[1]), 2, (0, 0, 255), 3)