Opencv videowriter doesn't save video on flask - python

i'm trying to save the output video.mp4 file to my dirc. it works individually, so i think my code is not wrong...
but when i use the function on app.py. the terminal is showing, it is processing. but i can't get actual video.mp4 file.
what is the problem of this?
this is original source function what i'm trying
def video():
pathIn=''
pathOut = ''
fps = 10
frame_array = []
files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]
#for sorting the file names properly
files.sort(key = lambda x: x[5:-4])
files.sort()
----------
for i in range(len(files)):
filename=pathIn + files[i]
#reading each files
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width,height)
#inserting the frames into an image array
frame_array.append(img)
out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'avc1'), fps, size)
for i in range(len(frame_array)):
# writing to a image array
out.write(frame_array[i])
i tried individually the code and searched a lot about flask.
another function from other py is working well on flask. but only this opencv is not working.
from make_vid import video
#app.route('/upload_gpx', methods=["GET", "POST"])
def upload_gpx():
video()
return render_template('public/display_vid.html')
and my terminal shows
OpenH264 Video Codec provided by Cisco Systems, Inc.
this. so i think the video() is worked but i can't get my video.
only when i run the makevid.py, i can get my video.
i need help that how can i get the video using video() function on flask??

Related

The document could not be opened, opencv python3

I'm trying to make a video from images with python and OpenCV but when I run the script the video is generated but when I try to open it I give this error:
This is the script:
import cv2
import numpy as np
import glob
frameSize = (1920, 1080)
out = cv2.VideoWriter('output_video.avi',cv2.VideoWriter_fourcc(*'DIVX'), 60, frameSize)
for filename in glob.glob('/folder_path/*.jpg'):
img = cv2.imread(filename)
out.write(img)
out.release()
UPDATE:
If I use
out = cv2.VideoWriter('output_video.avi',cv2.VideoWriter_fourcc(*'MJPG'), 60, frameSize)
Instead
out = cv2.VideoWriter('output_video.avi',cv2.VideoWriter_fourcc(*'DIVX'), 60, frameSize)
The video start but I can see anything
Ok, I have found a solution.
This is the final code:
import cv2,os
from os.path import isfile, join
def convert_pictures_to_video(pathIn, pathOut, fps, time):
# this function converts images to video
frame_array=[]
files=[f for f in os.listdir(pathIn) if isfile(join(pathIn,f))]
#files.remove(".DS_Store")
for i in range (len(files)):
filename=pathIn+files[i]
# reading images
img=cv2.imread(filename)
# img=cv2.resize(img,(1400,1000))
height, width, layers = img.shape
size=(width,height)
for k in range (time):
frame_array.append(img)
out=cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'mp4v'), fps, size)
for i in range(len(frame_array)):
out.write(frame_array[i])
out.release()
pathIn= '/pathIn-folder/'
pathOut='/pathOut-folder/output.avi'
fps=1
time=20 # the duration of each picture in the video
convert_pictures_to_video(pathIn, pathOut, fps, time)
You can find more info and a tutorial here.
REMEMBER
If you have a mac there are two important things to do.
First you have to uncomment #files.remove(".DS_Store") because when you create a new folder on macOS there is an extra hidden file called .DS_Store
You can't open the output video with Quick Time Player
You have to use another software like VLC

recognise.train(face, np.array(ids)) Empty training data was given You'll need more than 1 sample to learn a model. in function 'cv:face:LBPH::train'

I'm currently doing a project but I'm running into an error.
I'm using python 3.9, opencv-contrib and I have installed the required libraries
The project is a face recognition project. First, I ran a code to open the webcam and another one to identify a face and make a square and these two codes are working fine. I also uploaded around 20 sample pictures in a file called image.
Now the other code that I ran is used to train python for the faces. This is the following code:
# import the required libraries
import cv2
import os
import numpy as np
from PIL import Image
import pickle
cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
recognise = cv2.face.LBPHFaceRecognizer_create()
# Created a function
def getdata():
current_id = 0
label_id = {} #dictionanary
face_train = [] # list
face_label = [] # list
# Finding the path of the base directory i.e path were this file is placed
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# We have created "image_data" folder that contains the data so basically
# we are appending its path to the base path
my_face_dir = os.path.join(BASE_DIR,'image_data')
# Finding all the folders and files inside the "image_data" folder
for root, dirs, files in os.walk(my_face_dir):
for file in files:
# Checking if the file has extention ".png" or ".jpg"
if file.endswith("png") or file.endswith("jpg"):
# Adding the path of the file with the base path
# so you basically have the path of the image
path = os.path.join(root, file)
# Taking the name of the folder as label i.e his/her name
label = os.path.basename(root).lower()
# providing label ID as 1 or 2 and so on for different persons
if not label in label_id:
label_id[label] = current_id
current_id += 1
ID = label_id[label]
# converting the image into gray scale image
# you can also use cv2 library for this action
pil_image = Image.open(path).convert("L")
# converting the image data into numpy array
image_array = np.array(pil_image, "uint8")
# identifying the faces
face = cascade.detectMultiScale(image_array)
# finding the Region of Interest and appending the data
for x,y,w,h in face:
img = image_array[y:y+h, x:x+w]
#image_array = cv2.rectangle(image_array,(x,y),(x+w,y+h),(255,255,255),3)
cv2.imshow("Test",img)
cv2.waitKey(1)
face_train.append(img)
face_label.append(ID)
# string the labels data into a file
with open("labels.pickle", 'wb') as f:
pickle.dump(label_id, f)
return face_train,face_label
# creating ".yml" file
face,ids = getdata()
recognise.train(face, np.array(ids))
recognise.save("trainner.yml")
After running the code I get the following error:
Traceback (most recent call last):
File "C:\Users\person\Desktop\WebcamRecognition\face_trainer.py", line 76, in <module>
recognise.train(face, np.array(ids))
cv2.error: OpenCV(4.5.4-dev) D:\a\opencv-python\opencv-python\opencv_contrib\modules\face\src\lbph_faces.cpp:362: error: (-210:Unsupported format or combination of formats) Empty training data was given. You'll need more than one sample to learn a model. in function 'cv::face::LBPH::train'
Anyone knows how to solve this error.

Image magick with python on windows giving CorruptImageError: unable to read image data

Hi I am facing issues while trying to convert PDF files to .jpeg
I am running python from anaconda distribution on windows machine.
Below is the code that is working for some of the pdfs
import os
from wand.image import Image as wi
pdf_dir = r"C:\\Users\Downloads\python computer vison\Computer-Vision-with-Python\pdf_to_convert"
os.chdir(pdf_dir)
path = r"C:/Users/Downloads/python computer vison/Computer-Vision-with-Python/jpeg_extract/"
for pdf_file in os.listdir(pdf_dir):
print("filename is ",pdf_file)
pdf = wi(filename=pdf_file,resolution=300)
#print("filename is ",pdf_file)
pdfImage = pdf.convert("jpeg")
i = 1
for img in pdfImage.sequence:
page = wi(image=img)
page.save(filename=path+pdf_file+str(i)+".jpg")
i+=
and below is the output
filename is tmpdocument-page0.pdf
filename is tmpdocument-page1.pdf
filename is tmpdocument-page100.pdf
filename is tmpdocument-page1000.pdf
filename is tmpdocument-page1001.pdf
filename is tmpdocument-page1002.pdf
filename is tmpdocument-page1003.pdf
filename is tmpdocument-page1004.pdf
filename is tmpdocument-page1005.pdf
filename is tmpdocument-page1006.pdf
filename is tmpdocument-page1007.pdf
filename is tmpdocument-page1008.pdf
filename is tmpdocument-page1009.pdf
filename is tmpdocument-page1012.pdf
---------------------------------------------------------------------------
CorruptImageError Traceback (most recent call last)
<ipython-input-7-84715f25da7c> in <module>()
8 #path = r"C://Users/Downloads/Work /ml_training_samples/tmp/"
9 print("filename is ",pdf_file)
---> 10 pdf = wi(filename=pdf_file,resolution=300)
11 #print("filename is ",pdf_file)
12 pdfImage = pdf.convert("jpeg")
~\Anaconda3\envs\python-cvcourse\lib\site-packages\wand\image.py in __init__(self, image, blob, file, filename, format, width, height, depth, background, resolution, pseudo)
4706 self.read(blob=blob, resolution=resolution)
4707 elif filename is not None:
-> 4708 self.read(filename=filename, resolution=resolution)
4709 # clear the wand format, otherwise any subsequent call to
4710 # MagickGetImageBlob will silently change the image to this
~\Anaconda3\envs\python-cvcourse\lib\site-packages\wand\image.py in read(self, file, filename, blob, resolution)
5000 r = library.MagickReadImage(self.wand, filename)
5001 if not r:
-> 5002 self.raise_exception()
5003
5004 def save(self, file=None, filename=None):
~\Anaconda3\envs\python-cvcourse\lib\site-packages\wand\resource.py in raise_exception(self, stacklevel)
220 warnings.warn(e, stacklevel=stacklevel + 1)
221 elif isinstance(e, Exception):
--> 222 raise e
223
224 def __enter__(self):
CorruptImageError: unable to read image data `C:/Users/AppData/Local/Temp/magick-40700dP2k-1ORw81R1' # error/pnm.c/ReadPNMImage/1346
bach ground
so i have a pdf Image document i named as tmpdocument which has over 2200 pages so i split them using python into individual pdf documents.Now I am trying to convert them into jpeg.
problem:
so when I am trying to convert the pdf's into jpeg some of the pages are successful and some page fa9.ils with the above error since all these pages are from same document i highly doubt this is an format issue. also I am able to open and view the image in adobe so i'm sure that page is not corrupted.
Lastly Image magic takes so much disk space and then this issue I am truly lost is there any other way to achieve the above scenerio any inputs would be helpful.
Thanks.
Updated
Thanks for the reply.
Yes I am using ghostscript 9.26. The pdf is kinda sensitive data so I cant post online unfortunately. temp folder is 18mb so i think that is okay.
I have found some code online it is generating the jpeg files but replacing them rather than creating new files i have never done any subprocess before and there is no visibility in this code if program is running or failed or how to kill it any inputs here also appreciated.
I understand it is not using image magick anymore still I am okay as long as i can generate jpeg.
import os, subprocess
pdf_dir = r"C:\\Users\Downloads\latest_python\python computer vison\Computer-Vision-with-Python\pdf_to_convert"
os.chdir(pdf_dir)
pdftoppm_path = r"C:\Program Files\poppler-0.68.0_x86\poppler-0.68.0\bin\pdftoppm.exe"
i = 1
for pdf_file in os.listdir(pdf_dir):
if pdf_file.endswith(".pdf"):
subprocess.Popen('"%s" -jpeg %s out' % (pdftoppm_path, pdf_file))
i+=1

How to export video as .mp4 using openCV?

I am trying to export video as .mp4 with openCV. I have tried several codecs but for now I had no success.
This is a function that constructs a video from frames:
def create_movie(self, out_directory, fps, total_frames):
img1 = cv2.imread("temp/scr0.png")
height, width, layers = img1.shape
codec = cv2.cv.CV_FOURCC('X','V','I','D')
video = cv2.VideoWriter(out_directory, codec, fps, (width, height))
for i in range(total_frames):
img_name = "temp/scr" + str(i) + ".png"
img = cv2.imread(img_name)
video.write(img)
video.release()
cv2.destroyAllWindows()
I usually get next error message, using different codecs:
Tag XVID/0x44495658 incompatible with output codec id '13'
Is is possible to do this and how?
There is a non-direct solution. You export as .avi and then convert to .mp4 using python's call which calls terminal command.
from subprocess import call
dir = out_directory.strip(".avi")
command = "avconv -i %s.avi -c:v libx264 -c:a copy %s.mp4" % (dir, dir)
call(command.split())
May be a little bit late to answer this, but if you want to write an .MP4 file with OpenCV try this:
import cv2
#your previous code here
fourcc = cv2.VideoWriter_fourcc(*'a\0\0\0')
out = cv2.VideoWriter('out.mp4', fourcc, fps, res)
#the character '\0' is the Null-Terminator or simply 0x00 in the ASCII-Table
#tag: *'a\0\0\0' corresponds to 0x00000061
#your following code here

How can I capture a picture from webcam and send it via flask

I want to send an Image object in a flask response but it gives me an error. I tried also an approach with StringIO.
image = Image.open("./static/img/test.jpg")
return send_file(image, mimetype='image/jpeg')
This is just a test case. So the major problem is to capture an image from /dev/video0 and sent it (ideally without temporary storing on disk) to the client. I use v4l2capture for that. The test picture should also work if you may have a better solution for that task.
import select
import v4l2capture
video = v4l2capture.Video_device("/dev/video0")
size_x, size_y = video.set_format(1280, 1024)
video.create_buffers(1)
video.queue_all_buffers()
video.start()
select.select((video,), (), ())
image_data = video.read()
video.close()
image = Image.fromstring("RGB", (size_x, size_y), image_data)
Thanks.
EDIT
Works now. Better solutions as v4l2capture are welcome...
Did it with.
image = Image.open("./static/img/test.jpg")
img_io = StringIO()
image.save(img_io, 'JPEG', quality=70)
img_io.seek(0)
return send_file(img_io, mimetype='image/jpeg')

Categories