Opencv videocapture не открывает файл
cap_dshow.cpp, 2315 line, bool videoInput::isDeviceDisconnected(int deviceNumber)
It is added function on opencv 3.2.0.
Steps to reproduce
The text was updated successfully, but these errors were encountered:
9 Answers 9
Renaming the opencv_ffmpeg.dll file may also be necessary.
For OpenCV version X.Y.Z
opencv_ffmpeg.dll ==> opencv_ffmpegXYZ.dll
For 64-bit OpenCV version X.Y.Z
opencv_ffmpeg.dll ==> opencv_ffmpegXYZ_64.dll
Thank you! It works, but only if you copy all files from C:\OpenCV\3rdparty\ffmpeg`, not just opencv_ffmpeg.dll`.
See all answers below. It seems that one needs to rename the opencv_ffmpeg.dll file to opencv_ffmpegXYZ.dll for OpenCV version X.YZ and to opencv_ffmpegXYZ_64.dll if one uses the 64 bit version.
With OpenCV 2.4.10, adding C:\opencv\sources\3rdparty\ffmpeg to Windows path and renaming opencv_ffmpeg.dll and opencv_ffmpeg_64.dll to opencv_ffmpeg2410.dll and opencv_ffmpeg2410_64.dll it works ! Thanks :) I am now able to open MJPEG video files
Thanks - this works! It's frustrating that this "silently fails" without that DLL copied in. I'd rather instead of a subtle false, a nice big exception "error, Danger Will Robinson, missing dll <. >" and then die.
Copying opencv_ffmpeg.dll wasn't enough for me - I had to rename it to opencv_ffmpeg246.dll, when I used OpenCV 2.4.6 with Python 2.7.5
I first tried copying, then changing the Path environment of windows.. it didn't work until i changed the name to opencv_ffmpeg245.dll for my openCV version 2.4.5 and python 2.7. (notice **245.dll is from opencv version 2.4.5)
For 64 bit versions, rename opencv_ffmpeg_64.dll to opencv_ffmpeg249_64.dll Change 249 to your opencv version.
For OpenCV 3.0.0 on 64 bit environment copy opencv_ffmpeg_64.dll and rename it to opencv_ffmpeg300_64.dll.
Also add this path to your PATH environment variable to get it work with OpenCV under Java.
Update: This is still true for OpenCV 2.4.9, copy all the files, and rename the dll opencv_ffmpeg249.dll
I had the same issue with python 2.7 and opencv 2.4.10. I copied the opencv_ffmpeg2410_64.dll file from C:\Applications\opencv\build\x64\vc10\bin into the python path (mine is at C:\Users\mohammad\Anaconda) and it was solved!
At first I use windows8.1 32bit and opencv 2.4.10.
I faced same problem to use file test1.wmv which was made by Logicool C270.
I tried to use other file test2.mov which was made by Digital Camera ( Canon SX160 ). So I can play test2.mov to append path C:\opencv\build\x86\vc12\bin .
But I cannot Play test1.wmv.
So I try to change format test1.wmv to test1a.mp4 by using VLC ( to Video for youtube HD ) .
Then I can play test1a.mp4.
I tried test1.wmv on Ubuntu 14.04 LTS , then I can play it easy.
It may occur some difference on default ffmpeg binary between windows8.1 and Ubuntu 14.04 LTS.
The opencv works fine when doing other things. It can open images and show images. But it can't open a video.
The code I'm using to open a video is as below
But when executing, it outputs error messages like below
My vlc and mplayer can play this video, but the opencv can't.
I have installed x264 and libx264-142 codec package. (using sudo apt-get install )
My version of ubuntu is 14.04 trusty .
I'm not sure is it a codec problem or not?
I have rebuilt opencv either with WITH_UNICAP=ON or with WITH_UNICAP=OFF , but it doesn't affect the problem at all. The error messages never change.
nhlsm commented May 2, 2017
Thank you for reply, wuzhenwu.
Another camera does not work. ( same, just black screen )
- Both camera work fine with AMCAP (9.20) program.
- Both camera does not work with old AMCAP ( < 9.20 )
( error message is "bla bla bla . 80070005." 80070005 is -2147024891 in decimal )
nhlsm commented May 1, 2017
Thank you for reply, wuzhenwu. But, it does not work.
The log message is as follows. Can you upload your log meesge on yout machine?
( The debug built binary can print log message. )
I suspect "Event: Code: 0x03 Params: -2147024891, 0"
Code 0x03 means EC_ERRORABORT.
nhlsm commented May 1, 2017
Thank you for reply, wuzhenwu. But, it does not work.
The log message is as follows. Can you upload your log meesge on yout machine?
( The debug built binary can print log message. )
I suspect "Event: Code: 0x03 Params: -2147024891, 0"
Code 0x03 means EC_ERRORABORT.
wuzhenwu commented May 2, 2017
here is my debug info. I think what u suspected is right. u can dig into the problem,or maybe
u can try a new camera first if possible.
***** VIDEOINPUT LIBRARY - 0.1995 - TFW07 *****
SETUP: Setting up device 0
SETUP: USB2.0 PC CAMERA
SETUP: Couldn't find preview pin using SmartTee
SETUP: Default Format is set to 640x480
SETUP: trying specified format RGB24 @ 640x480
SETUP: trying format RGB24 @ 640x480
SETUP: trying format RGB32 @ 640x480
SETUP: trying format RGB555 @ 640x480
SETUP: trying format RGB565 @ 640x480
SETUP: trying format YUY2 @ 640x480
SETUP: Capture callback set
SETUP: Device is setup and ready to capture.
Event: Code: 0x0d Params: 0, 0
Event: Code: 0x0e Params: 0, 0
joel92217 commented May 9, 2017
I have the same problem. This problem may be caused by Windows Update. Uninstall Windows update KB3150513 solves my problem. For your reference.
2 Answers 2
I converted that mp4 file to an avi file with ffmpeg . Then the above opencv code can play that avi file well.
Therefore I am sure that this is a codec problem.
(I then converted that mp4 file to another mp4 file using ffmpeg , thinking maybe ffmpeg would help turning that original unreadable .mp4 codec into a readable .mp4 codec, but the resulting .mp4 file ended up broken. This fact may or may not relate to this problem, just mentioning, in case anybody needs this information.)
Despite knowing this is a codec problem, I tried many other ways but still couldn't solve it. At last I tried rebuilding ffmpeg and opencv, then the problem was solved!
Following is my detailed rebuilding procedure.
(1) Build ffmpeg
(2) Build Opencv
Now the opencv code should play a mp4 file well!
- Try add WITH_UNICAP=ON WITH_V4L=ON when cmake opencv. But didn't work at all.
- Try changing codec inside the python opencv code. But in vain.
cap = cv2.VideoCapture("MOV_0006.mp4")
print cap.get(cv2.cv.CV_CAP_PROP_FOURCC)
I tested this in two environment. In the first environment the opencv works, and in the other the opencv fails to play a video. But both printed out same codec 828601953.0 .
I tried to change their codec by cap.set(cv2.cv.CV_CAP_PROP_FOURCC, cv2.cv.CV_FOURCC(*'H264')) but didn't work at all.
I grep AVC: nal size and find the libraries contain this error message are opencv-2.4.8/3rdparty/lib/libavcodec.a etc. That's why I tried to replace them. But it turns out that this is a bad idea.
Try to install some that thing and some this thing. But it was totally useless.
I've searched the web and there are many similar problems, but NONE of them had a solution!
Below are problems I think the same as mine.
This one mentions rebuilding ffmpeg ! But the arguments weren't enough for me.
Cannot open “.mp4” video files using OpenCV 2.4.3, Python 2.7 in _Windows 7 machine — from Stack Overflow
OpenCV 2.4 VideoCapture not working on Windows — from Stack Overflow
Первое - не могу понять, как считать код ошибки.
Второе - проверяю существования файл QDir ом. работает
Третье - В системе проигрывается MOV файл.
OpenCV собрана в MinGW, которая по сути линуксовая штука. Может быть QT не видит системных кодеков. Если да, то как то нужно, видимо, их подключать.
PS. В С варианте тоже пробовала и тоже не открывается.
Подобные вопросы люди задавали, но ответа почему-то нет.
Что будет, если mov al,cs:string заменить на mov al,cs
1) В некоторой программе что-то реализуется. Вопрос: что будет если mov al,cs:string заменить на.
Из командной строки файл вообще не открывается а если открыть через проводник, то открывается и сразу вылетает
masm model small stack 256 .data per_1 db 23 per_2 dw 9856 per_3 dd 9875645 per_4 dw.
я конечно не гений,
однако могу предположить, что правильно думаешь.
ты сделал оболочку, а ядро которое будет обрабатывать видео не подключил и не добавил
просто у меня была стычка на с++ билдере. писал браузер на базе хрома, дополнительно качал и компонент и ядро, собственно которое все обрабатывает.
1) Qt, а не QT
2) Не "линуксовая штука", а Unix компилятор.
3) "Может быть QT не видит системных кодеков"?! Вы вызываете OpenCV, при чем тут Qt?
4) Для работы с видео нужно подключить либу ffmpeg, которая идет в комплекте с opencv.
Спасибо за разъяснения и уточнения. И все таки последний шаг:
Как мне эту библиотеку подключить? (я только разбираюсь с Qt, OpenCV и написанием свой программы обработки видео). Какой нибудь пример.
Может opencv_ffmpeg_64.dll нужно зарегестрировать в системе Windows? Или этого не нужно делать, а только прописать в .pro -файле команду (какую).
И кстати такой дополнительный вопрос. В Qt много опций сборки. Создается build-simplecard-Desktop_Qt_5_3_MinGW_32bit-Debug и build-simplecard-Desktop_Qt_5_3_MinGW_32bit-Release, внутри которых в свою очередь тоже папки Release и Debug. и вот когда я запускаю simplecard.exe, то вылетает ошибка - не находит ни одну dll, причем это касается и opencv-библиотке и Qt- библиотеки.
Из Qt-Creator же все запускается.
Где можно прочитать разъяснение к этим нюансам Qt.
А другие opencv либы как вы подключали? Эту так же, через LIBS +=.
Только вам нужна 32 версия либы, а не 64.
В PATH добавить что-ли? Нет.
Qt Creator использует свои переменные окружения. А если вы сами запускаете exe, то все либы должны быть прописаны в PATH или лежать рядом с файлом.
Отсутствующий файл ffmpeg.dll OpenCV не генерирует никаких предупреждений / ошибок в OpenCV 2.3.1, и код автоматически завершается сбоем. Убедитесь, что на вашем пути есть правильная opencv_ffmpeg * .dll.
ответ дан 08 дек '11, 13:12
Меня это тоже мучило пару часов, пока я не увидел такой ответ - Бен Эллисон
У меня была именно эта проблема; независимо от того, какой кодировщик я использовал, он не загружался, пока я не скопировал эту DLL. - Дуг Кавендек
в Windows вам нужно добавить нужную папку, например: opencv\build\..\bin откуда вы извлекли opencv на свой путь. - быстрое умножение
+ все для этого. Это (я обнаружил) также относится к привязкам Java; вам понадобится dll FFmpeg в пути к классам. - Смоллтаун2k
1)
Убедитесь, что видеофайл действительно находится в той же папке, что и приложение (я предполагаю, что вы уже пробовали это), в противном случае укажите абсолютный путь.
2)
Если вы используете Windows, вам может потребоваться пакет кодеков для чтения видеофайла (например, K-Lite Codec Pack).
Как предположил Макмад, AVI - это просто контейнер, который может содержать различные кодеки аудио, видео или даже кодеков с субтитрами. Также, здесь - это сборки Zeranoe FFmpeg для Windows. Вы можете получить дополнительную информацию о содержимом кодека вашего файла, если сделаете следующее:
Вы должны увидеть следующий результат:
Итак, как вы можете видеть, этот контейнер .mp4 имеет видеокодек H.264 и аудиокодек AAC.
ответ дан 07 дек '11, 14:12
Чтобы расширить пункт 1: люди часто делают ошибку, помещая файл изображения (avi, jpg и т. Д.) В ту же папку, что и их исходный код, а не в ту же папку, что и скомпилированная программа. - Стив
Я копирую opencv_ffmpeg310.dll, opencv_ffmpeg310x64.dll и проблема решена. Большое спасибо. - Mesutpiskin
Возможно, вы загрузили неправильный файл библиотеки. Как и я, у меня такая же проблема. Но я могу открыть файл AVI в VC6.0, который использует opencv версии 1.0. Наконец, я обнаружил, что использую неправильную библиотеку.
В режиме отладки , но я использую opencv_core220.lib и opencv_highgui220.lib .И я заменяю их на opencv_core220d.lib и opencv_highgui220d.lib .Теперь я могу это прочитать.
В OpenCV 2.4.4: есть только opencv_ffmpeg244.dll (релиз dll), но не opencv_ffmpeg244d.dll (отладочная dll)
Так что попробуйте в режиме компиляции релиза!
Создан 22 июля '13, 09:07
У меня была такая же проблема с отсутствующей DLL. «Релизная» версия у меня работает как в режиме отладки, так и в режиме выпуска. - cbuchart
Я тоже сталкиваюсь с той же проблемой. С образцом кода для VideoCapture моя программа Visual Studio не смогла открыть ни один видеофайл. Затем предложение nimcap работает для меня. «Отсутствующий файл ffmpeg.dll в OpenCV не генерирует никаких предупреждений / ошибок в OpenCV 2.3.1, и код автоматически завершается сбоем. Убедитесь, что на вашем пути есть правильная opencv_ffmpeg * .dll».
Решение: скопируйте opencv_ffmpeg.dll в мой проект Visual Studio. /Debug папку, я могу открыть практически любой видеофайл с помощью VideoCapture.
Под Windows x64, вам не нужно ничего переименовывать. Просто поставьте следующее . \ opencv \ build \ x64 \ vc12 \ bin в вашей PATH.
Я просто добавляю к этому, потому что потратил больше времени, чем хотел бы признаться. Невозможность открыть файл вызвала массу странных исключений.
Если вы обнаружите, что абсолютные пути работают, а относительные пути не работают, еще одна вещь, которую необходимо проверить, - убедиться, что рабочий каталог установлен правильно.
В Visual Studio это Свойства проекта (Свойства конфигурации) -> Отладка -> Рабочий каталог. Я обнаружил, что мой по умолчанию установлен на «$ (ProjectDir)», когда мне действительно нужен «$ (OutDir)».
ответ дан 15 окт '17, 16:10
Для тех, кто не нашел решения: В openCV4 и в режиме «отладки» выполните следующие действия:
Перейдите в opencv \ build \ x64 \ vc15 \ bin
Скопируйте opencv_videoio_ffmpeg440_64.dll в папку отладки вашего проекта.
ответ дан 14 мар '21, в 07:03
ответ дан 05 мая '12, 18:05
Просто измените свой код следующим образом:
Создан 11 июля '16, 23:07
Откройте D:\OpenCV\build\x64\vc14\bin и скопировать opencv_ffmpeg320.dll or opencv_ffmpeg320_64.dll что актуально для вас в зависимости от вашего Windows (x86 or x64) .
opencv_ffmpeg320.dll -> для 32-bit Windows (x86)
opencv_ffmpeg320_64.dll -> для 64-bit Windows (x64)
Вставьте скопированный .dll в C:\Python27\ или любое место, доступное из Windows PATH переменные среды.
В качестве альтернативы вы можете создать папку D:\OpenCV\vendor\ и добавить .dll файл в эту папку, а затем добавьте D:\OpenCV\vendor\ . windows environment variables .
Techkid86 commented May 9, 2017
I had uninstalled the most recent windows updates, restarted, and it remained inoperable. only recently (yesterday) did it start working again. Maybe it needed several restarts? I also added the registry fix that helped when windows 10 anniversary update had broken webcams, as well as turned off the permissions for "Apps" to use the webcam. From what I could find, that event code is a lack of permission for webcam access. It was certainly a windows problem, but idk what solved the issue for me.
I'm using Python bindings to OpenCV 2.4 installed with following instructions.
My problem is similar to this one, but I need Windows machine solution.
Problem: when I try to use
it works fine, but the following code
always return False.
Path to the file is correct, absolute and has no spaces.
I tried on two machines with Windows XP and Windows 7 with similar results. On Linux (Ubuntu) it works fine for me.
It was "C:\\m.avi" , but I just tried "C:\m.avi" and "C:/m.avi" . It still not working (with and without os.path.join ).
Check if opencv_ffmpeg.dll is in the same directory that other OpenCV dlls used by python. Also, try another avi file. Sometimes OpenCV can't decode files that are correctly played by other programs (ex. Windows Media Player)
I didn't find any files with "opencv" in a name on my computer (except opencv folder and it's contents of course). So I just tried to copy opencv_ffmpeg.dll to C:\Python27\Lib\site-packages` (like cv2.pyd`) but it doesn't work.
Techkid86 commented May 7, 2017
Same problem. Code that worked only a few days ago does not work now after a forced update (windows 10)
same -2147024891 Event code parameters. Even after uninstalling the updates manually, the problem remains. Either windows changed something in the registry somewhere, or the updates are not contained to what "Programs and Features" can uninstall. Additionally, my cameras (both built in and external logitech C270) work when accessed by skype, but crash when accessed by a program called GRIP. GRIP complains that "CameraService Crashed".
GRIP is an openCV integrated program written in java
crashes with this stacktrace. Hope this helps.
Читайте также: