How do I open .wmv files with OpenCV on Mac? - python

I am trying to open a Windows Media Video file on a macintosh using OpenCV. To view this video in MacOS I had to install a player called Flip4Mac. I am assuming that this came with the codecs for decoding WMV. Is there something I can now do to get OpenCV to open the videos using the codec?
In python/opencv2 opening a video should be super easy:
cap = cv2.VideoCapture('0009.wmv')
But I get this:
WARNING: Couldn't read movie file 0009.wmv

OpenCV video on OS X is very buggy in my experience. However try installing ffmpeg using Homebrew (I also recommend installing OpenCV using homebrew if you haven't done that already):
$ brew install ffmpeg
On Mavericks I've had all kinds of problems getting OpenCV and ffmpeg work together, so you might want to try installing ffmpeg and opencv in different orders, if this does not work. But for me now the following code works, provided that there is a file named test.wmv in the directory:
import cv2
vid = cv2.VideoCapture("test.wmv")
while True:
vid.grab()
retval, image = vid.retrieve()
if not retval:
break
cv2.imshow("Test", image)
cv2.waitKey(1)

I have had the problem before and it was simply that VideoCapture needed the full path to the file and not a relative path.
hope this helps.

Related

How to convert video on python to .mp4 without ffmpeg?

I need to convert videos to .mp4 format I used to ffmpeg but it converts for too long. Is there are a way to convert video to .mp4 in python without ffmpeg?
UPD moviepy depends on ffmpeg too (
==
Zulko/moviepy
pip install MoviePy
import moviepy.editor as moviepy
clip = moviepy.VideoFileClip("myvideo.avi")
clip.write_videofile("myvideo.mp4")
As per MoviePy documentation, there is no ffmpeg dependencies:
MoviePy depends on the Python modules Numpy, imageio, Decorator, and tqdm, which will be automatically installed during MoviePy's installation.
ImageMagick is not strictly required, but needed if you want to incorporate texts. It can also be used as a backend for GIFs, though you can also create GIFs with MoviePy without ImageMagick.
PyGame is needed for video and sound previews (not relevant if you intend to work with MoviePy on a server but essential for advanced video editing by hand).
For advanced image processing, you will need one or several of the following packages:
The Python Imaging Library (PIL) or, even better, its branch Pillow.
Scipy (for tracking, segmenting, etc.) can be used to resize video clips if PIL and OpenCV are not installed.
Scikit Image may be needed for some advanced image manipulation.
OpenCV 2.4.6 or a more recent version (one that provides the package cv2) may be needed for some advanced image manipulation.
Matplotlib
I wrote a quick program that will convert all video files of a particular type in a directory to another type and put them in another directory.
I had to install moviepy using Homebrew for it to work rather than rely on PyCharm's package installation.
import moviepy.editor as moviepy
import os
FROM_EXT = "mkv"
TO_EXT = "mp4"
SOURCE_DIR = "/Volumes/Seagate Media/Movies/MKVs"
DEST_DIR = "/Volumes/Seagate Media/Movies/MP4s"
for file in os.listdir(SOURCE_DIR):
if file.lower().endswith(FROM_EXT.lower()):
from_path = os.path.join(SOURCE_DIR, file)
to_path = os.path.join(DEST_DIR, file.rsplit('.', 1)[0]) + '.' + TO_EXT
print(f"Converting {from_path} to {to_path}")
clip = moviepy.VideoFileClip(from_path)
clip.write_videofile(to_path)

OpenCV 4.0.0 SystemError: <class 'cv2.CascadeClassifier'> returned a result with an error set

Hello I am trying to create a facial recognition program but I have a peculiar error:
here is my code:
import cv2 as cv
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face_cascade = cv.CascadeClassifier("lbpcascade_frontalface.xml")
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5);
and this error is the output
SystemError: <class 'cv2.CascadeClassifier'> returned a result with an error set
I have "lbpcascade_frontalface.xml" in the working directory so that shouldn't be an issue
if it helps when I enter
cv.__version__
I get
'4.0.0'
New Answer
OpenCV seems to now have a directory dedicated to cascades, they are placed in data and I am seeing something like this floating around in tutorials now
haar_cascade_face = cv.CascadeClassifier('data/haarcascade/haarcascade_frontalface_default.xml')
You may have to find where data is on your machine or the above my work. I have not touched this project since I finished it in early 2019.
Bear in mind this only works for frontal face, if you want to use Haar's Cascade for eyes that is a separate file.
old answer
Turns out I didn't need to download another file and use it because opencv comes with it this little bit of code worked
cv.CascadeClassifier(cv.data.haarcascades + "haarcascade_frontalface_default.xml")
Well I was in this same problem, as #TylerStrouth mentioned this code snippet doesn't work :
cv.CascadeClassifier(cv.data.haarcascades + "haarcascade_frontalface_default.xml")
because there are no haarcascades files in data directory if you have just installed opencv in a standard format of pip install opencv-python or sudo apt-get install python3-opencv
You will get an error something similar to this stackoverflow question, therein is the mentioned solution that worked for me, that is if you're using python3 then you need also to install opencv-contrib-python before running the above code snippet.
pip install opencv-contrib-python
which has full package (contains both main modules and contrib/extra modules)
As explained by #TylerStrouth above opencv has a directory of cascades in which the cascade files are available, I also faced the same problem while running the code for face detection on Ubuntu 16.04 and solved it as follows
Get the location of opencv using
whereis opencv
Mine was in /usr/share/opencv
Check whether the cascades are present in that location and copy paste the location in cv2.CascadeClassifier along with the required haarcascade
I have encountered same issue in little different way.
I was using Jupiter notebook to execute code here
I copied XML file from here and created a XML file in current Jupiter directory, when loading this files using below:
classifier = CascadeClassifier('haarcascade_frontalface_default.xml')
Its returned me error :
SystemError: <class 'cv2.CascadeClassifier'> returned a result with an error set
So, I tried other way, removed this file, and downloaded actual file as XML format in current directory, which resolved my issue.
I was having the same error when i was using hogcascade_pedestrians.xml to detect pedestrians from a local video and i was reading the hogcascade_pedestrians.xml as follows:
pedestrainsClassifier = cv2.CascadeClassifier("hogcascade_pedestrians.xml")
Of which you should read it as follows:
pedestrainsClassifier = cv2.CascadeClassifier(f"{cv2.data.haarcascades}hogcascade_pedestrians.xml")
Alternatively you can do it as follows:
pedestrainsClassifier = cv2.CascadeClassifier(cv2.data.haarcascades +"hogcascade_pedestrians.xml")
Good luck
Change your code as follows, this worked for me
har_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +'har.xml')
On version 3.4.9.33 of opencv-python (pip show opencv-python, Windows) the below line works fine: trained_face_data = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

ImageMagick wand not recognizing pdf image?

I'm trying to use this blog post to convert one pdf to a jpg, however everytime I try to run this simple script I get this exception wand.exceptions.WandError: wand contains no images MagickWand-56' # error/magick-image.c/MagickWriteImage/13001
from wand.image import Image
with Image(filename="myFile.pdf") as img:
img.save(filename="myFile.png")
I'm using the latest version of Wand and Python 3.4.2. The only thing I can think of is possibly a version compatibility issue.
So just to close the question, the problem is missing ghostscript library on mac, as indicated in my comment above:
"maybe then some libraries missing. do you use linux/windows/mac?
check what is required there for pdfs? ghostscript maybe? "

Recording video with webcam using VideoCapture

I want to record a video with python (using my webcam) and I came across VideoCapture which was easy to install on windows. I know there is OpenCV out there, but that was too much for me.
So far I can create every 0.04 seconds a .jpg with this code:
from VideoCapture import Device
import time
cam = Device(devnum=0) #uses the first webcame which is found
x = 0
while True:
cam.saveSnapshot(str(x)+'.jpg', timestamp=3, boldfont=1) #########################
x += 1
time.sleep(0.04)
0.04 seconds * 25 = 1. So what I am planning to do is an animated gif, that has 25 frames/sec. If somebody of you knows how to produce a real video file like .mp4, I really would prefer the .mp4 rather than .gif. However if thats not possible, the next thing I need to do is, to concatenate all .jpg files (0.jpg, 1.jpg, 2.jpg ...) but as you can imagine with increasing recording time I get A LOT of files. So I was wondering if it would be possible to write the .jpg files (the frames) to one .gif file consecutively. If thats not possible in python, how would you concatenate the jpg files to get an animated gif in the end?
OpenCV will make it more easy. You will find more problem in your method. To use opencv you have to install 1 more package known as numpy (numerical python). It's easy to install. If you want to install it automatically:
Install
Install pip manually
After that go to your cmd>python folder>Lib>site-packages and type pip install numpy *but for using pip you have to be in internet access.
After installation of numpy just type pip intall opencv.
Now you can import all the packages. If numpy somehow fails, maunually downlaod numpy 1.8.0 and install it.

X11 Tkinter + PIL + py2app = IOError cannot identify image file

I have a problem with a python program (python 2.7.3, X11 Tkinter, py2app 0.6.4, MacOS X 10.7.4) that I'm trying to export to py2app. The problem only started occurring in the standalone py2app-ified app version of the program. When I run the python source file from which the app was created, the problem does not exist, so I feel it must have something to do with the py2app export.
The problem: When I start the GUI, the first time I try to load a valid image file, the image fails to load, and I get the following error from the PIL Image module:
File "Image.pyc", line 1980, in open
IOError: cannot identify image file
When I then (without closing the GUI or anything) try to open the exact same file, it loads perfectly, no errors or problems. This happens every time, with any image file I try - the first attempt to load fails, subsequent attempts succeed. I should add that after that first error, no image files ever fail to load - even if they are different from the first one.
A few notes:
- The image file is a sequence, and is very large (around 300 MB), so to speed up the loading process, I use a mmap. I have tried removing the mmap step, and handing a regular file object directly to ImagePIL.open it directly, and the problem is unaffected.
- I also tried seeking to the beginning of the file before giving it to ImagePIL.open, but that had no effect.
- The py2app setup file is pretty vanilla - it just includes a few config files and an icon.
Here is the relevant part of the offending image load function:
import Image as ImagePIL
import mmap as m
...
...
def loadImage(self):
errorLog.debug("Attempting to open image \""+self.filenameVar.get()+"\"")
try:
if self.fileMap is not None:
self.fileMap.close()
imageFile = open(self.filenameVar.get(), 'r')
self.fileMap = m.mmap(imageFile.fileno(), 0, prot=m.PROT_READ)
# self.fileMap.seek(0)
self.imageSeries = ImagePIL.open(self.fileMap)
imageFile.close()
except(IOError):
errorLog.exception("Failed to open image \""+self.filenameVar.get()+"\"")
return
I'm pretty stumped - any ideas? Thanks in advance!
Edit: I should add that Tkinter, PIL, and py2app were installed using MacPorts 2.1.2, in the off chance that helps.
It seems that py2app does not include PIL's image plugins into the application bundle even though one of the py2app recipes tries to ensure that they are included.
One thing you could try is to build with "python setup.py py2app --packages=PIL" and then use "import PIL.Image as ImagePIL" to use it.
I don't understand yet why the PIL recipe doesn't work, it might be something in the way MacPorts builds python packages (I don't use MacPorts myself).
The problem is the result of inconsistency between Pillow version 3.0.0 and py2app.
I suggest two solution to avoid PIL (Pillow)
Use opencv instead of PIL.
uninstall the current version of Pillow and install a previous one like 1.7.8

Categories