I install cv2 using pip command but it give error No matching
distribution found for cv2.
Below my is 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()
Install opencv or cv2 using pip
Related
I am running the below code to convert video into frames. Problem is it is creating Image files with 0 KB size and when I open it is not showing anything.. I don't understand what is creating the problem. Do I need to install any Image codecs?
'''
Using OpenCV takes a mp4 video and produces a number of images. I am using OpenCV 3.3.0 version and Python 2.7
Which will produce a folder called data with the images, There will be 2000+ images for example.mp4.
'''
import cv2
import numpy as np
import os
# Playing video from file:
try:
cap = cv2.VideoCapture('aa.mkv')
except:
print "Could not open video file"
raise
print cap.grab()
try:
if not os.path.exists('data'):
os.makedirs('data')
except OSError:
print ('Error: Creating directory of data')
currentFrame = 0
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
if not frame is None:
# Saves image of the current frame in jpg file
name = './data/frame' + str(currentFrame) + '.jpg'
print ('Creating...' + name)
cv2.imwrite(name, frame)
#cv2.imshow(name, frame)
else:
break
# To stop duplicate images
currentFrame += 1
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
You are not using imwrite function to write frames. Also your imshow function name is misspelled. I have made changes in your code. Try this:
import cv2
import numpy as np
import os
# Playing video from file:
cap = cv2.VideoCapture('aa.mkv')
try:
if not os.path.exists('data'):
os.makedirs('data')
except OSError:
print ('Error: Creating directory of data')
currentFrame = 0
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
if not frame is None:
# Saves image of the current frame in jpg file
name = './data/frame' + str(currentFrame) + '.jpg'
print ('Creating...' + name)
cv2.imwrite(name, frame)
cv2.imshow(name, frame)
else:
break
# To stop duplicate images
currentFrame += 1
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
I am trying to save video using videocapture object in openCv using python. But after pressing 'q' the video is saved as 'output.avi' but its size is showing as 0 KB. Need your help, not able to find out the error.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
#1.2. Gui Features in OpenCV 25
#OpenCV-Python Tutorials Documentation, Release 1
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
Here you need to play with fourCC code
FourCC code is passed as cv2.VideoWriter_fourcc('M','J','P','G') or cv2.VideoWriter_fourcc(*'MJPG) for MJPG.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
For more read, OpenCV saving doc and FourCC doc
It maybe that the codecs for XVID is not properly installed.
(If you are using Jupyter Notebook, there would be jupyter logs begin with OpenCV: FFMPEG: ...)
If you are on linux, you could try to use the cv2.VideoWriter_fourcc(*'mp4v') as below:
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4', -1, 20.0, (640,480))
Notice, the extension mp4 matters! Should choose the right extension matching the codec.
I can run the same program in Windows. I can see my camera using lsusb in Ubuntu 16.04, 64 bits. The camera is an OSVR infrared camera.
My program is
import numpy as np
import cv2
camera = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = camera.read()
cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('camera', frame)
# k = cv2.waitKey(30)
# When everything done, release the capture
camera.release()
cv2.destroyAllWindows()
The results are:
cwu#ubuntu:~/project/osvrCamera$ python test.py
select timeout
select timeout
OpenCV Error: Assertion failed (!buf.empty() && buf.isContinuous()) in imdecode_, file /tmp/binarydeb/ros-kinetic-opencv3-3.1.0/modules/imgcodecs/src/loadsave.cpp, line 490
Traceback (most recent call last):
File "test.py", line 8, in <module>
ret, frame = camera.read()
cv2.error: /tmp/binarydeb/ros-kinetic-opencv3-3.1.0/modules/imgcodecs/src/loadsave.cpp:490: error: (-215) !buf.empty() && buf.isContinuous() in function imdecode_
Check if the frame isn't empty() first (maybe cam/frame isn't fully initialised when you try to convert/display it:
import numpy as np
import cv2
camera = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = camera.read()
if not frame.empty():
cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('camera', frame)
# k = cv2.waitKey(30)
# When everything done, release the capture
camera.release()
cv2.destroyAllWindows()
I am trying to use background Substractor module in opencv. I am referring this blog. I am not able to use it because I again and again get the error message 'module' object has no attribute 'createBackgroundSubtractorMOG' , I have go-ogled through all the answers to this problem and I have tried using all the substrings possible like - createBackgroundSubtractor , BackgroundSubtractor , createBackgroundSubtractorMOG2 etc. but I again get the same error message. I am using -
opencv 3.0.0
python 2.7.10
ubuntu 15.10
here's my code--
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG(detectShadows=True)
while(1):
ret, frame = cap.read()
fgmask = fgbg.apply(frame)
cv2.imshow('frame', fgmask)
k = cv2.waitKey(0)
if(k == 27):
break
cap.release()
cv2.destroyAllWindows()
Got my question solved. What i did , I opened python command line and wrote dir(cv2) and it listed me all the functions I can call and there I found BackgroundSubtractorMOG and it worked!
import cv2
import numpy as np
cap = cv2.VideoCapture('traffic.avi')
retval, frame = cap.read()
print retval
================ RESTART: J:\Python For DIP\traffic_video.py ================
False
>>>
The Value of retval is always False, which means the video is not read by the command. It must be True to read frames. I don't know what to do. However when I use my default webcam it turns to be True. I tried many videos and the same problem appears. Note: I have installed the ffmpeg correctly.
Note: This is not the full code, in this step I am only validating cap.read() either True or False
This method is guaranteed 100%
first of all check your version of OpenCV, say for instance 2.4.11. you can check it by typing the following commands in your Python Shell:
>>> from cv2 import __version__
>>> __version__
'2.4.11'
>>>
Then go to C:\opencv\build\x86\vc12\bin and copy opencv_ffmpeg2411.dll.
Finally go to root directory of Python ex: C:\Python27 and paste opencv_ffmpeg2411.dll in it
check the name of the file opencv_ffmpeg2411.dll, whether the version
of opencv is written or not, if not do the following
opencv_ffmpeg(version of your opencv without dots).dll
After that create a new Python file and copy this code and paste it loading your own video
import numpy as np
import cv2
# Capture video from file
cap = cv2.VideoCapture('your video')
while True:
ret, frame = cap.read()
if ret == True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(30) & 0xFF == ord('q'):
break
else:
break
cap.release()
cv2.destroyAllWindows()
you will have an output video for example like this:
Result
Finding the root directory of Python can be a little tricky. I am using an Enthought distribution and, at first, pasted the opencv_ffmpeg file into the wrong Python directory.
WRONG:
C:\Users\USERNAME\AppData\Local\Programs\Python\Python35-32
RIGHT:
C:\Users\USERNAME\AppData\Local\Enthought\Canopy\User
Long story short, make sure you find the right Python directory.