0
votes

I come from RDBMS background and just starting on python. below is a simple code i written to invoke my web cam via python

import cv2

vid = cv2.VideoCapture(0)
 while vid == True:
     print("Connected....");
if cv2.waitKey(0) : break

cv2.release();

but i am getting error

AttributeError: module 'cv2.cv2' has no attribute 'release'

while executing it. I am running this code using python3.5 and on linux 14.04 platform. I can see cv2 package installed via help("modules") list and it gets imported as well without error . however i dont see it in the interpreter list of pycharm. please help.

2
it seems like i had issues with openCV and python3.5 which are still unknown to me. i switched back to python2.7 and used the blog at link to install opencv and it worked without any issues. - Pawan Rawat

2 Answers

1
votes

cv2.release() does not exist. I think what you are trying to do is vid.release()

cv2 is the opencv module and vid is the VideoCapture object. which is the one that you have to do the release.

UPDATE:

The code you have has several mistakes. Before I only addressed the one you asked, but lets go through all of them.

First one, the indentation is wrong, I guess maybe it is from copying the code.

Second one

while vid == True:

This is not the correct way to do it. You can use the vid.isOpened() function to see if it opened/connected to the webcam.

Third one, you do not need to use ; after the instructions.

Fourth one, this one is not an error, but something that is not necessary

if cv2.waitKey(0) : break

the if is not necessary, waitKey will return the key pressed as an ascii character, if you use a number other than 0 it will return 0 if no key was pressed. But with 0 it will wait for a key to be pressed "blocking" the current thread (in case you have more than one). However, it will not wait unless that you have a imshow window opened.

Now, the complete code with those changes that I wrote and that checks if the script can connect to a camera will be

import cv2

vid = cv2.VideoCapture(0)
if vid.isOpened():
  print ("Connected....")
else:
  print ("Not Connected....")

vid.release()

In a similar fashion you can display the video until a key is pressed:

import cv2

vid = cv2.VideoCapture(0)
if vid.isOpened():
  print ("Connected....")
  while True:
    ret, frame = vid.read()
    if ret:
      cv2.imshow("image", frame)
    else:
      print ("Error aqcuiring the frame")
      break
    if cv2.waitKey(10) & 0xFF:
      break
else:
  print ("Not Connected....")

vid.release()
cv2.destroyAllWindows()

If something is not clear, feel free to ask :)

0
votes

import cv2 import numpy

img = cv2.imread("lena.jpg", 1) cv2.imshow("image", img) cv2.waitKeyEx(0) cv2.destroyAllWindows()