OpenCV real-time camera image not moving - python

I'm trying to run the most simple script for viewing the laptop's camera in real time. But unfortunately after starting the window shows, but I get only a single frame displayed that doesn't ever get updated.
import cv2
cap = cv2.VideoCapture(0)
while True:
ret, img = cap.read()
cv2.imshow('test', img)
if cv2.waitKey(-1):
break
cv2.destroyAllWindows()
cap.release()
I was following tutorials for installing this on Windows and installed it on separate environment, using pip and downloaded wheel. The window shows OK, and the image from camera is displayed but static. The program isn't hanged however, because it awaits a key being pressed and closes correctly afterwards.
What can be the cause?

Try using this loop:
while True:
ret, img = cap.read()
cv2.imshow('test', img)
keypressed = cv2.waitKey(30)
if keypressed == ord('q'):
break
The argument of cv2.waitKey(delay) is the delay in millisecond and the returned value is the key pressed:
The function waitKey waits for a key event infinitely (when 𝚍𝚎𝚕𝚊𝚢≤0 ) or for delay milliseconds, when it is positive. [..]
It returns the code of the pressed key or -1 if no key was pressed before the specified time had elapsed.
See: https://docs.opencv.org/4.1.0/d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7

Try this:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

I hope this will work it is fast and easy solution.
you can capture image by pressing c and q for quit the window
import cv2
cap = cv2.VideoCapture(0)
count=0
while(True):
ret, frame = cap.read()
cv2.imshow("imshow",frame)
key=cv2.waitKey(30)
if key==ord('q'):
break
if key==ord('c'):
count+=1
cv2.imwrite('/home/user/Desktop/image'+str(count)+'.png', frame)
cap.release()
cv2.destroyAllWindows()

Related

Create a loop to get the image from the camera without breaking(any reason)

I am going to write a code to get the image from the IP camera. Of course, if the connection between the code and the camera is interrupted (for any reason), it will wait to connect again and start imaging again.
as we know
Receiving the image from the camera does not work with the usual loops.
I checked almost all the cases and did not get any results.
Edit my code to get the image:
python 3.6.17
opencv 3.4.2.17
import cv2
#print("Before URL")
cap = cv2.VideoCapture('rtsp://admin:123456#192.168.1.216/H264?ch=1&subtype=0')
#print("After URL")
while True:
#print('About to start the Read command')
ret, frame = cap.read()
#print('About to show frame of Video.')
cv2.imshow("Capturing",frame)
#print('Running..')
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

OpenCV capture doesn't work gets this problem MFVideoFormat_RGB24(codec not found),how can i solve?

I am making a python app i need openCV library here is my code:
# importing the required modules
import cv2
import numpy as np
# capturing from the first camera attached
cap = cv2.VideoCapture(0)
# will continue to capture until 'q' key is pressed
while True:
ret, frame = cap.read()
cv2.imshow('frame', frame)
# Program will terminate when 'q' key is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Releasing all the resources
cap.release()
cv2.destroyAllWindows()
when I run the code I got this error:
[ WARN:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wwma2wne\opencv\modules\videoio\src\cap_msmf.cpp (677) CvCapture_MSMF::initStream Failed to set mediaType (stream 0, (640x480 # 30) MFVideoFormat_RGB24(codec not found)
I think may be it requires a codec driver but i don't know how to fix the error
please help me friends
following code resolved this issue for me: cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
try
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)

How to play a wav file and make your code continue running in python?

I have this code that plays a video, and detects something on it. Whenever it detects something in the video, I want to hear something, here is the code:
import cv2
import os
video_capture = cv2.VideoCapture('video')
while True:
_, frame = video_capture.read()
found = detect_something(frame)
if found :
os.system("aplay 'alarm'")
cv2.imshow('Video',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
The problem is that, whenever it plays the alarm, the video freezes. I want the alarm to be played as a background sound. How can I do that?
What it needs is a tread:
import cv2
import os
from threading import Thread # Import Thread here
video_capture = cv2.VideoCapture('video')
def music(): # Define a function to go in the Thread
os.system("aplay 'alarm'")
while True:
_, frame = video_capture.read()
found = detect_something(frame)
if found :
mus = Thread(target=music) # Create a Thread each time found
mus.start() # Start the Thread as soon as created
cv2.imshow('Video',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()

How to access video stream from an ip camera using opencv in python?

Right now I am using a web cam and it works perfectly fine with the code below -:
capture = cv2.VideoCapture(0)
Now instead of web cam, I want to use the ip camera(https://192.168.0.60)
What would be the easiest way to do it with OpenCV(Python)?
I saw a bunch of posts, but couldn't find a straight answer to this.
Can someone help, who already got it running?
Thank you!
Firstly, you must find the exact url for your video stream, and that's best done with a web browser. For example I use IP Webcam app on android (com.pass.webcam) and it's stream will be on:
http://phone-ip-address:port/video
If I visit that url with a web browser, I can see the live stream. Make sure, that what you see is only the video stream, not a html page with the stream. If there is a html page, you can right-click and select Open image in new tab (in Chrome) to get to the stream.
However it looks like OpenCV can only read the video stream if the filename/url has the right suffix. Adding ?type=some.mjpeg worked for me. So the url would be:
http://phone-ip-address:port/video?type=some.mjpeg
Try visiting such an url in the web browser before you go for opencv.
Take a look at this example with python, OpenCV, IPCAM and hikvision
import numpy as np
import cv2
cap = cv2.VideoCapture()
cap.open("rtsp://USER:PASS#IP:PORT/Streaming/Channels/2")
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
#gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('Salida',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
Image:
Get video from IPCAM with python and OpenCV
Here you go,
import numpy as np
import cv2
cap = cv2.VideoCapture('rtsp://<username_of_camera>:<password_of_camera#<ip_address_of_camera')
while(True):
ret, frame = cap.read()
cv2.imshow('Stream IP Camera OpenCV',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
For example:
import numpy as np
import cv2
cap = cv2.VideoCapture('rtsp://admin:admin#192.168.0.60')
while(True):
ret, frame = cap.read()
cv2.imshow('Stream IP camera opencv',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Then save the file as camera.py (.py), go to command prompt or terminal, locate file and type python camera.py or python <file_name>.py enter to run script.
If you want to exit from script windows just press "q" or close cmd.
Hope this helpful.
Here is an example for a Vivotek IP8136W IP Camera. It does not support streaming.
This code continuously grabs still frames, at about 2fps. No observed CPU loading.
import numpy as np
import cv2
# for webcams, request stream only once.
#cap = cv2.VideoCapture(0)
while(True):
# For single image IP cams, request frame every time.
cap = cv2.VideoCapture("http://root:0002A78D65F2#192.168.1.38/cgi-bin/viewer/video.jpg")
ret, frame = cap.read()
# Display the resulting frame
if ret:
cv2.imshow('camera',frame)
else:
print("error getting frame.")
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Done. release the capture
cap.release()
cv2.destroyAllWindows()

opencv error Assertion failed python

import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor,
file /home/pi/opencv-2.4.9/modules/imgproc/src/color.cpp, line 3737
Traceback (most recent call last): File "test.py", line 11, in
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.error: /home/pi/opencv-2.4.9/modules/imgproc/src/color.cpp:3737: error:
(-215) scn == 3 || scn == 4 in function cvtColor
This typically happens to me when the filename doesn't exist or isn't an image.
This is happening because there is an error in reading image from the video. you can try the below code and if you are seeing nothing, then the problem is with your webcam.
import cv2
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
while ret:
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
ret, frame = cap.read()
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
If you are using a docker container to run your code, the issue might be in the way you set up your docker container. In particular, you need to specify a flag --device to enable a camera usage in the docker container when creating the container like this:
docker run --device <device-path> <rest-of-the-paramaters>
Before that, you need to check the path of the camera device by using ls -ltrh /dev/video* for Ubuntu. Usually, the path is /dev/video0.
I ran your code, it works perfectly fine for me.
But I did get some indentation errors.
Here's the updated code:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
If one still gets this error, try doing the following:
check if your webcam works fine with any other library other than OpenCV
change VideoCapture(0) => VideoCapture(1)
Uninstall OpenCV and reinstall it
Relaunch your code editor or whatever
Switch to a different IDE (for example from PyCharm to Jupyter notebook)
Also add these in the above code :
if ret:
assert not isinstance(frame,type(None)), 'frame not found'
OR
assert (frame is not None) == ret, (ret, type(frame))
OR
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break

Categories

Resources