【发布时间】:2022-11-10 06:27:25
【问题描述】:
我打算将 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) 我的系统或代码中是否存在问题 如何解决这个问题。
【问题讨论】:
-
它可以在我的笔记本电脑上使用
cv.videoCapture(0)。你确定你的相机连接正确吗?如果您使用的是笔记本电脑,则可访问性可能存在一些问题。尝试以管理员或类似的方式运行 IDE。 -
始终在创建
assert webcam.isOpened()后立即检查它。如果这甚至不起作用,那么您的所有其余代码都是无关紧要的。