Samuel Kahessay Samuel Kahessay - 1 month ago 31
Python Question

Cropping live video feed in OpenCV

I have a live video feed that tracks green objects and draws a rectangle over the object's area. I'm curious as to how I would be able to crop the feed to only show the area that the rectangle encompasses.

Here's the section of relevance:

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)

Answer

What you might be looking for is to create a 'Region of Interest(ROI)' using OpenCV Python.

You can do so in your code as shown:

(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]

Note that (x,y) corresponds to the top-left point of your rectangle. The area inside the rect declared above has been stored in Mat roi.

Comments