I was trying to write a program to rename all the video files of a folder. I just wanted to add video quality or dimension like (720p) or (1080p) or something like that to the end of the current file name. But I'm getting the following error:
Traceback (most recent call last):
File "f:\Python Projects\Practice\mm.py", line 17, in <module>
os.rename(file_name, f'{file_title} ({height}p){file_extension}')
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'Video 1.mp4' -> 'Video 1 (1080p).mp4'
Here is my code:
import os
from cv2 import cv2
os.chdir(r'F:\Python Projects\Practice\Temp Files')
for file_name in os.listdir():
# Getting Video Resolution
with open(file_name, 'r') as f:
f_string = str(f).split('\'')[1]
video_path = f'F:\\Python Projects\\Practice\\Temp Files\\{f_string}'
video = cv2.VideoCapture(video_path)
height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Getting the title
file_title, file_extension = os.path.splitext(file_name)
os.rename(file_name, f'{file_title} ({height}p){file_extension}')
Can anyone tell me how I can fix this problem? Thanks in advance... :)
The problem is that cv2.VideoCapture(video_path) opens your file as well. As this object continues to exist, the file is still open (even if it no longer is by your open(...) as f: once you exit the with block.)
So, you have to do it explicitely with:
video.release()
Something like this. Tested. Use
video.release()
to close a file opened with cv2.
import os
from cv2 import cv2
os.chdir(r'F:\Python Projects\Practice\Temp Files')
for file_name in os.listdir():
# Getting Video Resolution
f = open(file_name, 'r')
f_string = str(f).split('\'')[1]
f.close()
video_path = f'F:\\Python Projects\\Practice\\Temp Files\\{f_string}'
video = cv2.VideoCapture(video_path)
height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
video.release()
# Getting the title
file_title, file_extension = os.path.splitext(file_name)
os.rename(file_name, f'{file_title} ({height}p){file_extension}')
I've simplified the code and it works quite fine. I'm sharing my code here. If anyone becomes benefited from my code, it will be a matter of pride for me... :)
import os
from cv2 import cv2
video_folder = r'F:\Python Projects\Practice\Temp Files'
os.chdir(video_folder)
for file_name in os.listdir():
# Getting video quality
video_path = f'{video_folder}\\{file_name}'
video = cv2.VideoCapture(video_path)
width = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
video.release()
# Getting title
file_title, file_extension = os.path.splitext(file_name)
new_file_name = f'{file_title} ({width}p){file_extension}'
# Renaming the file
os.rename(file_name, new_file_name)
print('Rename Successful!')
Related
I am making a game in pygame and I have this unusual error that hasn't happened before. I am trying to animate my player and in the code I print the data that I'm getting. Whenever I use the path to the run animation, it runs perfectly. But when I try with the idle animations it returns this error:
Traceback (most recent call last):
File "/Users/dhruv/Documents/Games/2D Platformer Logic/scripts/support.py", line 15, in <module>
print(import_folder('../graphics/character/idle'))
File "/Users/dhruv/Documents/Games/2D Platformer Logic/scripts/support.py", line 11, in import_folder
img_surf = pygame.image.load(full_path)
pygame.error: Unsupported image format
I have checked the files, they are all .png files. So why am I getting this error? Here is my code btw.
import pygame
from os import walk
def import_folder(path):
surface_list = []
for _, __, img_files in walk(path):
real_imgs = sorted(img_files)
for image in real_imgs:
full_path = path + '/' + image
img_surf = pygame.image.load(full_path)
surface_list.append(img_surf)
return surface_list
print(import_folder('../graphics/character/idle'))
You could use a try/ except loop to trap and ignore the loading errors:
import pygame
from os import walk
def import_folder(path):
surface_list = []
for _, __, img_files in walk(path):
real_imgs = sorted(img_files)
for image in real_imgs:
try:
full_path = path + '/' + image
img_surf = pygame.image.load(full_path)
surface_list.append(img_surf)
except pygame.error:
print(f"Unable to load image {full_path}")
return surface_list
print(import_folder('../graphics/character/idle'))
Or you could use a pattern based search (known as a glob). Here's an example using Pathlib, which is much nicer that os.walk() and friends:
from pathlib import Path
def import_folder(path):
surface_list = []
img_files = Path(path).glob("*.png")
for img_file in img_files:
img_surf = pygame.image.load(img_file)
surface_list.append(img_surf)
return surface_list
I am using PIL to make an application to open all images in a folder. I sought for tutorials for PIL. I tried to find tutorials with list of images, but I failed to do so. I found some, but I had to list the file location beforehand. It annoyed me. So, instead I want the user to choose a folder, and the application would load all the images for the user. But, while making the thumbnails for the list of images, I got an error which I'm not familiar with. This is the exact error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line
1892, in __call__
return self.func(*args)
File "f:\OG\Python\ImageViewer.py", line 47, in openFolder
GetFiles()
File "f:\OG\Python\ImageViewer.py", line 87, in GetFiles
with Image.open(i) as img:
prefix = fp.read(16)
raise AttributeError(name)
The minimal code to get this error is:
import glob
from PIL import Image, ImageTk
fileDir = "Your Folder"
imageList = []
image_list = []
for filename in glob.glob(fileDir + '/*.jpg'): # gets jpg
im = Image.open(filename)
imageList.append(im)
for i in imageList:
with Image.open(i) as img: # This raises the error
imageList[i] = img.thumbnail((550, 450))
for i in image_list: # Would this work?
image_list[i] = ImageTk.PhotoImage(imageList[i])
I would like to know if the code that is commented with 'Would this work?' would work or not.
Just remove the reading part again which doesn't make sense
import glob
from PIL import Image, ImageTk
fileDir =r"your path"
imageList = []
for filename in glob.glob(fileDir + '/*.jpg'): # gets jpg
im = Image.open(filename)
imageList.append(im)
imageList will look like this :
[<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=200x200 at 0x25334A87D90>]
here is the blockbuster solution
import glob
from PIL import Image, ImageTk
import PIL
from pathlib import Path
fileDir = r"your_path_here"
imageList = []
for filename in glob.glob(fileDir + '/*.jpg'): # gets jpg
im = Image.open(filename)
imageList.append(im)
im.thumbnail((550, 450))
im.save(fileDir+'/'+Path(filename).name.split('.')[0]+'_thumbnail.png')
I solved it, I edited the code as follows:
import glob
from PIL import Image, ImageTk
fileDir = "Your Folder"
imageList = []
image_list = []
count = 0
for filename in glob.glob(fileDir + '/*.jpg'): # gets jpg
imageList.append(filename)
for i in imageList:
with Image.open(i) as img:
i = img.thumbnail((550, 450))
for i in imageList: # This gives a Key Error Now
image_list.append(ImageTk.PhotoImage(imageList[count]))
count = count + 1
Basically, Introduced a new variable count with a value of 0, removed open from first for loop, used append method for the last for loop and added count 1 each time :)
i want to encoding some of folders that contain face images.
this is the code that i've been tried.
import face_recognition
import cv2
import numpy as np
import os
import glob
video_capture = cv2.VideoCapture(0)
known_face_encodings = []
known_face_names = []
# Load image folder and learn how to recognize it.
os.chdir("./coba1")
for file in glob.glob("*.jpg"):
images = face_recognition.load_image_file(file)
images_encoding = face_recognition.face_encodings(images)[0]
known_face_encodings.append(images_encoding)
known_face_names.append("jokowi")
print(images_encoding)
#Load image folder and learn how to recognize it.
os.chdir("./coba")
for file in glob.glob("*.jpg"):
images = face_recognition.load_image_file(file)
images_encoding = face_recognition.face_encodings(images)[0]
known_face_encodings.append(images_encoding)
known_face_names.append("amber heard")
print(images_encoding)
when i run the code, the terminal shows this warning
Traceback (most recent call last):
File "face_rec.py", line 32, in <module>
os.chdir("./coba")
FileNotFoundError: [Errno 2] No such file or directory: './coba'
is there anything wrong with my code? i really need the solution, thanks in advance !
I just have started with Python and Numpy arrays. I am reading a huge amount of image data set located in many different folders. Although, everything is working fine when reading the images, but I continuously getting an error which I am not sure about what really is it. I tried to research for it, but unfortunately I failed to get the real answer. Please help me regarding this issue.
My code is below.
import os
import numpy as np
import matplotlib.pyplot as mpplot
import matplotlib.image as mpimg
images = []
path = "../compCarsThesisData/"
for root, _, files in os.walk(path):
current_directory_path = os.path.abspath(root)
for f in files:
name, ext = os.path.splitext(f)
if ext == ".jpg":
current_image_path = os.path.join(current_directory_path, f)
current_image = mpimg.imread(current_image_path)
images.append(current_image)
print(files)
for img in images:
print (img.shape)
The error I'm facing is below also.
File "reading.py", line 15, in <module>
current_image = mpimg.imread(current_image_path)
File "C:\Users\zeele\AppData\Local\Programs\Python\Python36\lib\site-packages\matplotlib\image.py", line 1359, in imread with Image.open(fname) as image:
File "C:\Users\zeele\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\Image.py", line 2618, in open
prefix = fp.read(16)
OSError: [Errno 22] Invalid argument
P.S. As a new member please don't mind if the question is unclear or not direct. Your help will be highly appreciated.
Thanks.
I believe this is my first StackOverflow question, so please be nice.
I am OCRing a repository of PDFs (~1GB in total) ranging from 50-200 pages each and found that suddenly all of the available 100GB of remaining harddrive space on my Macbook Pro were gone. Based on a previous post, it seems that ImageMagick is the culprit as shown here.
I found that these files are called 'magick-*' and are stored in /private/var/tmp. For only 23 PDFs it had created 3576 files totaling 181GB.
How can I delete these files immediately within the code after they are no longer needed? Thank you in advance for any suggestions to remedy this issue.
Here is the code:
import io, os
import json
import unicodedata
from PIL import Image as PI
import pyocr
import pyocr.builders
from wand.image import Image
from tqdm import tqdm
# Where you want to save the PDFs
destination_folder = 'contract_data/Contracts_Backlog/'
pdfs = [unicodedata.normalize('NFKC',f.decode('utf8')) for f in os.listdir(destination_folder) if f.lower().endswith('.pdf')]
txt_files = [unicodedata.normalize('NFKC',f.decode('utf8')) for f in os.listdir(destination_folder) if f.lower().endswith('.txt')]
### Perform OCR on PDFs
def ocr_pdf_to_text(filename):
tool = pyocr.get_available_tools()[0]
lang = 'spa'
req_image = []
final_text = []
image_pdf = Image(filename=filename, resolution=300)
image_jpeg = image_pdf.convert('jpeg')
for img in image_jpeg.sequence:
img_page = Image(image=img)
req_image.append(img_page.make_blob('jpeg'))
for img in req_image:
txt = tool.image_to_string(
PI.open(io.BytesIO(img)),
lang=lang,
builder=pyocr.builders.TextBuilder()
)
final_text.append(txt)
return final_text
for filename in tqdm(pdfs):
txt_file = filename[:-3] +'txt'
txt_filename = destination_folder + txt_file
if not txt_file in txt_files:
print 'Converting ' + filename
try:
ocr_txt = ocr_pdf_to_text(destination_folder + filename)
with open(txt_filename,'w') as f:
for i in range(len(ocr_txt)):
f.write(json.dumps({i:ocr_txt[i].encode('utf8')}))
f.write('\n')
f.close()
except:
print "Could not OCR " + filename
A hacky way of dealing with this was to add an os.remove() statement within the main loop to remove the tmp files after creation.
tempdir = '/private/var/tmp/'
files = os.listdir(tempdir)
for file in files:
if "magick" in file:
os.remove(os.path.join(tempdir,file))
Image should be used as a context manager, because Wand determine timings to dispose resources including temporary files, in-memory buffers, and so on. with block help Wand to know boundaries when these Image objects are still needed and when they are now unnecessary.
See also the official docs.