processing multiple images in sequence in opencv python - python-3.x

I am trying to build the code using python, for which I need to process at least 50 images. So how should I read the images one by one and process it. Is it possible using a loop and do i need to create a separate database for this or just saving all the images in separate file will do?

I have written some code may statisfy your requirement.
import glob
import os,sys
import cv2
## Get all the png image in the PATH_TO_IMAGES
imgnames = sorted(glob.glob("/PATH_TO_IMAGES/*.png"))
for imgname in imgnames:
## Your core processing code
res = propress(imgname)
## rename and write back to the disk
#name, ext = os.path.splitext(imgname)
#imgname2 = name+"_res"+ext
imgname2 = "_res".join(os.path.splitext(imgname))
cv2.imwrite(imgname2, res)

The task consists of following steps,
Having the images in a directory e.g. foo/
Getting the list of all images in the foo/ directory
Lopp over the list of images
3.1. img = cv2.imread(images(i),0)
3.2. ProcessImage(img) #Run an arbitrary function on the image
3.3. filename = 'test' + str(i) +'.png'
3.4. cv2.imwrite(filename, img)
End of the loop

Related

Python Pillow library not saving files with same name in same location

Below is the code I am using to convert a binary data into image and then saving it
img = base64.b64decode(rec.image3)
img_conv = Image.open(io.BytesIO(img))
img_format = img_conv.format
img_conv.save('{}/{}'.format(path, rec.image_name), format(img_format))
There are 4 images with same code and I want to handle the scenario where if all the file names are same in the same location, it should force to save the 4 images even though it has duplicate name.
Any suggestion would be appreciated. Thanks.
Supposing that you want to keep each file under a different name: Append '_' to the original filename as long as a file with such a name exists in your directory.
from pathlib import Path
path_to_save = Path(path, rec.image_name)
while path_to_save.exists():
path_to_save = Path(str(path_to_save) + '_')
img_conv.save(path_to_save, format(img_format))

Automate cropping with Pillow and python?

So I have a folder with 500+ images that need to be cropped. And I have searched and have manage to create this cut-and-paste script. But, for some reason it doesn't save the new image!? The terminal is just still, no errors no nothing.
from PIL import Image # import the Python Image processing Library
import os # To read the folder
directory_in_str = "/Users/hora/Downloads/Etik"
directory = os.fsencode(directory_in_str)
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".png"):
image = os.path.join(directory_in_str, filename)
imageObject = Image.open(image) # Create an Image object from an Image
cropped = imageObject.crop((1025,85,2340,2040)) # Crop the iceberg portion (top left x, top left y, bottom right x, bottom right y)
cropped.save("{}".format(filename+"_cropped"), 'png') # Save the cropped portion
continue
else:
continue
Im searching in a specific folder, and the cropped image should be saved with a filename_cropped.png. But not necessary, I have backups if something should go side-ways.
The expected result:
Loop through a folder
Crop all images ending with .png
And save the crop image with the previous filename but with extension
FILNAME_cropped.png
Done
Two issues regarding this line:
cropped.save("{}".format(filename+"_cropped"), 'png')
Your filename still contains the file extension.
You don't add a (new) file extension yourself.
Both issues result in some string xxx.png_cropped for your new file.
My suggestion to modify your code:
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".png"):
image = os.path.join(directory_in_str, filename)
filename, file_extension = os.path.splitext(filename) # <-- After reading, filename can be overwritten
imageObject = Image.open(image)
cropped = imageObject.crop((1025,85,2340,2040))
cropped.save("{}".format(filename+"_cropped.png"), 'png') # <-- Explicitly add .png to your filename
continue
else:
continue
Hope that helps!
add the directory path in saving the file.
directory_in_str = "/Users/hora/Downloads/Etik/"
cropped.save("{}".format(directory_in_str+filename+"_cropped"),'png')

os.listdir reads images randomly making bounding box training difficult

os.listdir(path) command reads images randomly from a folder. I have saved a csv file with bouding box information for the images in folder sequentially. I assumed os.listdir would read the images sequentially so that my csv file also can be read sequentiallu during the training.
I have tried sorted(os.listdir) but no use. I could not find any other functions or code to read the images sequentially from a folder. I named the images as frame1.jpg, frame2.jpg etc.
PATH = os.getcwd()
# Define data path
data_path = PATH + '/frames'
data_dir_list = sorted(os.listdir(data_path))
print(data_dir_list)
img_data_list=[]
for dataset in (data_dir_list):
img_list=sorted(os.listdir(data_path+'/'+ dataset))
print ('Loaded the images of dataset-'+'{}\n'.format(dataset))
for img in sorted(img_list):
input_img=cv2.imread(data_path + '/'+ dataset + '/'+ img )
input_img=cv2.cvtColor(input_img, cv2.COLOR_BGR2GRAY)
input_img1=input_img
#input_img_resize=cv2.resize(input_img,(512,512))
img_data_list.append(input_img1)
img_data = np.array(img_data_list)
img_data = img_data.astype('float32')
img_data /= 255
As per Python docs, os.listdir() returns filenames in an arbitrary order. It just maps to an underlying operating system call that will return filenames in whatever order is presumably most efficient based on filesystem design.
It's just a standard list of strings, so sorted() would work in the way you're using it. Are the sequential numbers in your filenames correctly padded for this to work with the more than 10 images you're presumably using? What's the random order you're seeing from sorted(os.listdir(...))?

How to change where the output directory where the new images go

I have a small query I'm hoping someone can help me out within Python 3. I am resizing a dataset of 10000 images to all be 1000x1000 in dimension before I do any pytorch analysis with it. I just wanted to ask how I change my code to save the outgoing images to a new folder I have created ''train_resized'' instead of the same folder as the original files as it is doing now when I run. Thanks
# Testing dataset
from PIL import Image
import os, sys
path = (r'G:\My Drive\CATSVDOGS2.0\test1\\')
dirs = os.listdir( path )
def resize():
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
imResize = im.resize((1000,1000), Image.ANTIALIAS)
imResize.save(f + ' resized.jpg', 'JPEG', quality=90)
resize()
In your line
imResize.save(f + ' resized.jpg', 'JPEG', quality=90)
you're setting the path when using the variable f, as f uses the path variable you defined. A quick way to set the path is to do something like:
imResize.save('G:\\My Drive\\Path\\To\\Folder\\' + item + ' resized.jpg', 'JPEG', quality=90)
of course specify the path to be whatever you want. Untested as I don't have Python installed on my work machine, but that is the general gist.

Python importing a batch of jpg images in files?

I'm trying to import a batch of images from a file to a new separate folder according to the images name for example; 1000_70.jpg --> folder 70 and 1200_71.jpg --> folder 71. However, when I ran the script it does nothing.
from PIL import Image
import glob
import os
folder='Desktop/n' # All jpegs are in this folder
imList=glob.glob(folder+'*.jpg') # Reading all images with .jpg
newfold = 'Desktop/n/l' # New folder path
for img in imList: # Loop
im = Image.open(img) # Opening image
fileName, fileExt = os.path.splitext(img) # Extract the filename and
# Extension from path
im.save(newfold+fileName+'*.jpg') #save the image to new folder from
#old folder
First of you want the filename of the image not the path, use split instead of splitext to remove the parent folder and than use splitext to remove the extension:
os.path.splitext("afdsasdf/fasdfa/fff.jpg")
=> ('afdsasdf/fasdfa/fff', '.jpg')
os.path.split("afdsasdf/fasdfa/fff.jpg")
=> ('afdsasdf/fasdfa', 'fff.jpg')
Second you remove the wildcare in *.jpg when saving the image. You need that wildcare with glob since you are selectioning multiple files.
Third you need to extract the second number in the filename (1000_70.jpg --> 70).
All toghether you should have something that look like this:
for img in imList:
im = Image.open(img)
filepath, filenameExt = os.path.split(img)
filename, fileExt = os.path.splitext(filenameExt)
folderNumber = filename.split("_")[1]
im.save("{}/{}/{}".format(newfold, folderNumber, filenameExt))

Resources