Opencv 和 Python 的问题 [英] Problem with Opencv and Python

查看:48
本文介绍了Opencv 和 Python 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 python 和 Opencv 的新手,我尝试输入以下代码将图像从我的网络摄像头保存到我的计算机:

I'm new to python and Opencv and I tried to put in the following code to save an image to my computer from my webcam:

import cv
if __name__=='__main__':
    pCapturedImage = cv.CaptureFromCAM(1)
    rospy.sleep(0.5)
        pSaveImg=cv.QueryFrame(pCapturedImage)
    cv.SaveImage("test.jpg", pSaveImg)

但是当我尝试打开它时,我发现 jpeg 是空的.有人可以帮忙吗?另外,我尝试了一个程序来显示我的网络摄像头看到的内容:

But when I try to open it, I find that the jpeg is empty. Could someone please help? Also, I tried a program to show what my webcam is seeing:

import cv
if __name__=='__main__':
    cv.NamedWindow("camera",1)
    capture=cv.CaptureFromCAM(0)
    while True:
        img=cv.QueryFrame(capture)
        cv.ShowImage("camera", img)
        if cv.WaitKey(10)==27:
        break
    cv.DestroyedWindow("camera")

但是当我运行它时,我得到一个只显示灰色屏幕的应用程序.有人也可以帮忙吗?谢谢.

But when I run it, I get an application that just shows me a gray screen. Could someone help with this too? Thanks.

推荐答案

您是否尝试过演示程序?他们展示了如何使用网络摄像头以及其他许多东西.

Have you tried the demo programs? They show how to use the webcam among many other things.

对于第一个问题,我不熟悉在 opencv 中使用相机,但我通过打开捕获(capture.open(device_id) 在下面的代码中)让它工作了

For the first problem, I am not familiar with using cameras in opencv, but I got it to work by opening the capture (capture.open(device_id) in the code below)

这是一个工作 python 示例(我使用较新的 C++ 接口:imread, imwriteVideoCapture、等等...您可以在 OpenCV 文档 中找到,当它可用时列为cv2"用于python.):

Here is a working python sample (I use the newer c++ interface: imread, imwrite, VideoCapture, etc... which you can find in the OpenCV docs listed as "cv2" when it is available for python.):

import cv2

capture = cv2.VideoCapture()  # this is the newer c++ interface
capture.open(0)  # Use your device id; I think this is what you are missing. 
image = capture.read()[1]
cv2.imwrite("test.jpg", image)

我通过在捕获对象上使用 open 也使您的第二个示例工作:

I got your second sample also working just by using open on the capture object:

import cv2

cv2.namedWindow("camera", 1)  # this is where you will put the video images
capture = cv2.VideoCapture()
capture.open(0)  # again, use your own device id
while True:
    img = capture.read()[1]
    cv2.imshow("camera", img)
    if cv2.waitKey(10) == 27:  # waiting for the esc key
        break
cv2.destroyWindow("camera")

这篇关于Opencv 和 Python 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆