Video file not opening?(opencv 3.1.0 windows) - opencv

import cv2
cap = cv2.VideoCapture("StopMoti2001.mpeg")
if cap.isOpened():
print 'fine'
else:
print 'not fine'
output is 'not fine' I have checked for various videos and I also moved the ffmpeg file moving to PATH and still the problem remains same. can you please suggest a solution

Solved my problem, Actually I was working in anaconda, so instead of moving ffmpeg to Python27, I should move it to Anaconda dll folder to make it work.

Related

OperationalError: no such module: fts4

Hi I´ve tried to run a fuzzymatcher code and the error below pops up:
OperationalError: no such module: fts4
Any suggestions? Thanks in advance
Edit: I've already tried downloading the sqlite zip from the website and saving it in DLLs files but it still does not work. Do I have to activate it somehow?
I´m using Anaconda3 64 bit.
Thanks
Confirm that the DLL files have been added in the correct place; if you are using Windows it will be C:\ProgramData\Anaconda3\DLLs.
you can try to load the extensions:
import sqlite3
conn = sqlite3.connect(':memory:')
cur = conn.cursor()
conn.enable_load_extension(True)
for (val,) in cur.execute('pragma compile_options'):
print (val)
It will show some results similar to these:
COMPILER=msvc-1500
ENABLE_BYTECODE_VTAB
ENABLE_COLUMN_METADATA
ENABLE_DBSTAT_VTAB
ENABLE_FTS3
ENABLE_FTS4
ENABLE_FTS5
ENABLE_GEOPOLY
ENABLE_JSON1
ENABLE_RTREE
ENABLE_STMTVTAB
MAX_TRIGGER_DEPTH=100
TEMP_STORE=1
THREADSAFE=1
As mentioned by #Ahmed and #Jeremy in the previous answer,
Confirm that the DLL files have been added in the correct place
However, make sure that it is indeed the correct place. For example, if you're working in a virtual environment, the location is not C:\ProgramData\Anaconda3\DLLs.
Check where python is installed to find the correct place.
You can copy the downloaded sqlite files in C:\Users\ (usernamefolder)\anaconda3\DLLs and check for the enabled extensions using the following syntax in jupyter notebook.
import sqlite3
conn = sqlite3.connect(':memory:')
cur = conn.cursor()
conn.enable_load_extension(True)
for (val,) in cur.execute('pragma compile_options'):
print (val)
This will give the list of extensions which are enabled and FTS-4 will be one of them. In case you tried and it still hasn't been enabled you can uninstall and reinstall anaconda package and try repeating the procedure.
This is what worked for me
install this in anacoda prompt using the comand below
conda install -c conda-forge sqlite-fts4

Saving an image to another folder of my choice (with "~") using OpenCV

I am a few images in the "Downloads" folder. I want to save the images to a particular folder named "unclassified" using OpenCV. I have already seen the question OpenCV - Saving images to a particular folder of choice and from that I have tried this particular code:
import cv2
import os
img = cv2.imread('1.jpg', 1)
path = '~/Downloads/unclassified'
cv2.imwrite(os.path.join(path , 'waka.jpg'),img)
cv2.waitKey(0)
This works on Windows but it didn't work on Ubuntu (I am working on a Ubuntu 16.04) when I wrote:
cv2.imwrite(os.path.join(path , 'waka.jpg'), img)
The code returned False on Ubuntu. What should I do to solve this error?
You can use something like that:
cv2.imwrite(os.path.expanduser(os.path.join(path , 'waka.jpg')), img)
The problem is with the "~". os.path.expanduser(...) will change that with the appropriate path.

cv2.imshow() function is opening a window that always says not responding - python opencv

I am trying to run a very simple program. To open and jpg file and display it using the opencv library for python. Initially it all worked fine but now it just opens a window which doesn't show the image but says 'not responding'. I need to go to the task manager and close it!
from numpy import *
import matplotlib as plt
import cv2
img = cv2.imread('amandapeet.jpg')
print img.shape
cv2.imshow('Amanda', img)
You missed one more line:
cv2.waitKey(0)
Then the window shows the image until you press any key on keyboard. Or you can pass as following:
cv2.waitKey(1000)
cv2.destroyAllWindows()
Here, window shows image for 1000 ms, or 1 second. After that, the window would disappear itself. But in some cases, it won't. So you can forcefully destroy it using cv2.destroyAllWindows()
Please read more tutorials first : http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html
None of the answers here worked in MacOS. The following works:
Just add a cv2.waitKey(1) after cv2.destroyAllWindows().
Example:
import cv2
image = cv2.imread('my_image.jpg')
cv2.imshow('HSV image', hsv_image); cv2.waitKey(0); cv2.destroyAllWindows(); cv2.waitKey(1)
The solution that worked for me:
Switch from inline graphics to auto. It worked both in Spyder and in Jupyter notebooks.
To change Spyder setting:
Go to Tools > Preferences > IPhyton console > Graphics > Backend: Automatic
(Change backend from Inline to Automatic)
To change Notebook setting:
Enter command:
%matplotlib auto
Some background for my case (for those who may be quick to judge):
It used to work fine: I could open an image, it would load, and it would be responsive (doesn't say "Not responding", can close, focus, etc.) Then I installed some packages and ran some demo notebooks that apparently messed up some settings (Spyder open files were reset too).
I tried adding waitKey(1) (and 0, 30, 1000, etc values too). It made the image load, at least. But the image frame was "Not Responding": didn't refresh, couldn't close, didn't come to top, etc. Had to close using cv2.destroyAllWindows().
Note that everything worked fine during the duration of waitKey. I put this in a loop that shows the same image in the same named window and waits for a few seconds. During the loop everything works fine. As soon as the loop ends, the image window is "Not responding" (which looks like a GUI thread issue). I tried using cv2.startWindowThread(), and didn't make any difference.
Finally, changing from Inline graphics to Auto brought everything back to order.
I've been working with opencv 3.2 and matplotlib too recently and discovered (through trial and error of commenting out lines) that the import of pyplot from matplotlib has some sort of interference with the cv2.imshow() function. I'm not sure why or how it really works but in case anyone searches for this issue and comes across this old forum, this might help. I'm working to try to find a solution around this interference bu
I did also face the same issue. I am running through command line python prompt in centos 7 with the following code
>> import cv2, numpy as np
>> cap=cv2.VideoCapture(0)
>> img=cap.read()
>> cap.release()
>> cv2.imshow('image',img[1])
>> cv2.waitKey(0)
>> cv2.destroyAllWindows()
>> cv2.waitKey(1)
Even then the problem persisted and didn't solve. So I added
>> cv2.imshow('image',img[1])
Adding this did close the image window.Running the command again would create a new instance. Hope you can try if you still face any issues.
The cv2.imshow() function always takes two more functions to load and close the image. These two functions are cv2.waitKey() and cv2.destroyAllWindows(). Inside the cv2.waitKey() function, you can provide any value to close the image and continue with further lines of code.
# First line will provide resizing ability to the window
cv.namedWindow('Amanda', cv.WINDOW_AUTOSIZE)
# Show the image, note that the name of the output window must be same
cv.imshow('Amanda', img)
# T0 load and hold the image
cv.waitKey(0)
# To close the window after the required kill value was provided
cv.destroyAllWindows()
Hoping that you will get the image in a separate window now.
I've installed opencv-contrib-python library instead of opencv-python and now cv2.imshow() function works as expected.
If you have used python notebooks then there is a problem in using cv2.waitKey(0) and cv2.destroyallwindows() in Unix based system to run a program of opencv.
I have an alternative method which would prevent from freezing your image
Steps: -Copy the code from python notebooks and create new filename.py and paste it
- Open terminal
- cd path/to/file
- source activate VirtualEnvironment
- python filename.py
This will run code directly from terminal. Hope this helps you. Example Link: https://youtu.be/8O-FW4Wm10s
I was having this same error until I added the below lines of code. For the waitKey, you can input figures above 0(i.e 1, 100 and above). It serves as the delay time for the window and it is in milliseconds.
----> cv2 waitKey(0)
----> cv2 destroyAllWindows()
I found that i had a breakpoint on the
cv2.waitkey()
funtion. removing that fixed the issue for me
As I tried all solutions mentioned above, it works for displaying an image but in my case, I want to display the video not just the single image in the window, So to solve the problem added
k=cv2.waitkey(10)
if k == 27:
break
after cv2.imshow('title',img)

OpenCV 2.4.3 VideoCapture is not working

Recently I migrated to OpenCV 2.4.3 from OpenCV 2.4.1.
My program which worked well with 2.4.1 version now encounters problem with 2.4.3.
The problem is related to VideoCapture that can not open my video file.
I saw a similar problem while searching the internet, but I couldn't find a proper solution for this. Here is my sample code:
VideoCapture video(argv[1]);
while(video.grab())
{
video.retrieve(imgFrame);
imshow("Video",ImgFrame);
waitKey(1);
}
It's worth mentioning that capturing video from webcam device works well, but I want to grab stream from file.
I'm using QT Creator 5 and I compiled OpenCV with MinGW. I'm using Windows.
I tried several different video formats and I rebuilt OpenCV with and without ffmpeg, but the problem still persists.
Any idea how to solve the problem?
Try this:
VideoCapture video(argv[1]);
int delay = 1000.0/video.get(CV_CAP_PROP_FPS);
while(1)
{
if ( !video.read(ImgFrame)) break;
imshow("Video",ImgFrame);
waitKey(delay);
}
In my experience with OpenCV I struggled using IP cams until my mentor discovered how to get them to work, don't forget to plug your IP address in otherwise it won't work!
import cv2
import numpy as np
import urllib.request
# Sets up the webcam and connects to it and initalizes a variable we use for it
stream=urllib.request.urlopen('http://xx.x.x.xx/mjpg/video.mjpg')
bytes=b''
while True:
# Takes frames from the camera that we can use
bytes+=stream.read(16384)
a = bytes.find(b'\xff\xd8')
b = bytes.find(b'\xff\xd9')
if a!=-1 and b!=-1:
jpg = bytes[a:b+2]
bytes= bytes[b+2:]
frame = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR)
img = frame[0:400, 0:640] # Camera dimensions [0:WIDTH, 0:HEIGHT]
# Displays the final product
cv2.imshow('frame',frame)
cv2.imshow('img',img)
# Hit esc to kill
if cv2.waitKey(1) ==27:
exit(0)

Problems converting video to pictures using python 2.7

Tried a lot of options and am running out of ideas. I was hoping someone here could help. I am trying to write some code in python that will extract frames (say every tenth frame) from a video (.avi or .wmv) and create a picture (.jpg preferably - but other formats will do). I have had no success and was wondering if someone could assist me in solving my problem by providing an alternative to what I have tried and failed.
I have tried PyMedia (the example in their tutorial http://pymedia.org/tut/src/dump_video.py.html does not work - the program bombs out when it looks for the video codecs):
#dm= muxer.Demuxer( inFile.split( '.' )[ -1 ] ) This line does not work
dm= muxer.Demuxer( 'avi' ) #This modified line does seem to work however
i= 1
inFile = "VideoTest.avi"
f= open( inFile, 'rb' )
s= f.read( 400000 )
r= dm.parse( s )
v= filter( lambda x: x[ 'type' ]== muxer.CODEC_TYPE_VIDEO, dm.streams )
v_id= v[ 0 ][ 'index' ]
print 'Assume video stream at %d index: ' % v_id
c= vcodec.Decoder( dm.streams[ v_id ] ) #this is the point where it crashes.
I have tried OpenCV v2.2 for Python but that doesn't work either (I can get most of OpenCV to work - except the one function, CaptureFromFile, that I need does not work). I believe the reason this function doesn't work is because on Windows it requires highGui to operate and for some reason, python and opencv cannot find highgui eventhough it is in the correct directory. I also understand OpenCV has issues with finding and applying correct video codecs so I am not sure which is the cause of my problem.
I have looked at pyFFMPEG but the last build for that was version 2.6 and I am running python 2.7.
I am running this on Windows Vista and Windows 7 machines, have Python 2.7 and OpenCV 2.2 loaded on C:\ and all other python packages (pygames, pymedia, numpy, scipy) installed in C:\python27\Libs\site-packages..." I downloaded and installed from executables, all packages were built for python 2.7. My Path variable includes Python27 and OpenCV and I have a PYTHONPATH variable.
Thanks for any ideas or recommendations.
I tried the following to extract each frames as a separate image:
import cv2
file_path = "some\path\to\the\file.avi"
video_object = cv2.VideoCapture(path)
success = True
while success:
success,frame = video_object.read()
if success:
cv2.imwrite(path[:-4]+"_"+str(i)+".jpg",frame)
print("Done!")
This script saves each frame as an image in the same folder as the source file. It may not be the most efficient way to do this, but it works for me! I know my string parsing is not the most recommended, but it works.
video_object.read() returns two object. The first is a bool indicating whether the reading operation was a success or not, and the second is the image.
There may be limitations with respect to the video codec, of which I am not aware. I'm using Python 2.7 with the most recent version of openCV and Numpy as of 11/7/2013.

Resources