OpenCV Python - Reading pgm files - python

I'm trying to read a bunch of pgm files for a facial recognition project.
These files lie in an overall folder called "negative" and within the negative folder are subfolders. This portion of my script is supposed to go into all of the directories, store the filenames in an array, and store the "image file" in another array using OpenCV.
os.chdir("../negative")
dirnames = os.listdir(".")
neg_names = []
for i in dirnames:
if os.path.isdir(i):
os.chdir(i)
neg_names.append(os.listdir("."))
os.chdir("..")
face = cv2.imread(i,-1)
faces_negatives.append(face)
print faces_negatives
For some reason when it prints the array I get NONE in every index (there are 40 of them). From my understanding I should be getting binary values from this. This code works file with jpg files.

Just in case anyone else runs into this issue, I found a solution:
I figured out the issue I was having had to do with the path that I was sending into the function "imread". The full path of the file needs to be passed into the function in order for it to read properly. The issue was resolved when I entered in the full path of the image

Related

How to loop through all image files (png) in a directory and send to deepstack?

I am attempting to create a script that will look at a directory and send all of the files of a certain type (PNG) to my Deepstack face recognition. The python script is Deepstack shows (and works fine) is as follows:
import requests
user_image = open("image1.png","rb").read()
response = requests.post("http://localhost:80/v1/vision/face/register",
files={"image":user_image},data={"userid":"User Name"}).json()
print(response)
If I understand your question correctly, you're asking how to check all the files in a directory and operate only on the files ending in ".png".
To do that, you would want to use the os.listdir function to provide a list of all files in a given directory, then check if each one ends in ".png" using a substring.
For example:
import os
# this will list the contents of the current directory by default
# you can also give os.listdir an argument with a path to a specific directory to list
fileList = os.listdir()
for fileName in contents:
if fileName[-4:] == ".png":
### your code goes here, using fileName
This example isn't perfect because it throws an error for filenames with fewer than 4 characters, but you can get the idea.

open image files from window explorer using python code

i recently just took up python for my research studentship (so i don't have a very strong cs background). I'm dealing with a large set of image files in many different subfolders in a big folder so I want to build a python code to search and open them.
I got introduced to os and sys libraries to play around with them. I could get the file to open but that is only when I specifically put a full dirpath for the file. I'm having trouble building a code to direct python to the right folder when I only know the folder name(i'm not sure if i'm making sense haha sorry).
My goal is to be able to type the id name of a folder containing the image in the python output so the file could be pulled out and displayed.
Any suggestions would be great! thank you so much!
You should look at the documentation for the functions we recommended you in the comments. Also, you may be interested to read some tutorials on files and directory, mainly in Python.
And look at how many questions we had to ask you to understand what you wanted to do. Provide code. Explain clearly what is your input, its type, its possible values, and what is the expected output.
Anyway, from what I understood so far, here is a proposal based on os.startfile :
import os
from pathlib import Path
# here I get the path to the desired directory from user input, but it could come from elsewhere
path_to_directory = Path(input("enter the path to the folder : "))
extension_of_interest = ".jpg"
filepaths_of_interest = []
for entry in path_to_directory.iterdir():
if entry.is_file() and entry.name.endswith(extension_of_interest):
print("match: " + str(entry))
filepaths_of_interest.append(entry)
else:
print("ignored: " + str(entry))
print("now opening ...")
for filepath_of_interest in filepaths_of_interest:
os.startfile(filepath_of_interest, "open")
when run, given the path C:/PycharmProjects/stack_oveflow/animals, it prints :
enter the path to the folder : C:/PycharmProjects/stack_oveflow/animals
ignored: C:\PycharmProjects\stack_oveflow\animals\cute fish.png
match: C:\PycharmProjects\stack_oveflow\animals\cute giraffe.jpg
match: C:\PycharmProjects\stack_oveflow\animals\cute penguin.jpg
match: C:\PycharmProjects\stack_oveflow\animals\cute_bunny.jpg
now opening ...
and the 3 jpg images have been opened with my default image viewer.
The startfile function was asked to "open" the file, but there are other possibilities described in the documentation.

Check if there are .format files in a directory

I have been trying to figure out for a while how to check if there are .pkl files in a given directory. I checked the website and I could find ways to find if there are files in the directory and list them, but I just want to check if they are there.
In my directory are a total of 7 .pkl files, as soon as I create one, the others are created so to check if the seven of them exist, it will be enough to check if one exists. Therefore, I would like to check if there is any .pkl file.
This is working if I do:
os.path.exists('folder1/folder2/filename.pkl')
But I had to write one of my file names. I would like to do so without searching for a specific file. I also tried
os.path.exists('folder1/folder2/*.pkl'),
but it is not working neither as I don't have any file named *.pkl.
You can use the python module glob (https://docs.python.org/3/library/glob.html)
Specifically, glob.glob('folder1/folder2/*.pkl') will return a list of all .pkl files in folder2.
You can use :
for dir_path, dir_names, file_names in os.walk(search_dir):
# Go over all files and folders
for file_name in file_names:
if (file_name.endswith(".pkl")):
# do something like break after the first one you find
Note : This can be used if you want to search entire directory with sub directories also
In case you want to search only one directory , you can run the "for" on os.listdir(path)

Convert all pdf in a folder to text files and store them in different folders using python

Im trying to convert all the pdf stored in one file, say 60 pdfs into text documents and store them in different folders. the folder should have unique names.
i tried this code.The folders where created, but the pdftotext conversion command doesnt work in the loop:
import os
def listfiles(path):
for root, dirs, files in os.walk(path):
for f in files:
print(f)
newpath = r'/home/user/files/'
p=f.replace("pdf","")
newpath=newpath+p
if not os.path.exists(newpath): os.makedirs(newpath)
os.system("pdftotext f f.txt")
f=listfiles("/home/user/reports")
One problem here is the os.system("pdftotext f f.txt") call. I assume you want the f's here replaced with the current file in the loop. If that is the case you need to change this to os.system("pdftotext {0} {0}.txt".format(f))
Another issue may be that the working directory is not being set up so the call to system is looking for the file in the wrong place. Try using os.chdir every time you change folders.
to place the text file in a diffrent folder try:
os.system("pdftotext {0} {1}/{0}.txt".format(f, newpath))
I don't know Python, but I think I can clearly see a mistake there. It looks like you are just replacing the ".pdf" with a ".txt". Since a PDF isn't just plain text, this won't work.
For the convertion look at the top answer of this post:
Python module for converting PDF to text

In python, how do I copy files into a directory and stop once that directory reaches a certain size

I am still very new to Python, but I am trying to create a program which will, among other things, copy the contents of a directory into a set of directories that will fit onto a disc (I have it set up the following variables to be the size capacities I want, and set up an input statement to say which one applies):
BluRayCap = 25018184499
DVDCap = 4617089843
CDCap = 681574400
So basically I want to copy the contents of a beginning directory into another directory, and as needed, create another directory in order for the contents to fit into discs.
I kind of hit a roadblock here. Thanks!
You can use os.path.getsize to get the size of a file, and you can use os.walk to walk a directory tree, so something like the following (I'll let you implement CreateOutputDirectory and CopyFileToDirectory):
current_destination = CreateOutputDirectory()
for root, folders, files in os.walk(input_directory):
for file in files:
file_size = os.path.getsize(file)
if os.path.getsize(current_destination) + file_size > limit:
current_destination = CreateOutputDirectory()
CopyFileToDirectory(root, file, current_destination)
Also, you may find the Python Search extension for Chrome helpful for looking up this documentation.
Michael Aaron Safyan's answer is good.
Besides, you can use shutil module to CreateOutputDirectory and CopyFileToDirectory

Categories

Resources