I’ve tried to save an image using OpenCV to a specified folder in the past days however i constantly find this error:
JavaScript
x
5
1
Traceback (most recent call last):
2
File "C:UsershimikDesktop[REDACTED][REDACTED]IMGTEST.py", line 3, in <module>
3
cam = VideoCapture(0) # 0 -> index of camera
4
NameError: name 'VideoCapture' is not defined
5
My code is below:
JavaScript
1
11
11
1
from cv2 import *
2
3
cam = VideoCapture(0)
4
s, img = cam.read()
5
if s:
6
namedWindow("cam-test",CV_WINDOW_AUTOSIZE)
7
imshow("cam-test",img)
8
waitKey(0)
9
destroyWindow("cam-test")
10
imwrite("filename.jpg",img)
11
Any suggestions or ideas on how to solve my issue? Edit: removed irrelevant information!
Advertisement
Answer
Basically the issue is with your from cv2 import *
. I’ll just point you to the internet as to why you shouldn’t us import *
.
FE. this medium article has a nice write-up. Be sure to follow the links in that article as well.
There are two easy fixes available. First, import cv2 into its proper namespace.
JavaScript
1
11
11
1
import cv2 as cv
2
3
cam = cv.VideoCapture(0)
4
s, img = cam.read()
5
if s:
6
cv.namedWindow("cam-test")
7
cv.imshow("cam-test",img)
8
cv.waitKey(0)
9
cv.destroyWindow("cam-test")
10
cv.imwrite("filename.jpg",img)
11
Option 2, import specific parts from cv2. Note that I would very strongly advise to use option 1 here.
JavaScript
1
11
11
1
from cv2 import (VideoCapture, namedWindow, imshow, waitKey, destroyWindow, imwrite)
2
3
cam = VideoCapture(0)
4
s, img = cam.read()
5
if s:
6
namedWindow("cam-test")
7
imshow("cam-test",img)
8
waitKey(0)
9
destroyWindow("cam-test")
10
imwrite("filename.jpg",img)
11