I have about 200- 400 pictures in a folder to be processed. I am trying to use python to write a sort of script to process these images. The image output are changing but there are some logic error which i am aware of but no idea to amend. These are the two files i have so far
test2 and resize are 2 .py files that i have created. test2.py will be calling resize.py it will resize images that are in the directory
test2.py
import glob
import cv2
from resize import process
for image_file in glob.iglob('/home/winowa/Desktop/Intern101/fisherFace/test/*.jpg'):
process(image_file)
resize.py
import cv2
def process(filename):
image = cv2.imread(filename)
print image.shape
r = 100.0 / image.shape[1]
dim = (100, int(image.shape[0] *r))
imageresized = cv2.resize(image,(300,300),dim,interpolation = cv2.INTER_AREA)
for i in range(19):
cv2.imwrite( 'imageresized_{}.jpg'.format(i) ,imageresized )
print 'imageresized_{}.jpg'.format(i)
i am aware that after entering resize.py it will loop19 times before going to the 2nd round of test2.py. I am trying to correct the program to move on to the next image and will output images name as imageresized1.jpg,imageresized2.jpg and so on. Now images are the right name but wrong images. Only one image is being prcessed due to the for loop. range(19) are 19 images in my folder
What about
test2.py
import glob
import cv2
from resize import process
for (i,image_file) in enumerate(glob.iglob('/home/winowa/Desktop/Intern101/fisherFace/test/*.jpg')):
process(image_file, i)
resize.py
import cv2
def process(filename, key):
image = cv2.imread(filename)
print image.shape
r = 100.0 / image.shape[1]
dim = (100, int(image.shape[0] *r))
imageresized = cv2.resize(image,(300,300),dim,interpolation = cv2.INTER_AREA)
cv2.imwrite( 'imageresized_{}.jpg'.format(key) ,imageresized )
print 'imageresized_{}.jpg'.format(key)
This assumes that you only want to write a single file for each call to process and that your "19 files" will be the files matched by glob.
Related
I am trying to crop all images in a folder and save them in another folder. Then split all the images I have cropped using the image_slicer library.
I know a similar question like this has been asked but the difference is that I don't want the original folder to contain the cropped photos.
Here is my code so far; it runs but does nothing:
from PIL import Image
import image_slicer
import os
path = 'BeforeAfter'
arr = os.listdir(path)
def crop():
for i in arr:
if os.path.isfile(i):
img = Image.open(i)
f, e = os.path.splitext(i)
left = 66.6
top = 37.4
right = 1212.4
bottom = 550.7
imCrop = img.crop((left, top, right, bottom))
imCrop.save("CroppedImages/", "PNG", quality= 100)
# tiles = image_slicer.slice(toslice, 12, save=False)
# image_slicer.save_tiles(tiles, directory='frames')
crop()
I created an model in blender. From here I took 2d slices through the y-plane of that model leading to the following.
600 png files each corresponding to a ylocation i.e y=0, y=0.1 etc
Each png file has a resolution of 500 x 600.
I am now trying to merge the 600 pngs into a h5 file using python before loading the .h5 into some software. I find that each individual png file is read fine and looks great. However when I look at the final 3d image there is some stretching of the image, and im not sure how this is being created.
The images are resized (from 600x600 to 500x600, but I have checked and this is not the cause of the stretching). I would like to know why I am introducing such stretching in other planes (not y-plane).
Here is my code, please note that there is some work in progress here, hence why I append the dataset to a list (this is to be used for later code)
from PIL import Image
import sys
import os
import h5py
import numpy as np
import cv2
from datetime import datetime
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(dir_path + '//..//..')
Xlen=500
Ylen=600
Zlen=600
directory=dir_path+"/LowPolyA21/"
for filename in os.listdir(directory):
if fnmatch.fnmatch(filename, '*.png'):
image = Image.open(directory+filename)
new_image = image.resize((Zlen, Xlen))
new_image.save(directory+filename)
dataset = np.zeros((Xlen, Zlen, Ylen), np.float)
# traverse all the pictures under the specified address
cnt_num = 0
img_list = sorted(os.listdir(directory))
os.chdir(directory)
for img in (img_list):
if img.endswith(".png"):
gray_img = cv2.imread(img, 0)
dataset[:, :, cnt_num] = gray_img
cnt_num += 1
dataset[dataset == 0] = -1
dataset=dataset.swapaxes(1,2)
datasetlist=[]
datasetlist.append(dataset)
dz_dy_dz = (float(0.001),float(0.001),float(0.001))
for j in range(Xlen):
for k in range(Ylen):
for l in range(Zlen):
if datasetlist[i][j,k,l]>1:
datasetlist[i][j,k,l]=1
now = datetime.now()
timestamp = now.strftime("%d%m%Y_%H%M%S%f")
out_h5_path='voxelA_'+timestamp+'_flipped'
out_h5_path2='voxelA_'+timestamp+'_flipped.h5'
with h5py.File(out_h5_path2, 'w') as f:
f.attrs['dx_dy_dz'] = dz_dy_dz
f['data'] = datasetlist[i] # Write data to the file's primary key data below
Example of image without stretching (in y-plane)
Example of image with stretching (in x-plane)
import pprint as pp
original_img = cv2.imread("/content/drive/My Drive/images/image1.jpg") #here i want to use multiple images atleast 250 images.
original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
results = tfnet2.return_predict(original_img)
print(results)
I guess all your images are in the folder images. So you can use os to gett all their filenames.
import os
pth = "/content/drive/My Drive/images" # make sure it is correct
images = os.listdir(pth)
for image in images:
image_path = os.path.join(pth, image)
original_img = cv2.imread(image_path)
original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
results = tfnet2.return_predict(original_img)
print(results)
anyone can use for loop add empty folder to direct all the json files directly to the same folder using basic addition '+' operator.
for i in range():
original_img = cv2.imread("/folder path(500+ images)/" + any_empty_folder[i])
I am trying to open a set of images in python, but I am a bit puzzled on how I should do that. I know how to do it with one image, but I don't have a clue on how to handle several hundreds of images.
I have a file folder with a few hundred .jpg images. I want to load them in a python program to do machine learning on them. How can I do this properly?
I don't have any code yet since I am already struggling with this.
But my Idea in pseudocode was
dataset = load(images)
do some manipulations on it
How I have done it before:
from sklearn.svm import LinearSVC
from numpy import genfromtxt,savetxt
load = lambda x: genfromtxt(open(x,"r"),delimiter = ",",dtype = "f8")[1:]
dataset = load("train.csv")
train = [x[1:] for x in dataset]
target = [x[0] for x in dataset]
test = load("test.csv")
linear = LinearSVC()
linear.fit(train,target)
savetxt("digit2.csv",linear.predict(test),delimiter = ",", fmt = "%d")
Which worked fine because of the format. Al the data was in one file.
If you want to process each image individually (assuming you're using PIL or Pillow) then do so sequentially:
import os
from glob import glob
try:
# PIL
import Image
except ImportError:
# Pillow
from PIL import Image
def process_image(img_path):
print "Processing image: %s" % img_path
# Open the image
img = Image.open(img_path)
# Do your processing here
print img.info
# Not strictly necessary, but let's be explicit:
# Close the image
del img
images_dir = "/home/user/images"
if __name__ == "__main__":
# List all JPEG files in your directory
images_list = glob(os.path.join(images_dir, "*.jpg"))
for img_filename in images_list:
img_path = os.path.join(images_dir, img_filename)
process_image(img_path)
Read the documentation on python glob module and in a loop process each of the images in turn.
I am trying to write my first real python function that does something real. What i want to accomplish is searching a given folder, and then open all images and merging them together so they make a filmstrip image. Imagine 5 images stacked on top of eachother in one image.
I have this code now, which should be pretty much ok, but propably needs some modification:
import os
import Image
def filmstripOfImages():
imgpath = '/path/here/'
files = glob.glob(imgpath + '*.jpg')
imgwidth = files[0].size[0]
imgheight = files[0].size[1]
totalheight = imgheight * len(files)
filename = 'filmstrip.jpg'
filmstrip_url = imgpath + filename
# Create the new image. The background doesn't have to be white
white = (255,255,255)
filmtripimage = Image.new('RGB',(imgwidth, totalheight),white)
row = 0
for file in files:
img = Image.open(file)
left = 0
right = left + imgwidth
upper = row*imgheight
lower = upper + imgheight
box = (left,upper,right,lower)
row += 1
filmstripimage.paste(img, box)
try:
filmstripimage.save(filename, 'jpg', quality=90, optimize=1)
except:
filmstripimage.save(miniature_filename, 'jpg', quality=90)")
How do i modify this so that it saves the new filmstrip.jpg in the same directory as I loaded the images from? And it probably has some things that are missing or wrong, anybody got a clue?
Related question: How to generate a filmstrip image in python from a folder of images?
It is not an answer to your question, but It might be helpful:
#!/usr/bin/env python
from PIL import Image
def makefilmstrip(images, mode='RGB', color='white'):
"""Return a combined (filmstripped, each on top of the other) image of the images.
"""
width = max(img.size[0] for img in images)
height = sum(img.size[1] for img in images)
image = Image.new(mode, (width, height), color)
left, upper = 0, 0
for img in images:
image.paste(img, (left, upper))
upper += img.size[1]
return image
if __name__=='__main__':
# Here's how it could be used:
from glob import glob
from optparse import OptionParser
# process command-line args
parser = OptionParser()
parser.add_option("-o", "--output", dest="file",
help="write combined image to OUTPUT")
options, filepatterns = parser.parse_args()
outfilename = options.file
filenames = []
for files in map(glob, filepatterns):
if files:
filenames += files
# construct image
images = map(Image.open, filenames)
img = makefilmstrip(images)
img.save(outfilename)
Example:
$ python filmstrip.py -o output.jpg *.jpg
I think if you change your try section to this:
filmstripimage.save(filmstrip_url, 'jpg', quality=90, optimize=1)
In the case you are not joking there are several problems with your script e.g. glob.glob() returns list of filenames (string objects, not Image objects) therefore files[0].size[0] will not work.
as J. F. Sebastian mentioned, glob does not return image objects... but also:
As it is right now, the script assumes the images in the folder are all the same size and shape. This is not often a safe assumption to make.
So for both of those reasons, you'll need to open the images before you can determine their size. Once you open it you should set the width, and scale the images to that width so there is no empty space.
Also, you didn't set miniature_filename anywhere in the script.