OpenCV找到红色轮廓的中间(Python)

时间:2017-04-29 12:45:20

标签: python opencv opencv-contour

我的想法是用颜色键控过滤我的身体。如果我穿红色T恤,我想找到带有轮廓的红色T恤的中心。这有什么好办法吗? 这是我的代码:

import numpy as np
import cv2
import imutils

cap = cv2.VideoCapture(0)

while True:

    # Take each frame
    _, frame = cap.read()

    frame = imutils.resize(frame, width = 400)

    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of red color in HSV
    lower_red = np.array([0,50,50])
    upper_red = np.array([10,255,255])

    lower_skin = np.array([0, 48, 80])
    upper_skin = np.array([20, 255, 255])
    skin_mask = cv2.inRange(hsv, lower_skin, upper_skin)

    # Threshold the HSV image to get only red colors
    red_mask = cv2.inRange(hsv, lower_red, upper_red)

    mask = red_mask + skin_mask


    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))
    mask = cv2.erode(mask, kernel, iterations = 2)
    mask = cv2.dilate(mask, kernel, iterations = 2)

    mask = cv2.GaussianBlur(mask, (3, 3), 0)
    skin = cv2.bitwise_and(frame, frame, mask = mask)

    gray = cv2.cvtColor(skin, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]

    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if imutils.is_cv2() else cnts[1]

    # # loop over the contours
    for c in cnts:     
        cv2.drawContours(skin, [c], -1, (0, 255, 0), 2)

    cv2.imshow("Image", skin)

    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

cv2.destroyAllWindows()

所以此刻我只画出T恤和皮肤的轮廓。但我想找到红色T恤轮廓的中心。这可能吗?我是否必须自己过滤红色并且不要将它添加到皮肤面膜?也许我目前的代码无法做到这一点,我很乐意提议! :)

1 个答案:

答案 0 :(得分:0)

使用红色面具和cv2.findContours查找T恤,并使用cv2.moments(contour) for cnt in contours: center_x = int(cnt['m10']/cnt['m00']) center_y = int(cnt['m01']/cnt['m00']) 中所述的(function() { debugger; function greet(who) { debugger; console.log("Hello " + who); } debugger; greet("Harry"); debugger; console.log("hi"); console.log("bye"); })(); 查找其中心:

.carousel{ margin-top:50px }