照相机对opencv视频捕获没有响应

n1bvdmb6  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(185)

我打算把opencv作为我项目的一部分。我想从网络摄像头获取图像并处理它们。所以我使用了videocapture()。当我使用这个时,摄像头没有响应。我在visual studio和jupyter notbook中尝试了同一个程序。两个程序的结果都是一样的。代码如下:

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

print(check)
print(frame)

正在返回

False
None

我甚至尝试了videocapture(0)和videocapture(-1)是问题存在于我的系统或代码如何解决这个问题。

ovfsdjhp

ovfsdjhp1#

提示1:当你的唯一目标是测试你的网络摄像头时,你有过多的代码--请参见最小化脚本来检查摄像头。
提示2:关闭或暂停反病毒。我看到好几次反病毒(卡巴斯基,也许还有AVG)阻止Python打开网络摄像头(我猜是为了避免有人黑客你的摄像头)。

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()

相关问题