在 OpenCV 中裁剪实时视频源

Cropping live video feed in OpenCV

我有一个实时视频源,可以跟踪绿色对象并在对象区域上绘制一个矩形。我很好奇我如何能够裁剪提要以仅显示矩形所包含的区域。

相关部分如下:

while True: 

    (success, frame) = webcam.read()

    frame = imutils.resize(frame, width = 1000)
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    mask = cv2.inRange(hsv, greenLower, greenUpper)
    mask = cv2.erode(mask, None, iterations=2)
    mask = cv2.dilate(mask, None, iterations=2)

    cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
    center = None

    if len(cnts) > 0:

        c = max(cnts, key=cv2.contourArea)
        ((x, y), radius) = cv2.minEnclosingCircle(c)
        M = cv2.moments(c)
        center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))

    for c in cnts:
        if cv2.contourArea(c) < 500:
            continue

        (x, y, w, h) = cv2.boundingRect(c)
        cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 2)

    pts = deque(maxlen = 32)
    pts.appendleft(center)

    for i in xrange(1, len(pts)):

        if pts[i - 1] is None or pts[i] is None:
            continue

        thickness = int(np.sqrt(args["buffer"] / float(i + 1)) * 2.5)
        cv2.line(frame, pts[i - 1], pts[i], (0, 255, 0), thickness)

    cv2.imshow("Presentation Tracker", frame)

您可能正在寻找的是使用 OpenCV Python.

创建一个 'Region of Interest(ROI)'

您可以在代码中这样做,如下所示:

(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 2)
roi = frame[y:y+h, x:x+w]

请注意,(x,y) 对应于矩形的左上角。 上面声明的rect里面的区域已经存储在Mat roi中了。