AttributeError: module 'cv2.cv2' has no attribute 'release' - python-3.x

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.

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

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

Related

(linux) terminate running script

linx terminate running python script , what I know for kill process is that type kill program_ID, but this time I'm not sure how to do, and also don't know the key word to describe or search this problem on web
image in case someone wanna see:
https://ibb.co/xJZ2sQJ
https://ibb.co/Yjgcwwx
I'm inside the command prompt :
(I wrote while loop, so not sure how to stop, I type 'q' also not work)
(venv) joy#raspberrypi:~/Desktop $ python 2.py
^X
:q
q
quit()
quit(q)
kill
.py script
import cv2
# 1.creating a video object
video = cv2.VideoCapture(0)
# 2. Variable
a = 0
# 3. While loop
while True:
a = a + 1
# 4.Create a frame object
check, frame = video.read()
# Converting to grayscale
#gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
# 5.show the frame!
cv2.imshow("Capturing",frame)
# 6.for playing
key = cv2.waitKey(1)
if key == ord('q'):
break
# 7. image saving
showPic = cv2.imwrite("filename.jpg",frame)
print(showPic)
print(cv2.__version__)
# 8. shutdown the camera
video.release()
cv2.destroyAllWindows

OpenCV imshow function is not always working properly

I'm trying to read license plate. So I found this tutorial : https://medium.com/programming-fever/license-plate-recognition-using-opencv-python-7611f85cdd6c
And when I run it the cv2.imshow() isn't working every time. Sometime I got the image but sometime just the window with a tiny black rectangle in it. Here is the little window
img = cv2.imread('2.jpg',cv2.IMREAD_COLOR)
img = cv2.resize(img, (640,480) )
cv2.imshow('actual', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Just this tiny code is supposed to work everytime if the image exists. But it doesn't.
Does anyone have any clue about this ?
Thanks
Well to make it work I changed two things :
First I had cv2.namedWindow('actual', cv2.WINDOW_NORMAL)
And then I updated using : pip3 install opencv
And now it's working every time.
Try to put the destroyAllWindows in a loop to close it properly (pressing q):
img = cv2.imread('2.jpg',cv2.IMREAD_COLOR)
img = cv2.resize(img, (640,480) )
cv2.imshow('actual', img)
while True:
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break

Unable to capture image every 5 seconds using OpenCV

I am trying to capture image in every 5 seconds using opencv through my laptop's built-in webcam. I am using time.sleep(5) for the required pause. In every run, the first image seems to be correctly saved but after that rest all the images are being saved as an unsupported format (when i am opening them). Also I am unable to break the loop by pressing 'q'.
Below is my code.
import numpy as np
import cv2
import time
cap = cv2.VideoCapture(0)
framerate = cap.get(5)
x=1
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
cap.release()
# Our operations on the frame come here
filename = 'C:/Users/shjohari/Desktop/Retail_AI/MySection/to_predict/image' + str(int(x)) + ".png"
x=x+1
cv2.imwrite(filename, frame)
time.sleep(5)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
Any help is appreciated.
Just a small change, solved my issue.
I included the below code inside the loop :P
cap = cv2.VideoCapture(0)
framerate = cap.get(5)

Python add audio to video opencv

I use python cv2 module to join jpg frames into video, but I can't add audio to it. Is it possible to add audio to video in python without ffmpeg?
P.S. Sorry for my poor English
Use ffpyplayer to handle the audio part.
import cv2
import numpy as np
#ffpyplayer for playing audio
from ffpyplayer.player import MediaPlayer
video_path="../L1/images/Godwin.mp4"
def PlayVideo(video_path):
video=cv2.VideoCapture(video_path)
player = MediaPlayer(video_path)
while True:
grabbed, frame=video.read()
audio_frame, val = player.get_frame()
if not grabbed:
print("End of video")
break
if cv2.waitKey(28) & 0xFF == ord("q"):
break
cv2.imshow("Video", frame)
if val != 'eof' and audio_frame is not None:
#audio
img, t = audio_frame
video.release()
cv2.destroyAllWindows()
PlayVideo(video_path)
The sample code will work but you need to play around the cv2.waitKey(28) depending on the speed of your video.
This is how I am reading audio and video frames:
from moviepy.editor import *
from pafy import pafy
if __name__ == '__main__':
video = pafy.new('https://www.youtube.com/watch?v=K_IR90FthXQ')
stream = video.getbest(preftype='mp4')
video = VideoFileClip(stream.url)
audio = video.audio
for t, video_frame in video.iter_frames(with_times=True):
audio_frame = audio.get_frame(t)
print(audio_frame)
print(video_frame)
This code downloads YouTube video and returns raw frames as numpy arrays.
You can pass the file as an argument to the VideoFileClip instead of the URL.
You can use pygame for audio.
You need to initialize pygame.mixer module
And in the loop, add pygame.mixer.music.play()
But for that, you will need to choose audio file as well.
However, I have found better idea! You can use webbrowser module for playing videos (and because it would play on browser, you can hear sounds!)
import webbrowser
webbrowser.open("video.mp4")
import pygame
pygame.mixer.init()
pygame.mixer.music.load(
'c:Your_file')
pygame.mixer.music.play()
while True:
pygame.time.Clock().tick()
#used to show that you can do other stuff while playing audio
print("hi")

pygame.surface type error: an integer is required

I am new to pygame and i wanted to know what is wrong and how can i fix it, thank you! also my pygame closes right when i open it, thats why i took a screenshot like this one. if you could also explain why it closes that fast, that would be great! (pygame 1.9.2 python 3.4.1 , windows 8)![enter image description here][1]
#!/usr/bin/env python
import pygame, sys
from pygame.locals import *
pygame.init()
pygame.font.init()
pygame.display.set_caption('Primer juego de Gian Di Julio')
mainclock= pygame.time.Clock()
screen = pygame.display.set_mode((800,600))
pygame.mouse.set_visible(0)
#positioning the ship into the middle of the screen
ship = pygame.image.load('ship.png')
ship_top = screen.get_height() - ship.get_height()
ship_left = screen.get_width()/2 - ship.get_width()/2
pygame.Surface(ship,(ship_left,ship_top))
while True:
screen.fill((0,0,0))
x,y = pygame.mouse.get_pos()
screen.blit(ship, (x-ship.get.width()/2, ship_top))
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.display.update()
pygame.display.flip()
I just looked it up in the pygame docs:
Surface((width, height), flags=0, Surface) -> Surface
But the returned surface is not used in your program so you might leave it out.
When using pygame.display.flip() there is no need for calling pygame.display.update().
Additionally it should be indented.
It closes quickly because you have a syntax error in your code.
pygame.Surface(ship,(ship_left,ship_top))
This line tries to create a surface, with dimensions taken from the ship variable.
Since ship is a surface loaded from an image, it fails.
Removing this line will fix the issue.

Resources