Ask Your Question

Revision history [back]

Opencv can't show live webcam footage.What is wrong with my code ?

I want to display contour with live webcam feeding but it only show a frame.

code:

import cv2
import numpy
import math


windowName = "OBJECT_MOVEMENT"
cv2.namedWindow(windowName)

cap = cv2.VideoCapture(0)

if cap.isOpened():
ret, frame = cap.read()
else:
    ret = False
    print("False operation.")
while ret:
    ret, frame=cap.read()
    imgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(imgray,127,255,cv2.THRESH_BINARY)
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    finalIm = cv2.drawContours(frame, contours, -1, (0,255,0), 1)

    cnt = contours[0]
    M = cv2.moments(cnt)
    contours_sizes = [(cv2.contourArea(cnt), cnt) for cnt in contours]
    biggest_contour = max(contours_sizes, key=lambda x: x[0])[1]

    cX = int(((M["m10"])+1) / ((M["m00"])+1))
    cY = int(((M["m10"])+1) / ((M["m00"])+1))

    cv2.imshow("Countours",frame)
    if cv2.waitKey(0) == ord('q'):
        break
    cap.release()