I am running a video feed through a cv2.imshow
operator. Most of the time, the code runs when I call it in command line, but occasionally I get the following NameError:
NameError: name 'masked' is not defined
However, 'masked' is absolutely defined before it is called in cv2.imshow:
image = frame.array
miniframe = image
masked = cv2.bitwise_and(image, image, mask=circle_img)
cv2.imshow("frame", masked)
same thing happens when 'masked' is defined this way:
image = frame.array
miniframe = image
M = np.float32([[1,0,x+w/2],[0,1,y+h/2]])
masked = cv2.warpAffine(image, M, (x+w, y+h))
cv2.imshow("frame", masked)
When print masked
is inserted above the cv2.imshow
line, it results in the array printed as numbers - when the code is working. When it is not working, it results in the NameError traceback pointing to print masked
.
And to be clear, in either scenario the NameError happens seemingly randomly, without modification to the code. So, I can run it once or 20 times just fine, but then it will suddenly not work in command line, with a traceback to the cv2.imshow
line. Sometimes, copy-pasting identical blocks of code from previous versions will get it to work again, but after a few unmodified tries, back to NameError
.
I have read over Python NameError when var IS most definitely defined, and used cat -A filename.py
to check the invisible control characters. After de- and re-indenting, it worked 2 more times, and then right back to the NameError.
Any help would be much appreciated!
Found a resolution. My problem was related to a condition in 'masked' that was not fulfilled. This is a program that relies on face detection, but my problem would be the same for any random, ongoing condition that must be fulfilled.
Troubleshooting steps included: - reviewing my tracebacks - testing IRL by having a face in front of the camera on start, and then a hand over the camera on start. This confirmed that the program would run if a face was detected on start, but not if there was no face.
To resolve the issue, I used a try/except condition for cv2.imshow("frame", masked)
, resulting in code that looked like:
image = frame.array
miniframe = image
M = np.float32([[1,0,x+w/2],[0,1,y+h/2]])
masked = cv2.warpAffine(image, M, (x+w, y+h))
try:
cv2.imshow("frame", masked)
except NameError:
cv2.imshow("frame", image)
I am a rank beginner, this really taught me the value of testing and reviewing tracebacks!