0

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)

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.

1
  • 1
    Did you get this working? I suggested the same code below to another person so I hope I'm not spreading misinformation. Commented Jun 26, 2012 at 6:16

1 Answer 1

1

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

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)

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)

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")
Sign up to request clarification or add additional context in comments.

2 Comments

Did not work for me. Plus when I wrote print img it returned (False,None). Any solutions?
@PrakharMohanSrivastava I just checked the code again. It works for me. I updated the comments on the code - perhaps you need to use a different device id on capture.open(x)?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.