Drawing contours detected in image quickly turns into an all-black screen [closed]
Hi, I've been reading tutorials and I'm trying to detect rectangles from my webcam using OpenCV.
When I run this code, I see white specs on parts of the screen for a few frames. These white areas flicker in a familiar pattern to what I've seen image recognition do. Within 2 seconds the screen is entirely black.
Why is this happening? I'm trying to detect rectangles on the screen. Thanks!
import numpy as np
import cv2
import copy
cap = cv2.VideoCapture(0)
while(True):
ret, img = cap.read()
clone = copy.copy(img)
gray_image = cv2.cvtColor(clone, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray_image,127,255,1)
# contours,h = cv2.findContours(thresh,1,2)
contours, h = cv2.findContours(thresh,1,2)
for cnt in contours:
approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
print len(approx)
if len(approx)==4:
cv2.drawContours(img,[cnt],0,(0,0,255, 1),-1)
# Display the resulting frame
cv2.imshow('frame', img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
now I am seeing red flickering -- but when I hold up a solid colored object (a pink yoga block in front of a white mat) it does not show.
where is your code?
Just guessing: you're rendering the same
Matused for detecting contours.findContours()eats your input image, so if you want to use it later, make a copy (clone())As I said (and docs say http://docs.opencv.org/master/d3/dc0/...) input image of findContours is modified by the function
@Lorena I am searching for the Python example of clone. You are saying the object returned from the .read is a
Mat, is that the same asOutputArray?Sorry, comment made before pointing out you were using Python. Your code should work now, as you're finding contours of the grayscaled
retand showing originalimg. You'd better threshold before finding contours, as in examples. Is your problem solved?Nope, I see "src is not a numerical tuple" when I run
img = cap.read() clone = copy.copy(img) thresh = cv2.threshold(img,127,255,1)@berak he has updated the code quite a few times now, first version was re-using image
@LorenaGdL, ah, ok. explains a lot.