I am using Python 2.7.11 and OpenCV 2.4.9. I cannot read a video by using cv2.imread() or cv2.VideoCapture().
import cv2
cap = cv2.VideoCapture('cam.avi')
print ("open = ",cap.isOpened())
OR
import cv2
cap = cv2.imread('cam.avi')
print ("open = ",cap.isOpened())
It will return false.
I don't know why. I am sure that the cam.avi is here.
imread() does not support reading from video files directly.
See also the documentation of OpenCV.
If you want to read a video with imread you will first have to convert it to single images, either via a serperate program (ffmpeg comes to mind) or using OpenCV and store the images in memory.
Try providing full path to video, like:
import cv2
cap = cv2.VideoCapture(r'C:\Users\e01069\Downloads\drop.avi')
print ("open = ",cap.isOpened())
If you run following in your same file, you would know that python is looking for your file on some different location.
import os
print os.path.abspath(__file__) #this is your current working directory
Note: .imread wouldn't work this way.
Related
I'm a beginner in python and I'm trying to send someone my small python program together with a picture that'll display when the code is run.
I tried to first convert the image to a binary file thinking that I'd be able to paste it in the source code but I'm not sure if that's even possible as I failed to successfully do it.
You can base64-encode your JPEG/PNG image which will make it into a regular (non-binary string) like this:
base64 -w0 IMAGE.JPG
Then you want to get the result into a Python variable, so repeat the command but copy the output to your clipboard:
base64 -w0 IMAGE.JPG | xclip -selection clipboard # Linux
base64 -w0 IMAGE.JPG | pbcopy # macOS
Now start Python and make a variable called img and paste the clipboard into it:
img = 'PASTE'
It will look like this:
img = '/9j/4AAQSk...' # if your image was JPEG
img = 'iVBORw0KGg...' # if your image was PNG
Now do some imports:
from PIL import Image
import base64
import io
# Make PIL Image from base64 string
pilImage = Image.open(io.BytesIO(base64.b64decode(img)))
Now you can do what you like with your image:
# Print its description and size
print(pilImage)
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=200x100>
# Save it to local disk
pilImage.save('result.jpg')
You can save a picture in byte format inside a variable in your program. You can then convert the bytes back into a file-like object using the BytesIO function of the io module and plot that object using the Image module from the Pillow library.
import io
import PIL.Image
with open("filename.png", "rb") as file:
img_binary = file.read()
img = PIL.Image.open(io.BytesIO(img_binary))
img.show()
To save the binary data inside your program without having to read from the source file you need to encode it with something like base64, use print() and then simply copy the output into a new variable and remove the file reading operation from your code.
That would look like this:
img_encoded = base64.encodebytes(img_binary)
print(img_binary)
img_encoded = " " # paste the output from the console into the variable
the output will be very long, especially if you are using a big image. I only used a very small png for testing.
This is how the program should look like at the end:
import io
import base64
import PIL.Image
# with open("filename.png", "rb") as file:
# img_binary = file.read()
# img_encoded = base64.encodebytes(img_binary)
img_encoded = b'iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABX[...]'
img = PIL.Image.open(io.BytesIO(base64.decodebytes(img_encoded)))
img.show()
You could perhaps have your Python program download the image from a site where you upload files such as Google Drive, Mega, or Imgur. That way, you can always access and view the image easily without the need of running the program or for example converting the binary back into the image in the method you mentioned.
Otherwise, you could always store the image as bytes in a variable and have your program read this variable. I'm assuming that you really wish to do it this way as it would be easier to distribute as there is only one file that needs to be downloaded and run.
Or you could take a look at pyinstaller which is made for python programs to be easily distributed across machines without the need to install Python by packaging it as an executable (.exe) file! That way you can include the image file together by embedding it into the program. There are plenty of tutorials for pyinstaller you could google up. Note: Include the '--onefile' in your parameters when running pyinstaller as this will package the executable into a single file that the person you're sending it to can easily open whoever it may be-- granted the executable file can run on the user's operating system. :)
Im back with another probably stupid question!, my new issue is the following:
im trying to save a picture from my webcam into a specific folder using OpenCV imwrite,
its not working obviously here is my code:
import cv2 as cv
cam = cv.VideoCapture(0)
s, img = cam.read()
if s:
path = r"\imgtest\selfietest.jpg"
cv.imwrite(path, img)
Any suggestions for edits or fixes?, i've tried copying the file using shutil and moving it using the same module, i also tried to use the OS module to move it but it threw an "Access Denied" error so i would prefer to not need to grant the application admin rights every time i launched it thanks in advance!!
((ALSO ASSUME I KNOW NOTHING ABOUT PYTHON))
Use a full path, forward slashes, and r'' to pass a raw path. cv2.imwrite(r"D:/....jpg", img)
I have a Python program with a video file reader scenario. To do this, I use the FileVideoStream API from the library imutils.video as follows
from imutils.video import FileVideoStream
import time
import numpy as np
import cv2
vs = FileVideoStream('~/Downloads/capture.webm').start()
time.sleep(1.0)
while True:
if not vs.more():
print("vs", vs.more())
vs.stop()
break
print("vs", vs.more())
frame = vs.read()
The problem is the location "~/Downloads/capture.webm" is not recognized by the FileVideoStream function even the video file is exists in the mentioned directory.
ERROR: OpenCV: Couldn't read video stream from file "~/Downloads/capture.webm"
But when I save the video in the same python project directory and call as "capture.webm" it works!
And also the function doesn't recognize videos from a URL.
How can I solve this?
Completion for ~ inside path ~/Downloads/capture.webm is done by bash/sh/etc.. If you are using python you have to use full path /home/username/Downloads/capture.webm.
You can also use os.environ.get('USER') to get current USER name and insert it inside full path. For example
'/home/%s/Downloads/capture.webm' % os.environ.get('USER')
I'm using the following code to open a video stream:
import cv2
video = cv2.VideoCapture()
video.open("some_m3u8_link")
success, image = video.read()
However, even if the code works as intended locally, on Heroku success is always false.
I'm using cedar-14 stack with the following buildpacks:
heroku/python
https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git
(I tried several buildpack options for ffmpeg)
Running ffmpeg --version on heroku instance will return ffmpeg version 4.0-static https://johnvansickle.com/ffmpeg/
Is there any setting/configuration I missed in order to make it work on deployment? Thank you!
Later edit: I tried several links for "some_m3u8_link" including from twitch and other streaming services (including traffic streaming li
An example for reproducing:
python -c "import cv2; video=cv2.VideoCapture(); video.open('https://hddn01.skylinewebcams.com/live.m3u8?a=5tm6kfqrhqbpblan9j5d4bmua4'); success, image = video.read(); print(success)"
Returns True on local machine and False on Heroku.
(the link is taken from here)
You can use pafy module with cv2
-try opencv3 if its not working with cv2
import cv2, pafy
url = "Some url to stream"
video = pafy.new(url)
best = video.getbest(preftype="webm")
video=cv2.VideoCapture(best.url)
pafyPYPI
You can try this:
import cv2
video = cv2.VideoCapture("some_m3u8_link")
success, image = video.read()
Specifying the mode to open it might work.
video.open("some_m3u8_link", "r")
If that doesn't work then specifying the file extension might help.
You might also need to make a variable equal to the function
Ex:
""" replace .mp4 with the applicable file type,
I don't know if you need to specify file mode"""
import cv2
video = cv2.VideoCapture()
video = video.open("some_m3u8_link.mp4")
success, image = video.read()
If this doesn't work then I am out of ideas.
I've looked around and read the docs, and found no way or solution, so I ask here. Is there any packages available to use Python to convert a JPG image to a PNG image?
You could always use the Python Image Library (PIL) for this purpose. There might be other packages/libraries too, but I've used this before to convert between formats.
This works with Python 2.7 under Windows (Python Imaging Library 1.1.7 for Python 2.7), I'm using it with 2.7.1 and 2.7.2
from PIL import Image
im = Image.open('Foto.jpg')
im.save('Foto.png')
Note your original question didn't mention the version of Python or the OS you are using. That may make a difference of course :)
Python Image Library: http://www.pythonware.com/products/pil/
From: http://effbot.org/imagingbook/image.htm
import Image
im = Image.open("file.png")
im.save("file.jpg", "JPEG")
save
im.save(outfile, options...)
im.save(outfile, format, options...)
Saves the image under the given filename. If format is omitted, the
format is determined from the filename extension, if possible. This
method returns None.
Keyword options can be used to provide additional instructions to the
writer. If a writer doesn't recognise an option, it is silently
ignored. The available options are described later in this handbook.
You can use a file object instead of a filename. In this case, you
must always specify the format. The file object must implement the
seek, tell, and write methods, and be opened in binary mode.
If the save fails, for some reason, the method will raise an exception
(usually an IOError exception). If this happens, the method may have
created the file, and may have written data to it. It's up to your
application to remove incomplete files, if necessary.
As I searched for a quick converter of files in a single directory, I wanted to share this short snippet that converts any file in the current directory into .png or whatever target you specify.
from PIL import Image
from os import listdir
from os.path import splitext
target_directory = '.'
target = '.png'
for file in listdir(target_directory):
filename, extension = splitext(file)
try:
if extension not in ['.py', target]:
im = Image.open(filename + extension)
im.save(filename + target)
except OSError:
print('Cannot convert %s' % file)
from glob import glob
import cv2
pngs = glob('./*.png')
for j in pngs:
img = cv2.imread(j)
cv2.imwrite(j[:-3] + 'jpg', img)
this url: https://gist.github.com/qingswu/1a58c9d66dfc0a6aaac45528bbe01b82
import cv2
image =cv2.imread("test_image.jpg", 1)
cv2.imwrite("test_image.png", image)
I don't use python myself, but try looking into:
http://www.pythonware.com/products/pil/
import Image
im = Image.open("infile.png")
im.save("outfile.jpg")
(taken from http://mail.python.org/pipermail/python-list/2001-April/700256.html )