I am saving my video frames with below code but I want to add save_path to file name as well:
cv2.imwrite(f"{save_path}/{idx}.png", frame)
How could I add save_path to file name?
I need it as:
save_path/idxsavepath
since we lack the debugging info, here is a piece of code you should have written to avoid path problems. first, check that the directory is found and only then continue.
import os
import cv2
import numpy as np
def main():
# before continuing, must check if folder exists
save_dir = r'D:\pics'
valid_path = os.path.exists(save_dir)
print('is {} a valid path ? {}'.format(save_dir, valid_path))
if not valid_path:
print('folder {} does not exist - create it and try again'.format(save_dir))
else:
idx = 0
fake_frame = np.zeros(shape=(480, 640, 3))
image_full_path = '{}/{}.png'.format(save_dir, idx)
cv2.imwrite(image_full_path, fake_frame)
print('image saved successfully on {}'.format(image_full_path))
return
if __name__ == '__main__':
main()
Related
Code is working perfectly but How can I quit a script which is using a loop? Is there any method because Ctrl+C did not work. I do not have Break/Pause button in my keyboard so I could use it.
import pandas as pd
import os
from os import listdir
from os.path import isfile, join
from PIL import Image
import requests
from io import BytesIO
import argparse
arg_parser = argparse.ArgumentParser(allow_abbrev=True, description='Download images from url in a directory',)
arg_parser.add_argument('-d','--DIR',required=True,
help='Directory name where images will be saved')
arg_parser.add_argument('-c','--CSV',required=True,
help='CSV file name which contains the URLs')
arg_parser.add_argument('-i','--index',type=int,
help='Index number of column which contain the urls')
arg_parser.add_argument('-e','--end',type=int,
help='How many images to download')
args = vars(arg_parser.parse_args())
def load_save_image_from_url(url,OUT_DIR,img_name):
response = requests.get(url)
img = Image.open(BytesIO(response.content))
img_format = url.split('.')[-1]
img_name = img_name+'.'+img_format
img.save(OUT_DIR+img_name)
return None
csv = args['CSV']
DIR = args['DIR']
ind = 0
if args.get('index'):
ind = args['index']
df = pd.read_csv(csv) # read csv
indices = [int(f.split('.')[0]) for f in listdir(DIR) if isfile(join(DIR, f))] # get existing images
print(f'There are already {len(indices)} images present in the directory -{DIR}-')
start = 0
if len(indices):
start = max(indices)+1 # set strating index
end = 5000 # next n numbers of images to download
if args.get('end'):
end = args['end']
print(f'Downloaded a total of {len(indices)} images upto index: {start-1}. Downloading the next {end} images from -{csv}-')
count = 0
for i in range(start, start+end):
if count%250==0:
print(f"Total {start+count-1} images downloaded in directory. {end-count} remaining from the current defined")
url = df.iloc[i,ind]
try:
load_save_image_from_url(url,DIR,str(i))
count+=1
except:
print(f'Error Occured at index: {i}')
pass
I just want to quit the program while running. If I have to quit it, I have to close the terminal but I don't think this is the proper way. How could I quit it "properly" without closing the terminal?
You can use the KeyboardInterrupt to exit your application as follows:
try:
### code that prevented the exit goes here
except (KeyboardInterrupt, SystemExit):
print("Forced exit")
raise
Then you can normally exit with Ctrl+C
So I'm working on this sign language gesture recognition python project from git hub.
I followed the read me file and saved (in the project's root folder) all the dataset files in two seperate folders named as train_videos and test_videos for machine learning.
Now I'm getting the following error:
usage: video-to-frame.py [-h] gesture_folder target_folder
video-to-frame.py: error: the following arguments are required: gesture_folder, target_folder
Following is the code from "video-to-frame.py" file.
I can't figure out where to put the paths of my data set fodlers.
import cv2
import os
import pickle
from os.path import join, exists
import handsegment as hs
import argparse
from tqdm import tqdm
hc = []
def convert(gesture_folder, target_folder):
rootPath = os.getcwd()
majorData = os.path.abspath(target_folder)
if not exists(majorData):
os.makedirs(majorData)
gesture_folder = os.path.abspath(gesture_folder)
os.chdir(gesture_folder)
gestures = os.listdir(os.getcwd())
print("Source Directory containing gestures: %s" % gesture_folder)
print("Destination Directory containing frames: %s\n" % majorData)
for gesture in tqdm(gestures, unit='actions', ascii=True):
gesture_path = os.path.join(gesture_folder, gesture)
os.chdir(gesture_path)
gesture_frames_path = os.path.join(majorData, gesture)
if not os.path.exists(gesture_frames_path):
os.makedirs(gesture_frames_path)
videos = os.listdir(os.getcwd())
videos = [video for video in videos if(os.path.isfile(video))]
for video in tqdm(videos, unit='videos', ascii=True):
name = os.path.abspath(video)
cap = cv2.VideoCapture(name) # capturing input video
frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
lastFrame = None
os.chdir(gesture_frames_path)
count = 0
# assumption only first 200 frames are important
while count < 201:
ret, frame = cap.read() # extract frame
if ret is False:
break
framename = os.path.splitext(video)[0]
framename = framename + "_frame_" + str(count) + ".jpeg"
hc.append([join(gesture_frames_path, framename), gesture, frameCount])
if not os.path.exists(framename):
frame = hs.handsegment(frame)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
lastFrame = frame
cv2.imwrite(framename, frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
count += 1
# repeat last frame until we get 200 frames
while count < 201:
framename = os.path.splitext(video)[0]
framename = framename + "_frame_" + str(count) + ".jpeg"
hc.append([join(gesture_frames_path, framename), gesture, frameCount])
if not os.path.exists(framename):
cv2.imwrite(framename, lastFrame)
count += 1
os.chdir(gesture_path)
cap.release()
cv2.destroyAllWindows()
os.chdir(rootPath)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Extract Individual Frames from gesture videos.')
parser.add_argument('gesture_folder', help='Path to folder containing folders of videos of different gestures.')
parser.add_argument('target_folder', help='Path to folder where extracted frames should be kept.')
args = parser.parse_args()
convert(args.gesture_folder, args.target_folder)
This is the link to project's git hub repository.
So I'm relatively new to python but the snippet of code you shared is a function with inputs of gesture_folder and target_folder so with that said you will need to see where the function convert() is called in your overall code and then check what inputs are inside of the function call.
So if it looks like this then replace the paths in the function call
convert("C:\\User\gesturefolder","C:\\User\targetfolder" )
But if it looks like this
convert(gf,tf)
then you will need to work backwards and find where gf and tf are declared and replace the paths there
EDIT:
parser.add_argument('C:\\User\gesturefolder', help='Path to folder containing folders of videos of different gestures.')
parser.add_argument('C:\\User\targetfolder', help='Path to folder where extracted frames should be kept.')
If replacing this with your paths doesnt work then try replacing all backslashes with either \ or /
EDIT2:
So I looked through the Github and it appears the paths are provided when calling the python code
video-to-frame.py [-h] gesture_folder target_folder
Have you tried something like this
gesture_folder="C:\\..." #gesture folder path
target_folder="C:\\..." #target folder path
video-to-frame.py [-h] gesture_folder target_folder
EDIT3:
The last suggestion I can think of is since you are just running it the code directly and not calling it then just define the paths at the beginning of the code between the imports and hc
import cv2
import os
import pickle
from os.path import join, exists
import handsegment as hs
import argparse
from tqdm import tqdm
gesture_folder="C:\\..." #gesture folder path
target_folder="C:\\..." #target folder path
hc = []
Every time I run my program in the terminal it prints out:
thumb0496.jpg is not converted
{} is not converted
Whatever I do it never works... I am new to Python and have installed it via Anaconda along with OpenCV, Pip and ITK. I have only been doing this for 4 days and am stuck. Python is my first language also. Why are my code not working?
In case this code looks similar it is. I had to try out with combining some elements. Unfortunately I cannot find the post again. The code was worse before but I (somehow) fixed it. It is just this (new) piece I can't fix on my own!
import cv2
import sys
import itk
import os,glob
from os import listdir,makedirs
from os.path import isfile,join
path = '/Users/admin/Desktop/ff'
dstpath = '/Users/admin/Desktop/test'
PixelType = itk.UC
Dimension = 2
ImageType = itk.Image[PixelType, Dimension]
RGBPixelType = itk.RGBPixel[PixelType]
RGBImageType = itk.Image[RGBPixelType, Dimension]
ColormapType = itk.CustomColormapFunction[PixelType, RGBPixelType]
colormap = ColormapType.New()
ColormapFilterType = itk.ScalarToRGBColormapImageFilter[ImageType,RGBImageType]
colormapFilter1 = ColormapFilterType.New()
colormapFilter1.SetInput(reader.GetOutput())
colormapFilter1.SetColormap(colormap)
WriterType = itk.ImageFileWriter[RGBImageType]
writer = WriterType.New()
writer.SetFileName(dstpath)
writer.SetInput(colormapFilter1.GetOutput())
try:
makedirs(dstpath)
except:
print ("Directory already exist, images will be written in same folder")
files = [f for f in listdir(path) if isfile(join(path,f))]
for image in files:
try:
reader = ReaderType(os.path.join(path,image))
map = ColormapFilterType(reader, PixelType, RGBImageType, ImageType)
dstPath = join(dstpath,image)
cv2.imwrite(dstPath,map)
except:
print ("{} is not converted".format(image))
for fil in glob.glob("*.jpg"):
try:
img = ReaderType(os.path.join(path,fil))
map_imag = ColormapType(img, PixelType, RGBImageType,ImageType)
cv2.imwrite(os.path.join(dstpath,fil),map_image)
except:
print('{} is not converted')
Why don't you start from a working example, and gradually change it to suit your needs? Examples can be found in the quick-start guide and this blog post.
recently I try to find the right way to read LSUN dataset which is in the form of lmdb. However, I do not find any useful information. I want to know how to read image data from lmdb and what the advantage is in that way. Thank you!
Finally, I use the following code to extract LUSN images from lmbd file.
import os
import lmdb
from PIL import Image
import tempfile
def _export_mdb_images(db_path, out_dir=None, flat=True, limit=-1, size=256):
out_dir = out_dir
env = lmdb.open(
db_path, map_size=1099511627776,
max_readers=1000, readonly=True
)
count = 0
with env.begin(write=False) as txn:
cursor = txn.cursor()
for key, val in cursor:
key = str(key, 'utf-8')
# decide image out directory
if not flat:
image_out_dir = os.path.join(out_dir, '/'.join(key[:6]))
else:
image_out_dir = out_dir
# create the directory if an image out directory doesn't exist
if not os.path.exists(image_out_dir):
os.makedirs(image_out_dir)
with tempfile.NamedTemporaryFile('wb') as temp:
temp.write(val)
temp.flush()
temp.seek(0)
image_out_path = os.path.join(image_out_dir, key + '.jpg')
Image.open(temp.name).resize((size, size)).save(image_out_path)
count += 1
if count == limit:
break
if count % 1000 == 0:
print('Finished', count, 'images')
print("start")
db_path = "path to lmbd"
out_dir = os.path.join(db_path, "data")
_export_mdb_images(db_path, out_dir)
I am trying to access file_name dynamically from user and then pass it to videoCapture(file_name) and then process it.
Code :
import cv2
import numpy as np
import os
import sqlite3
import pickle
from PIL import Image
import sys
faceDetect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml');
rec = cv2.createLBPHFaceRecognizer();
'''
Dynamically accessing the fileName
Error seems to be here in the following couple of codes
Note: i am assigning file_name as <"test.mp4">
'''
file_name = raw_input("Enter file name: ")
print file_name
cam = cv2.VideoCapture(file_name)
while cam.isOpened():
ret,img = cam.read()
if ret == True:
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = faceDetect.detectMultiScale(gray,1.3,5);
for(x,y,w,h) in faces :
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
id,conf=rec.predict(gray[y:y+h,x:x+w])
'''
Few lines of code
'''
cv2.imshow("Face",img);
if (cv2.waitKey(1) == ord('q')):
break;
else :
print ('ret is false')
break
cam.release()
cv2.destroyAllWindows()
it show no error but it does not execute the while(cam.isOpened): loop. am i missing something ?
Enter the filename without the quotes. It works fine. Because since the input has alphabets it will be string object already. Adding quotes will be like inputting a wrong file name. As I said in comments videocapture does not throw error sometimes if entered filename does not exist. Hope this helps