'camera not responding for opencv videocapture
I intended to work on opencv as a part of my project. I want to take images from the webcam and process them. So I used videocapture(). When I used this the camera is not responding for it. the same program , I tried in both visual studio and jupyter notbook . both resulted the same. The code is as follows:
import cv2
import matplotlib.pyplot as plt
key = cv2. waitKey(1)
webcam = cv2.VideoCapture(-1)
while True:
try:
check, frame = webcam.read()
print(check) #prints true as long as the webcam is running
#print(frame) #prints matrix values of each framecd
cv2.imshow("Capturing", frame)
key = cv2.waitKey(1)
if key == ord('s'):
cv2.imwrite(filename='saved_img.jpg', img=frame)
webcam.release()
img_new = cv2.imread('saved_img.jpg', cv2.IMREAD_GRAYSCALE)
img_new = cv2.imshow("Captured Image", img_new)
cv2.waitKey(1650)
cv2.destroyAllWindows()
print("Processing image...")
img_ = cv2.imread('saved_img.jpg', cv2.IMREAD_ANYCOLOR)
print("Converting RGB image to grayscale...")
gray = cv2.cvtColor(img_, cv2.COLOR_BGR2GRAY)
print("Converted RGB image to grayscale...")
print("Resizing image to 28x28 scale...")
img_ = cv2.resize(gray,(28,28))
print("Resized...")
img_resized = cv2.imwrite(filename='saved_img-final.jpg', img=img_)
print("Image saved!")
plt.show()
break
elif key == ord('q'):
print("Turning off camera.")
webcam.release()
print("Camera off.")
print("Program ended.")
cv2.destroyAllWindows()
break
except(KeyboardInterrupt):
print("Turning off camera.")
webcam.release()
print("Camera off.")
print("Program ended.")
cv2.destroyAllWindows()
break
the
print(check)
print(frame)
are returning
False
None
I even tried videocapture(0) and videocapture(-1) Is problem present in my system or in the code how to resolve this issue.
Solution 1:[1]
Tip 1: you have an excessive amount of code when your sole objective is to test your webcam - see minimized script to check the cam.
Tip 2: shut down or suspend anti virus. I saw several of times anti virus(kaspersky and maybe AVG) blocking python from opening the webcam (I guess to avoid someone hacking your cam).
import cv2
def cam_test(port: int = 0) -> None:
cap = cv2.VideoCapture(port)
if not cap.isOpened(): # Check if the web cam is opened correctly
print("failed to open cam")
else:
print('cam opened on port {}'.format(port))
for i in range(10 ** 10):
success, cv_frame = cap.read()
if not success:
print('failed to capture frame on iter {}'.format(i))
break
cv2.imshow('Input', cv_frame)
k = cv2.waitKey(1)
if k == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
return
if __name__ == '__main__':
cam_test()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gilad eini |
