Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

close webcam in openCV python

I want to close web cam i used the cap.released() but it does not close the web cam after it captures the image. Here is my code:

import cv2
import matplotlib.pyplot as plt
def main():
     cap=cv2.VideoCapture(0)
     if cap.isOpened():
             ret, frame = cap.read()
             print(ret)
             print(frame)
     else:
         ret=False
     img1=  cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
     plt.imshow(img1)
     plt.title('Color Image RGB')
     plt.xticks([])
     plt.yticks([])
     plt.show()
     cap.release() 
if __name__=='__main__':
     main() 
like image 798
Mohammad Arshad Avatar asked Mar 13 '26 04:03

Mohammad Arshad


1 Answers

The cam will stay active until you close the figure, i.e. until the script finishes. This is because you only release the capture afterwards,

plt.show()
cap.release() 

If you want to turn off the camera after taking the image, reverse this order

cap.release() 
plt.show()
like image 104
ImportanceOfBeingErnest Avatar answered Mar 16 '26 04:03

ImportanceOfBeingErnest