Directory I would need to save to:
DataBase-Faces\name
Directory where the code is saving:
DataBase-Faces
My code:
cv2.imwrite("DataBase-Faces\\"+name+str(frames)+".png",Faceimage)
My program creates a folder with the typed name, I have to record these images in that folder, and the name of each image will be called Nome Typed + (frame number) .png
It looks like you're forgetting to put a directory separator between name and str(frames).
Try
image_path = '\\'.join(['DataBase-Faces', name, str(frames) + '.png'])
cv2.imwrite(image_path, Faceimage)
As a side note, you should not be concatenating paths by hand. Consider looking into the os.path module, which can save you from this sort of headache in the future.
General the Code to save the image is something like that
cv2.imwrite('file.png',img)
For the 'file.png' u want to be
EXAMPLE
name = 'my_photo_album_name'
frames = 500
frame_name = f'{name}\{frames}'
cv2.imwrite(f'DataBase-Faces\{frame_name}.png', img)
Related
I have a folder structure listed like the following
MA/valid/wrist/pa/positive/image2.png
Basically, for each wrist there are multiple pa, and for each pa there is a positive or negative study, and for each study there are up to 3 images in png format.
I have written a code below, but it only goes down to the pa level, it does not load my image files. Any help with loading my image files will be appreciated.
def load(Pic_Dir,Imsize):
data = []
dirs = next(os.walk(Pic_Dir))[1]
for dir_name in dirs:
files = next(os.walk(os.path.join(Pic_Dir, dir_name)))[2]
print("load [", len(files), "] files from [",dir_name,"] " )
for i in range(len(files)):
image_name = files[i]
image_path = os.path.join(Pic_Dir, dir_name, image_name)
label = dir_name
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.resize(img, (Imsize, Imsize))
data.append([np.array(img), label])
return
The function is called with the following line:
data=load("/Users/bond/MA/train/XR_WRIST",244)
I am not sure if I understood your question very well. However, if you need to walk through the directory and process all image file in its sub-directory, I would suggest you write something like this:
def load(root_director,Imsize):
import os
#TODO:You need to figure out how to get a list of this pa.
# Your question is not clear on how to get here
pas =get_list_of_pa()
cases =["positive", "negative"]
for pa in pas:
for case in cases:
in_dir = os.path.join(root_directory, pa, case)
all_images = [f for f in os.listdir(in_dir) if f.endswith('.png')]
for image in all_images:
#Do your processing here
pass
Basically, as you said, if you have many pa (what is pa?) you first need to get a list of all pas and loop through each one to access the list of cases=["positive", "negative]. This is not optimum. There are better ways to go through a directory, e.g., using the path.rglob or os.walk method you used before.
Please note that I am writing this code off the top of my head and did not test it in any way.
As a side note, IMHO, I would refactor your method and call it as follows
def load (director, pa, case):
# Get images for the pa and case
# Process the images
This would potentially reduce its complexity. In fact, to respect the single-responsibility principle (SRP), you probably need to refactor the method much further. For example, you need a method to get all the images of a directory
def get_images (director):
pass
Which returns the list of images (in this case, only .png files). Then, you would need another method that processes the image
def process_image (Imsize):
pass
I hope this helps!
I want my code to load all the images automatically. For now I have to
write code for each images separately, but i want it to automatically get all the images from the directory, use the image name as the variable to load image file and also modify the image name to store the encodings.
p_image = face_recognition.load_image_file("p.jpg")
P_face_encoding = face_recognition.face_encodings(p_image)[0]
Source for the face recognition code ( this is not my original code)
https://github.com/ageitgey/face_recognition/blob/master/examples/facerec_from_webcam_faster.py
import glob
p_image_list = []
for each_image in glob.glob("*.jpg"):
p_image_list.append(face_recognition.load_image_file(each_image)
p_image_list contains all the images in current folder
You can use a dictionary where items will be your variable names and have corresponding values of file names:
import os
files = os.listdir()
file_dict = {file : os.path.splitext(file) for file in files}
I'm currently working on converting breastcancer scans into black and white photos. This code needs to scan every file in the directory, process it, and save it with a unique name. My code looks like this:
wd = os.getcwd()
lencounter = 0
for file in os.listdir(wd):
lencounter += 1
for x in range(lencounter):
for file in os.listdir(wd):
if file.endswith("class0.png"):
image_file = Image.open(file)
image_file= image_file.convert('L')
image_file= image_file.convert('1')
print(image_file, x)
image_file.save("result1.png")
This code only allows me to save the last transformed picture, as "result1". Somehow the .save function doesn't let me include any iterationumber, just like you would expect when using the write() function.
I need something like "originalname_blackandwhite1.png" for every picture. I hope someone could help me out!
Thanks
What about image_file.save("{}_blackandwhite1.png".format(x))?
It can be more specific if you elaborate on how do you want your originalname to be
I am trying to create a unit test for a function that reads every image from a folder and saves them in a list.
Here is a simplified version of the function:
def read_images(directory):
image_paths = os.listdir(directory)
images = []
for im in image_paths:
images.append(cv2.imread(os.path.join(directory, im)))
return images
This other question brought me close to the solution, but in my case I want the fake files created to be images (basically, arrays) so I can read them with cv2.imread.
My idea is not having to create any temporary folder and, of course, not having to connect with any external folder or database. Is this possible?
Edit: to be clear, I'd like to not have to create temporary folders, nor temporary image files. I'd like to know if there is a way of telling the program: "There is a folder here, and inside it there are some images/arrays with this shape", but with actually not having to create anything in memory.
If you actually need temporary files, you should check tempfile.
It allows you to create temporary files and directories which provide automatic cleanup, so there are no trash files if you use this while having the opportunity to test what you want.
EDIT
If you don't really want to use tempfiles nor tempfolders, here is another solution concerning your problem:
Generate in-memory image for your test.
from io import BytesIO
from PIL import Image
def create_in_memory_image():
in_memory_file = BytesIO()
image = Image.new('RGBA',
size=(0, 0),
color=(155, 0, 0))
image.save(in_memory_file,
'png')
in_memory_file.name = 'tmp_testing_name.png'
in_memory_file.seek(0)
return in_memory_file
how do I mock a fake folder with fake images inside?
def local_cv2_imread():
# use as a side effect
return 'fakeImg1'
def test_read_images(self):
with mock.patch('os.listdir') as mock_listdir:
with mock.patch('package.module.cv2.imread') as mock_imread:
mock_listdir.return_value = ['fake_path']
mock_imread.side_effect = local_cv2_imread
images = read_images('a_real_path')
self.assertEqual(images, ['fakeImg1']
I want to be able to load large number of images one by one from the given folder. And also without knowing the names of the each image (only the name of the folder where all images are located). Currently I can load only one image using it's name (pic.jpg):
pixmap = QtGui.QPixmap("pic.jpg")
item = QtGui.QGraphicsPixmapItem(pixmap)
self.scene.addItem(item)
self.scene.update()
Is there any way to do this? Thanks in advance!
The os module contains filesystem access functions.
import os
dir = "dirname"
for file in os.listdir(dir):
... = QtGui.QPixmap(os.path.join(dir, file))
Note: os.path.join is there so you are platform agnostic.