Exemplo n.º 1
0
def change_color(x):
    if cv2.getTrackbarPos(switch, 'image') == 0:
        return
    img[:] = [
        cv2.getTrackbarPos('B', 'image'),
        cv2.getTrackbarPos('G', 'image'),
        cv2.getTrackbarPos('R', 'image')
    ]
    return
Exemplo n.º 2
0
def val_trackbars():
    min_val = cv.getTrackbarPos('min', "TrackBars")
    max_val = cv.getTrackbarPos('max', "TrackBars")
    aperture_size = cv.getTrackbarPos("apertureSize", "TrackBars")
    if aperture_size < 3:
        aperture_size = 3
    if aperture_size % 2 == 0:
        aperture_size += 1
    src = [min_val, max_val, aperture_size]
    return src
Exemplo n.º 3
0
def tune_thresholds(vid_feed, thresholds):
    """DOCSTRING"""
    # initialize window
    win = 'Adjustment Control Panel'
    cv2.namedWindow(win)

    # initialize variables and trackbars
    thresh_names = ['H_LO', 'H_HI',
                    'S_LO', 'S_HI',
                    'V_LO', 'V_HI']

    blur_k_name = 'BLUR \'K\''

    max_vals = [179, 179, 255, 255, 255, 255]

    for thresh, val, max_val in zip(thresh_names,
                                    thresholds,
                                    max_vals):
        cv2.createTrackbar(thresh, win, val, max_val, empty_callback)

    cv2.createTrackbar(blur_k_name, win,
                       cf['blur_k']['initial'],
                       cf['blur_k']['max'],
                       empty_callback)
    cv2.setTrackbarMin(blur_k_name, win, 1)

    thresh_vals = None
    keypress = -1

    while keypress == -1:
        __, frame = vid_feed.read()

        # blur frame
        blur_k = cv2.getTrackbarPos(blur_k_name, win)
        frame_blur = cv2.blur(frame, (blur_k, blur_k))

        frame_hsv = cv2.cvtColor(frame_blur, cv2.COLOR_BGR2HSV)

        thresh_vals = np.asarray([cv2.getTrackbarPos(name, win)
                                  for name in thresh_names])

        frame_thresh = cv2.inRange(frame_hsv,
                                   thresh_vals[::2],
                                   thresh_vals[1::2])

        # cv2.imshow(win_thresh, frame_thresh)
        cv2.imshow(win, frame_thresh)

        keypress = cv2.waitKey(5)

    cv2.destroyWindow(win)
    vid_feed.release()
    return thresh_vals, keypress
Exemplo n.º 4
0
def quitarFondo():
    cap = cv2.imread(
        r'/home/juan-rios/Documentos/python/trackMove/original/foto.png', 1)
    newImg = cv2.resize(cap, (550, 350))
    print(cap.shape)
    panel = np.zeros([650, 1120], np.uint8)
    cv2.namedWindow('panel')

    def nothing(x):
        pass

    cv2.createTrackbar('L - h', 'panel', 0, 179, nothing)
    cv2.createTrackbar('U - h', 'panel', 179, 179, nothing)
    cv2.createTrackbar('L - s', 'panel', 0, 255, nothing)
    cv2.createTrackbar('U - s', 'panel', 255, 255, nothing)
    cv2.createTrackbar('L - v', 'panel', 0, 255, nothing)
    cv2.createTrackbar('U - v', 'panel', 255, 255, nothing)
    cv2.createTrackbar('S ROWS', 'panel', 0, 480, nothing)
    cv2.createTrackbar('E ROWS', 'panel', 480, 480, nothing)
    cv2.createTrackbar('S COL', 'panel', 0, 640, nothing)
    cv2.createTrackbar('E COL', 'panel', 640, 640, nothing)
    while True:

        frame = newImg[0:650, 0:1120]
        s_r = cv2.getTrackbarPos('S ROWS', 'panel')
        e_r = cv2.getTrackbarPos('E ROWS', 'panel')
        s_c = cv2.getTrackbarPos('S COL', 'panel')
        e_c = cv2.getTrackbarPos('E COL', 'panel')
        roi = frame[s_r:e_r, s_c:e_c]
        hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
        l_h = cv2.getTrackbarPos('L - h', 'panel')
        u_h = cv2.getTrackbarPos('U - h', 'panel')
        l_s = cv2.getTrackbarPos('L - s', 'panel')
        u_s = cv2.getTrackbarPos('U - s', 'panel')
        l_v = cv2.getTrackbarPos('L - v', 'panel')
        u_v = cv2.getTrackbarPos('U - v', 'panel')
        lower_green = np.array([l_h, l_s, l_v])
        upper_green = np.array([u_h, u_s, u_v])
        mask = cv2.inRange(hsv, lower_green, upper_green)
        mask_inv = cv2.bitwise_not(mask)
        bg = cv2.bitwise_and(roi, roi, mask=mask)
        fg = cv2.bitwise_and(roi, roi, mask=mask_inv)
        cv2.imshow('filtro', bg)
        cv2.imshow('camara', fg)
        #cv2.imshow('panel', panel)
        cv2.imwrite(
            r'/home/juan-rios/Documentos/python/trackMove/sin_fondo/foto_sin_fondo.png',
            fg)
        k = cv2.waitKey(30) & 0xFF
        if k == 27:
            break
    cv2.destroyAllWindows()
Exemplo n.º 5
0
def val_trackbars():
    thresh_val = cv.getTrackbarPos('thresh_val', "Adaptive Threshold")
    adapt_val = cv.getTrackbarPos('adapt_val', "Adaptive Threshold")
    high_threshold = cv.getTrackbarPos("high_threshold", "Adaptive Threshold")
    block_size = cv.getTrackbarPos("block_size", "Adaptive Threshold")
    if block_size < 3:
        block_size = 3
    if block_size % 2 == 0:
        block_size += 1
    sub_const = cv.getTrackbarPos("sub_const", "Adaptive Threshold")
    src = [high_threshold, thresh_val_list[thresh_val], adaptive_thresh_val_list[adapt_val],
           block_size, sub_const]
    return src
Exemplo n.º 6
0
def gammaDisplay(img_path: str, rep: int):
    """
    GUI for gamma correction
    :param img_path: Path to the image
    :param rep: grayscale(1) or RGB(2)
    :return: None
    """

    img = cv2.imread(img_path, rep - 1)
    cv2.namedWindow('Gamma Correction')
    cv2.createTrackbar('Gamma', 'Gamma Correction', 1, 200, gamma)
    img = np.asarray(img) / 255

    cv2.imshow('Gamma correction', img)
    k = cv2.waitKey(1)

    new_gamma_img = img

    while 1:
        cv2.imshow('Gamma correction', new_gamma_img)
        k = cv2.waitKey(1) & 0xFF
        if k == 27:
            break
        g = cv2.getTrackbarPos('Gamma', 'Gamma correction')
        print(g / 100)
        new_gamma_img = np.power(img, g / 100)

    cv2.destroyAllWindows()
    pass
Exemplo n.º 7
0
 def erosion(val):
     erosion_size = cv2.getTrackbarPos(title_trackbar_kernel_size,
                                       title_erosion_window)
     erosion_type = 0
     val_type = cv2.getTrackbarPos(title_trackbar_element_type,
                                   title_erosion_window)
     if val_type == 0:
         erosion_type = cv2.MORPH_RECT
     elif val_type == 1:
         erosion_type = cv2.MORPH_CROSS
     elif val_type == 2:
         erosion_type = cv2.MORPH_ELLIPSE
     element = cv2.getStructuringElement(
         erosion_type, (2 * erosion_size + 1, 2 * erosion_size + 1),
         (erosion_size, erosion_size))
     erosion_dst = cv2.erode(src, element, iterations=iterations)
     cv2.imshow(title_erosion_window, erosion_dst)
Exemplo n.º 8
0
 def dilatation(val):
     dilatation_size = cv2.getTrackbarPos(title_trackbar_kernel_size,
                                          title_dilatation_window)
     dilatation_type = 0
     val_type = cv2.getTrackbarPos(title_trackbar_element_type,
                                   title_dilatation_window)
     if val_type == 0:
         dilatation_type = cv2.MORPH_RECT
     elif val_type == 1:
         dilatation_type = cv2.MORPH_CROSS
     elif val_type == 2:
         dilatation_type = cv2.MORPH_ELLIPSE
     element = cv2.getStructuringElement(
         dilatation_type,
         (2 * dilatation_size + 1, 2 * dilatation_size + 1),
         (dilatation_size, dilatation_size))
     dilatation_dst = cv2.dilate(src, element, iterations=iterations)
     cv2.imshow(title_dilatation_window, dilatation_dst)
Exemplo n.º 9
0
    def get_trackbar_values(self):
        h_min = cv2.getTrackbarPos(f"HUE Min_{self.num}", f"HSV_{self.num}")
        h_max = cv2.getTrackbarPos(f"HUE Max_{self.num}", f"HSV_{self.num}")
        s_min = cv2.getTrackbarPos(f"SAT Min_{self.num}", f"HSV_{self.num}")
        s_max = cv2.getTrackbarPos(f"SAT Max_{self.num}", f"HSV_{self.num}")
        v_min = cv2.getTrackbarPos(f"VALUE Min_{self.num}", f"HSV_{self.num}")
        v_max = cv2.getTrackbarPos(f"VALUE Max_{self.num}", f"HSV_{self.num}")

        threshold1 = cv2.getTrackbarPos(f"Threshold1_{self.num}",
                                        f"Parameters_{self.num}")
        threshold2 = cv2.getTrackbarPos(f"Threshold2_{self.num}",
                                        f"Parameters_{self.num}")
        area_min = cv2.getTrackbarPos(f"Area_{self.num}",
                                      f"Parameters_{self.num}")

        return h_min, h_max, s_min, s_max, v_min, v_max, threshold1, threshold2, area_min
Exemplo n.º 10
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()
Exemplo n.º 11
0
def onthreshold(x):
    value = cv2.getTrackbarPos("value", "Threshold")
    a, binary = cv2.threshold(gauss, value, maxvalue, cv2.THRESH_BINARY)
    b, binary_inv = cv2.threshold(gauss, value, maxvalue,
                                  cv2.THRESH_BINARY_INV)
    c, trunc = cv2.threshold(gauss, value, maxvalue, cv2.THRESH_TRUNC)
    d, to_zero = cv2.threshold(gauss, value, maxvalue, cv2.THRESH_TOZERO)
    e, to_zero_inv = cv2.threshold(gauss, value, maxvalue,
                                   cv2.THRESH_TOZERO_INV)
    if (a):
        cv2.imshow("Binary", binary)
Exemplo n.º 12
0
def detectColor():
    def empty(a):
        pass

    cv2.namedWindow("TrackBars")
    cv2.resizeWindow("TrackBars", 640, 240)
    cv2.createTrackbar("Hue Min", "TrackBars", 0, 179, empty)
    cv2.createTrackbar("Sat Min", "TrackBars", 0, 255, empty)
    cv2.createTrackbar("Val Min", "TrackBars", 0, 255, empty)
    cv2.createTrackbar("Hue Max", "TrackBars", 179, 179, empty)
    cv2.createTrackbar("Sat Max", "TrackBars", 255, 255, empty)
    cv2.createTrackbar("Val Max", "TrackBars", 255, 255, empty)

    while True:
        img = cv2.imread("./lambo.jpeg")
        imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        h_min = cv2.getTrackbarPos("Hue Min", "TrackBars")
        h_max = cv2.getTrackbarPos("Hue Max", "TrackBars")
        s_min = cv2.getTrackbarPos("Sat  Min", "TrackBars")
        s_max = cv2.getTrackbarPos("Sat Max", "TrackBars")
        v_min = cv2.getTrackbarPos("Val Min", "TrackBars")
        v_max = cv2.getTrackbarPos("Val Max", "TrackBars")
        #print(v_min)
        # lower1 = np.array([h_min, s_min, v_min])
        # upper1 = np.array([h_max, s_max, v_max])
        lower = np.array([000, 000, 186])
        upper = np.array([179, 255, 255])
        mask = cv2.inRange(imgHSV, lower, upper)
        imgResult = cv2.bitwise_and(img, img, mask=mask)

        cv2.imshow("Original", img)
        cv2.imshow("HSV", imgHSV)
        cv2.imshow("Mask", mask)
        cv2.imshow("Result", imgResult)
        cv2.waitKey(0)
Exemplo n.º 13
0
def clahe_tune(img):
    """
    Apply CLACHE algorithm to image with trackbars to tune
    :param img: Input image of RGB format
    :output: filtered image
    """
    res = []
    tg = cv2.getTrackbarPos("tg", "track") + 1
    clahe = cv2.createCLAHE(clipLimit=cv2.getTrackbarPos("clip", "track"),
                            tileGridSize=(tg, tg))
    for channel in np.dsplit(img, img.shape[-1]):
        res.append(clahe.apply(channel))
    res = np.dstack(res)

    k = 2 * cv2.getTrackbarPos("kernel", "track") - 1
    t = cv2.getTrackbarPos("t", "track")

    res = cv2.GaussianBlur(res, (k, k), 0)  # Apply filter
    res = cv2.bilateralFilter(res, t, 75, 75)

    cv2.imshow("result", res)
    return res
Exemplo n.º 14
0
    def getTrackBarPos(self):
        h_min = cv2.getTrackbarPos("Hue min", "trackBars")
        h_max = cv2.getTrackbarPos("Hue max", "trackBars")
        s_min = cv2.getTrackbarPos("Sat min", "trackBars")
        s_max = cv2.getTrackbarPos("Sat max", "trackBars")
        v_min = cv2.getTrackbarPos("Value min", "trackBars")
        v_max = cv2.getTrackbarPos("Value max", "trackBars")

        return h_min, h_max, s_min, s_max, v_min, v_max
Exemplo n.º 15
0
def adjust_circle(image, circle):
    """Manually adjust a circle on an image.  Takes an input image and
    circle(center, radius) and shows a blown up region centered around the
    circle.  Allows the user to adjust the circle using trackbars.  Waits
    for keypress to finish.  Returns adjusted circle and keypress."""

    # initialize window and trackbars
    win = 'Adjust Target Circle'
    cv2.namedWindow(win)
    cv2.resizeWindow(win, 200, 200)

    # initialize variables
    roi, roi_origin = get_circle_roi(image, circle)

    circle_local = np.copy(circle)
    circle_local[0] = circle[0] - np.flipud(roi_origin)

    # scale image to be bigger and allow for easier adjustment
    scale = cf['roi']['ADJUST_SCALE']
    roi = scale_image(roi, scale)
    circle_local = np.multiply(circle_local, scale)

    img_circ = np.copy(roi)
    # Set max radius of circle such that the max diameter is the length
    # of the region of interest
    max_radius = roi.shape[0] // 2

    # initialize trackbars
    cv2.createTrackbar('x', win,
                       circle_local[0][0], roi.shape[1], empty_callback)
    cv2.createTrackbar('y', win,
                       circle_local[0][1], roi.shape[0], empty_callback)
    cv2.createTrackbar('r', win,
                       circle_local[1], max_radius, empty_callback)

    keypress = -1

    while keypress == -1:
        cv2.circle(img_circ,
                   (cv2.getTrackbarPos('x', win),
                    cv2.getTrackbarPos('y', win)),
                   cv2.getTrackbarPos('r', win),
                   (0, 0, 0),
                   1)
        cv2.imshow(win, img_circ)
        img_circ = np.copy(roi)
        keypress = cv2.waitKey(5)

    adj_circle = ((cv2.getTrackbarPos('x', win) // scale +
                   roi_origin[1],
                   cv2.getTrackbarPos('y', win) // scale +
                   roi_origin[0]),
                  cv2.getTrackbarPos('r', win) // scale)

    cv2.destroyWindow(win)
    return adj_circle, keypress
def draw_circle(event, x, y, flags, param):
    r = cv2.getTrackbarPos('R', 'image')
    g = cv2.getTrackbarPos('G', 'image')
    b = cv2.getTrackbarPos('B', 'image')
    color = (b, g, r)
    global ix, iy, drawing, mode
    # 当按下左键是返回起始位置坐标
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y
    # 当鼠标左键按下并移动是绘制图形。event 可以查看移动,flag 查看是否按下
    elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
        if drawing == True:
            if mode == True:
                cv2.rectangle(img, (ix, iy), (x, y), color, -1)
            else:
                # 绘制圆圈,小圆点连在一起就成了线,3 代表了笔画的粗细
                cv2.circle(img, (x, y), 3, color, -1)
                # 下面注释掉的代码是起始点为圆心,起点到终点为半径的
                # r=int(np.sqrt((x-ix)**2+(y-iy)**2))
                # cv2.circle(img,(x,y),r,(0,0,255),-1)
                # 当鼠标松开停止绘画。
    elif event == cv2.EVENT_LBUTTONUP:
        drawing == False
Exemplo n.º 17
0
def gammaDisplay(img_path: str, rep: int):
    """
    GUI for gamma correction
    Will track nar to change the gamma rate in an image
    The gamma will be set as:
    s=cr^Gamma
    The track bar will be [0-2] in rational numbers.
    :param img_path: Path to the image
    :param rep: grayscale(1) or RGB(2)
    :return: None
    """

    # Reads the image
    img = cv2.imread(img_path, rep - 1)

    # Create the window
    cv2.namedWindow('Gamma correction')
    # Create the taskbar
    cv2.createTrackbar('Gamma', 'Gamma correction', 1, 200, gamma)
    # Normalize the img
    img = np.asarray(img) / 255

    # Shows the image
    cv2.imshow('Gamma correction', img)
    k = cv2.waitKey(1)

    newim = img

    # Infinite loop until you press esc
    while 1:
        cv2.imshow('Gamma correction', newim)
        # Set a key that will stop the loop
        k = cv2.waitKey(1) & 0xFF
        if k == 27:
            break
        # Get the number from the taskbar
        g = cv2.getTrackbarPos('Gamma', 'Gamma correction')
        # Calculate the new image
        newim = np.power(img, g / 100)

    cv2.destroyAllWindows()

    pass
Exemplo n.º 18
0
    def getColors(self):
        # default run will be for skin-hues, but user will be able to play around.
        h_min = cv2.getTrackbarPos(self.trackbar_name[0], self.winname)
        h_max = cv2.getTrackbarPos(self.trackbar_name[1], self.winname)
        s_min = cv2.getTrackbarPos(self.trackbar_name[2], self.winname)
        s_max = cv2.getTrackbarPos(self.trackbar_name[3], self.winname)
        v_min = cv2.getTrackbarPos(self.trackbar_name[4], self.winname)
        v_max = cv2.getTrackbarPos(self.trackbar_name[5], self.winname)

        hsvarr = np.array([h_min, h_max, s_min, s_max, v_min, v_max])
        hsvarr1 = np.uint8([[[(h_min + h_max) / 2, (s_min + s_max) / 2,
                              (v_min + v_max) / 2]]])
        bgrarr = cv2.cvtColor(hsvarr1, cv2.COLOR_HSV2BGR)
        return bgrarr, hsvarr
Exemplo n.º 19
0
def findColor(
):  #Finds the color of an object by user varying slider to mask out object
    def empty(a):
        pass

    frameWidth = 640
    frameHeight = 480

    cap = cv2.VideoCapture(0)
    cap.set(3, frameWidth)
    cap.set(4, frameHeight)
    cap.set(10, 150)

    cv2.namedWindow("HSV")
    cv2.resizeWindow("HSV", 640, 240)
    cv2.createTrackbar("Hue Min", "HSV", 0, 179, empty)
    cv2.createTrackbar("Sat Min", "HSV", 0, 255, empty)
    cv2.createTrackbar("Val Min", "HSV", 0, 255, empty)
    cv2.createTrackbar("Hue Max", "HSV", 179, 179, empty)
    cv2.createTrackbar("Sat Max", "HSV", 255, 255, empty)
    cv2.createTrackbar("Val Max", "HSV", 255, 255, empty)

    while True:
        _, img = cap.read()
        imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        h_min = cv2.getTrackbarPos("Hue Min", "HSV")
        h_max = cv2.getTrackbarPos("Hue Max", "HSV")
        s_min = cv2.getTrackbarPos("Sat  Min", "HSV")
        s_max = cv2.getTrackbarPos("Sat Max", "HSV")
        v_min = cv2.getTrackbarPos("Val Min", "HSV")
        v_max = cv2.getTrackbarPos("Val Max", "HSV")
        #print(v_min)
        lower = np.array([h_min, s_min, v_min])
        upper = np.array([h_max, s_max, v_max])
        mask = cv2.inRange(imgHSV, lower, upper)
        result = cv2.bitwise_and(img, img, mask=mask)

        mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)

        cv2.imshow("Original", img)
        cv2.imshow("Mask", mask)
        cv2.imshow("Result", result)

        if cv2.waitKey(1) & 11111111 == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()
Exemplo n.º 20
0
def detect_color(path):
    # add track bar
    def empty(x):
        pass

    cv2.namedWindow('TrackBar')
    cv2.resizeWindow('TrackBar', 640, 240)
    cv2.createTrackbar('Hue min', 'TrackBar', 0, 179, empty)
    cv2.createTrackbar('Hue max', 'TrackBar', 179, 179, empty)
    cv2.createTrackbar('Saturation min', 'TrackBar', 0, 255, empty)
    cv2.createTrackbar('Saturation max', 'TrackBar', 255, 255, empty)
    cv2.createTrackbar('Val min', 'TrackBar', 0, 255, empty)
    cv2.createTrackbar('Val max', 'TrackBar', 255, 255, empty)

    while True:
        img = cv2.imread(path)
        imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

        # get the values from track bar
        h_min = cv2.getTrackbarPos('Hue min', 'TrackBar')
        h_max = cv2.getTrackbarPos('Hue max', 'TrackBar')
        s_min = cv2.getTrackbarPos('Saturation min', 'TrackBar')
        s_max = cv2.getTrackbarPos('Saturation max', 'TrackBar')
        v_min = cv2.getTrackbarPos('Val min', 'TrackBar')
        v_max = cv2.getTrackbarPos('Val max', 'TrackBar')

        lower = np.array([h_min, s_min, v_min])
        upper = np.array([h_max, s_max, v_max])
        mask = cv2.inRange(imgHSV, lower, upper)

        imgMasked = cv2.bitwise_and(img, img, mask=mask)

        # cv2.imshow('Original image', img)
        # cv2.imshow('HSV image', imgHSV)
        # cv2.imshow('Mask image', mask)
        # cv2.imshow('Masked image', imgMasked)

        imgStack = stackImages(0.6, ([img, imgHSV], [mask, imgMasked]))
        cv2.imshow('Stacked Images', imgStack)

        cv2.waitKey(1)
Exemplo n.º 21
0
    def stereo_bm(self):
        Left_Stereo_Map = (config.left_map1, config.left_map2)
        Right_Stereo_Map = (config.right_map1, config.right_map2)
        cv.namedWindow("Test Two Camera")
        cv.namedWindow('depth')
        cv.createTrackbar("numDisparities", "depth", 9, 100, lambda x: None)
        cv.createTrackbar("filterCap", "depth", 62, 63, lambda x: None)
        cv.createTrackbar("filterSize", "depth", 255, 255, lambda x: None)
        cv.createTrackbar("SADWindowSize", "depth", 0, 255, lambda x: None)
        leftCam = cv.VideoCapture(self.left_camera_id + cv.CAP_DSHOW)
        rightCam = cv.VideoCapture(self.right_camera_id + cv.CAP_DSHOW)

        leftCam.set(cv.CAP_PROP_FRAME_HEIGHT, self.frameHeight)
        leftCam.set(cv.CAP_PROP_FRAME_WIDTH, self.frameWidth)
        rightCam.set(cv.CAP_PROP_FRAME_HEIGHT, self.frameHeight)
        rightCam.set(cv.CAP_PROP_FRAME_WIDTH, self.frameWidth)
        if not (leftCam.isOpened() and rightCam.isOpened()):
            exit(1)
        while True:
            # Start Reading Camera images
            retvalOfRight, rightFrame = rightCam.read()
            retvalOfLeft, leftFrame = leftCam.read()
            # ret, frame = capture.read()
            if not (retvalOfRight and retvalOfLeft):
                print("read fail")
                break
            key = cv.waitKey(1)
            twoFrame = cv.hconcat([rightFrame, leftFrame])
            cv.imshow("Test Two Camera", twoFrame)
            if key & 0xFF == ord('q'):
                print("結束")
                break
            # elif key & 0xFF == ord('s'):
            elif 1 == 1:
                frameL = leftFrame
                frameR = rightFrame
            else:
                continue
            cv.imshow("left", frameL)
            cv.imshow("right", frameR)

            Left_nice = cv.remap(frameL, Left_Stereo_Map[0],
                                 Left_Stereo_Map[1], cv.INTER_LANCZOS4,
                                 cv.BORDER_CONSTANT, 0)
            Right_nice = cv.remap(frameR, Right_Stereo_Map[0],
                                  Right_Stereo_Map[1], cv.INTER_LANCZOS4,
                                  cv.BORDER_CONSTANT, 0)

            grayR = cv.cvtColor(Right_nice, cv.COLOR_BGR2GRAY)
            grayL = cv.cvtColor(Left_nice, cv.COLOR_BGR2GRAY)
            numDisparities = cv.getTrackbarPos("numDisparities", "depth")
            filterCap = cv.getTrackbarPos("filterCap", "depth")
            filterSize = cv.getTrackbarPos("filterSize", "depth")
            if filterSize % 2 == 0:
                filterSize += 1
            if filterSize < 5:
                filterSize = 5
            if filterCap < 1:
                filterCap = 1
            SADWindowSize = cv.getTrackbarPos("SADWindowSize", "depth")
            if SADWindowSize % 2 == 0:
                SADWindowSize += 1
            if SADWindowSize < 5:
                SADWindowSize = 5

            stereo = cv.StereoBM_create(numDisparities=16 * numDisparities,
                                        blockSize=SADWindowSize)
            stereo.setPreFilterCap(filterCap)
            stereo.setPreFilterSize(filterSize)
            disparity = stereo.compute(grayL, grayR)
            disparity.astype(np.float32) / 16
            disp = cv.normalize(disparity,
                                disparity,
                                alpha=255,
                                beta=1,
                                norm_type=cv.NORM_MINMAX,
                                dtype=cv.CV_8UC1)
            cv.imshow("depth", disp)
Exemplo n.º 22
0
cv2.namedWindow("Tracking")
cv2.createTrackbar("LH", "Tracking", 0, 255, nothing)
cv2.createTrackbar("LS", "Tracking", 0, 255, nothing)
cv2.createTrackbar("LV", "Tracking", 0, 255, nothing)

cv2.createTrackbar("UH", "Tracking", 255, 255, nothing)
cv2.createTrackbar("US", "Tracking", 255, 255, nothing)
cv2.createTrackbar("UV", "Tracking", 255, 255, nothing)

while True:
    ret, frame = cap.read()

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # Pega a posição e o valor de cada trackbar
    l_h = cv2.getTrackbarPos("LH", "Tracking")
    l_s = cv2.getTrackbarPos("LS", "Tracking")
    l_v = cv2.getTrackbarPos("LV", "Tracking")

    u_h = cv2.getTrackbarPos("UH", "Tracking")
    u_s = cv2.getTrackbarPos("US", "Tracking")
    u_v = cv2.getTrackbarPos("UV", "Tracking")

    l_b = np.array([l_h, l_s, l_v])
    u_b = np.array([u_h, u_s, u_v])

    mask = cv2.inRange(hsv, l_b, u_b)

    res = cv2.bitwise_and(frame, frame, mask=mask)

    if ret == True:
Exemplo n.º 23
0
img = cv2.imread("Resources/lambo.png")
imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

window = cv2.namedWindow("Trackbars")
cv2.resizeWindow("Trackbars", 512, 512)
cv2.createTrackbar("Hue Min", "Trackbars", 0, 179, lambda x: x)
cv2.createTrackbar("Hue Max", "Trackbars", 24, 179, lambda x: x)
cv2.createTrackbar("Sat Min", "Trackbars", 88, 255, lambda x: x)
cv2.createTrackbar("Sat Max", "Trackbars", 255, 255, lambda x: x)
cv2.createTrackbar("Val Min", "Trackbars", 137, 255, lambda x: x)
cv2.createTrackbar("Val Max", "Trackbars", 255, 255, lambda x: x)

while True:
    mins = np.array([
        cv2.getTrackbarPos("Hue Min", "Trackbars"),
        cv2.getTrackbarPos("Sat Min", "Trackbars"),
        cv2.getTrackbarPos("Val Min", "Trackbars")
    ],
                    dtype=np.uint8)

    maxes = np.array([
        cv2.getTrackbarPos("Hue Max", "Trackbars"),
        cv2.getTrackbarPos("Sat Max", "Trackbars"),
        cv2.getTrackbarPos("Val Max", "Trackbars")
    ],
                     dtype=np.uint8)
    mask = cv2.inRange(imgHSV, mins, maxes)
    result = cv2.bitwise_and(img, img, mask=mask)
    cv2.imshow("HSV", result)
    cv2.waitKey(1)
Exemplo n.º 24
0
import cv2.cv2 as cv


def some_func(x):
    pass


cv.namedWindow("Canny edge detection")

img = cv.imread("imgs/messi5.jpg", 0)
cv.createTrackbar("th1", "Canny edge detection", 0, 255, some_func)
cv.createTrackbar("th2", "Canny edge detection", 0, 255, some_func)
while True:
    th1 = cv.getTrackbarPos("th1", "Canny edge detection")
    th2 = cv.getTrackbarPos("th2", "Canny edge detection")

    canny = cv.Canny(img, th1, th2)

    cv.imshow("Canny edge detection", canny)
    if cv.waitKey(1) == ord(' '):
        break

    canny = cv.Canny(img, th1, th2)

cv.destroyAllWindows()
Exemplo n.º 25
0
cv2.createTrackbar("Val Max", "TrackBars",255,255,empty)





livecap = cv2.VideoCapture(0)
livecap.set(3, 600)                      # 3 represents height here
livecap.set(4, 400)                      # 4 represents width here
livecap.set(10, 1000)                    # 10 represents brightnes           


while True:
    success, img = livecap.read()
    imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    h_min = cv2.getTrackbarPos("Hue Min", "TrackBars")
    h_max = cv2.getTrackbarPos("Hue Max", "TrackBars")
    s_min = cv2.getTrackbarPos("Sat Min", "TrackBars")
    s_max = cv2.getTrackbarPos("Sat Max", "TrackBars")
    v_min = cv2.getTrackbarPos("Val Min", "TrackBars")
    v_max = cv2.getTrackbarPos("Val Max", "TrackBars")
    print(h_min,h_max,s_min,s_max,v_min,v_max)
    lower = np.array([h_min,s_min,v_min])
    upper = np.array([h_max,s_max,v_max])
    mask = cv2.inRange(imgHSV,lower,upper)                             #creating a mask image
    imgResult = cv2.bitwise_and(img,img,mask=mask)                      #imposing mask on original image
    imgStack = stackImages(0.4,([img,imgHSV],[mask,imgResult]))
    
    cv2.imshow("stacked images", imgStack)
    #cv2.imshow("img", img)
    #cv2.imshow("imgHSV", imgHSV)
Exemplo n.º 26
0
line_point_1_b = (int(Maxpoint_1[1][0]), int(Maxpoint_1[1][1]))
line_point_2_a = (int(Maxpoint_2[0][0]), int(Maxpoint_2[0][1]))
line_point_2_b = (int(Maxpoint_2[1][0]), int(Maxpoint_2[1][1]))
# 画出直线
cv.line(img, line_point_1_a, line_point_1_b, (0, 0, 255), 2)
cv.line(img, line_point_2_a, line_point_2_b, (0, 255, 0), 2)

cv.namedWindow('template')
cv.createTrackbar('Canny_thresh1', 'template', 41, 255, nothing)
cv.createTrackbar('Canny_thresh2', 'template', 237, 255, nothing)
# cv.createTrackbar('thresh', 'template', 100, 255, nothing)
# cv.createTrackbar('minLine', 'template', 5, 50, nothing)
# cv.createTrackbar('maxlineGap', 'template', 1, 50, nothing)

while True:
    lower = cv.getTrackbarPos('Canny_thresh1', 'template')
    upper = cv.getTrackbarPos('Canny_thresh2', 'template')
    edges = cv.Canny(img_gray, lower, upper, apertureSize=3)
    # thresh = cv.getTrackbarPos('thresh', 'template')
    # minLineLength = cv.getTrackbarPos('minLine', 'template')
    # maxLineGap = cv.getTrackbarPos('maxlineGap', 'template')
    thresh = 100
    minLineLength = 5
    maxLineGap = 1
    lines = cv.HoughLinesP(
        edges,
        1,
        np.pi / 180,
        thresh,  # 第二第三参数都为精确度
        minLineLength,
        maxLineGap)
Exemplo n.º 27
0
    onchange_fxn)  # Trackbar to change the values for Blue channel
cv2.createTrackbar(
    'Green_Channel', 'Trackbar_Window', 0, 255,
    onchange_fxn)  # Trackbar to change the values for Green channel
cv2.createTrackbar(
    'Red_Channel', 'Trackbar_Window', 0, 255,
    onchange_fxn)  # Trackbar to change the values for Red channel

# Creating a switch
switch_name = "Switch-\n 0: ON \n 1: OFF "
cv2.createTrackbar(switch_name, 'Trackbar_Window', 0, 1, onchange_fxn)

while (1):  # Whenever using while loop always place image inside the loop
    img = np.zeros((400, 600, 3), np.uint8)
    # Getting the positions of the Trackbars
    b = cv2.getTrackbarPos('Blue_Channel', 'Trackbar_Window')
    g = cv2.getTrackbarPos('Green_Channel', 'Trackbar_Window')
    r = cv2.getTrackbarPos('Red_Channel', 'Trackbar_Window')

    # # Getting the positions of the switch Trackbar
    s = cv2.getTrackbarPos(switch_name, 'Trackbar_Window')

    if s == 1:  # Checking if the switch is ON
        img[:] = [b, g,
                  r]  # Changing the Blue, Greem and Red channels of the image
    else:
        img[:] = 0  # 0 means no change in the BGR channels of the image

    cv2.imshow('Trackbar_Window', img)

    if cv2.waitKey(1) == 27:
Exemplo n.º 28
0
    pass


img = cv.imread('timg.jpg', cv.IMREAD_GRAYSCALE)
# v1 = cv.Canny(img, 80, 150)
# v2 = cv.Canny(img, 50, 100)
# res = np.hstack((v1, v2))
# cv_show('res', res)


cv.namedWindow('window')
cv.createTrackbar('bar_low', 'window', 0, 255, nothing)
cv.createTrackbar('bar_up', 'window', 0, 255, nothing)

while (True):
    low = cv.getTrackbarPos('bar_low', 'window')
    up=cv.getTrackbarPos('bar_up','window')
    res = cv.Canny(img, low, up)
    cv.imshow('window', res)
    key = cv.waitKey(10)
    if key == 27:
        break








Exemplo n.º 29
0
cv2.createTrackbar('Hue Max', 'TrackBars', 19, 179, empty_fn)
cv2.createTrackbar('Sat Min', 'TrackBars', 110, 255, empty_fn)
cv2.createTrackbar('Sat Max', 'TrackBars', 240, 255, empty_fn)
cv2.createTrackbar('Val Min', 'TrackBars', 153, 255, empty_fn)
cv2.createTrackbar('Val Max', 'TrackBars', 255, 255, empty_fn)

while True:
    # Read image file from path
    path = 'Resources/lambo.png'
    img = cv2.imread(path)

    # convert image to HSV
    imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    # Get the value from the trackbar
    hue_min = cv2.getTrackbarPos('Hue Min', 'TrackBars')
    hue_max = cv2.getTrackbarPos('Hue Max', 'TrackBars')
    sat_min = cv2.getTrackbarPos('Sat Min', 'TrackBars')
    sat_max = cv2.getTrackbarPos('Sat Max', 'TrackBars')
    val_min = cv2.getTrackbarPos('Val Min', 'TrackBars')
    val_max = cv2.getTrackbarPos('Val Max', 'TrackBars')

    lower = np.array([hue_min, sat_min, val_min])
    upper = np.array([hue_max, sat_max, val_max])

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

    imgResult = cv2.bitwise_and(img, img, mask=mask)

    #cv2.imshow('Original Image', img)
    #cv2.imshow('HSV Image', imgHSV)
Exemplo n.º 30
0
cv2.namedWindow('Paint', cv2.WINDOW_AUTOSIZE)


# Loading the default webcam of PC.
cap = cv2.VideoCapture(0)

# Keep looping
while True:
    # Reading the frame from the camera
    ret, frame = cap.read()
    #Flipping the frame to see same side of yours
    frame = cv2.flip(frame, 1)
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)


    u_hue = cv2.getTrackbarPos("Upper Hue", "Color detectors")
    u_saturation = cv2.getTrackbarPos("Upper Saturation", "Color detectors")
    u_value = cv2.getTrackbarPos("Upper Value", "Color detectors")
    l_hue = cv2.getTrackbarPos("Lower Hue", "Color detectors")
    l_saturation = cv2.getTrackbarPos("Lower Saturation", "Color detectors")
    l_value = cv2.getTrackbarPos("Lower Value", "Color detectors")
    Upper_hsv = np.array([u_hue,u_saturation,u_value])
    Lower_hsv = np.array([l_hue,l_saturation,l_value])


    # Adding the colour buttons to the live frame for colour access
    frame = cv2.rectangle(frame, (40,1), (140,65), (122,122,122), -1)
    frame = cv2.rectangle(frame, (160,1), (255,65), colors[0], -1)
    frame = cv2.rectangle(frame, (275,1), (370,65), colors[1], -1)
    frame = cv2.rectangle(frame, (390,1), (485,65), colors[2], -1)
    frame = cv2.rectangle(frame, (505,1), (600,65), colors[3], -1)