I have some images in a folder and if their dimensions are not what I want, I copy them to another folder and then resize them using the thumbnail command. After I've done that I want to rename them and as part of their new name I want to include the pixel sizes.
Anyway I've tried my code and I run into the following error:
File "C:/Anaconda/PhD/Scikit-Learn/Image Resizing3.py", line 55, in resize_img
os.rename(image_directory + '/Resized'+ "/" + image_filenames[i],image_directory + '/Resized'+ "/" + image_filenames[i][0:(len(image_filenames[i])-4)]+ str(img1.size[0]) + ' x ' + str(img1.size[1]) + '.jpg' )
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:
I thought if I used the with keyword that it would close any processes I was using.
If anyone can see any problems in my code wrt to the error then I'd really appreciate it if you have a solution for it.
import scipy.io as sio
from matplotlib import pyplot as plt
from matplotlib import image as mpimg
from PIL import Image
from collections import OrderedDict
import shutil as sh
import os
image_directory = 'C:/StreetView/Labelled Images with Classes/Folder1 /Labelled/Classes/wood'
def resize_img(image_directory, pixel_width, pixel_height):
image_filenames = []
DIR = os.listdir(image_directory)
for n in DIR:
if n.endswith('.jpg'):
image_filenames.append(n)
image_sizes = []
images = []
for i in range(len(image_filenames)):
with Image.open(image_directory + '/' + image_filenames[i]) as images:
image_sizes.append(tuple(images.size))
ordered_imsize = tuple(OrderedDict.fromkeys(image_sizes))
pixarea = []
for i in range(len(ordered_imsize)):
arg1 = ordered_imsize[i][0]
arg2 = ordered_imsize[i][1]
pixarea.append(arg1 * arg2)
print('The maximum pixel area is', max(pixarea))
print('The image dimensions giving the largest area is:', ordered_imsize[pixarea.index(max(pixarea))] )
print('The minimum pixel area is', min(pixarea))
print('The image dimensions giving the smallest area is:', ordered_imsize[pixarea.index(min(pixarea))] )
if not os.path.exists(image_directory + '/Resized'):
os.mkdir(image_directory + '/Resized') # Then make the folder
for i in range(len(image_directory)):
if (image_sizes[i][0] >= 100) or (image_sizes[i][1] >= 400):
print('Inside the greater than loop')
sh.copy(image_directory + "/" + image_filenames[i],image_directory + '/Resized')
image_sizes1 = []
with Image.open(image_directory + '/Resized'+ "/" + image_filenames[i]) as img1: # need to use the with keyword because this makes sure the file is closed after its been used so it doesn't cause any conflicts like it did when it wasn't used.
print('Checking size: ', img1.size)
img2 = img1.thumbnail((pixel_width,pixel_height)) # img1 is not the thumbnail
image_sizes1.append(tuple(img1.size))
os.rename(image_directory + '/Resized'+ "/" + image_filenames[i],image_directory + '/Resized'+ "/" + image_filenames[i][0:(len(image_filenames[i])-4)]+ str(img1.size[0]) + ' x ' + str(img1.size[1]) + '.jpg' )
print('Image number', i, 'has been resized')
else:
print('inside the else loop')
sh.copy(image_directory + "/" + image_filenames[i],image_directory + '/Resized')
image_sizes2 = []
with Image.open(image_directory + '/Resized'+ "/" + image_filenames[i]) as img3:
image_sizes2.append(tuple(img3.size))
img3.save(image_directory + '/Resized' + "/" + image_filenames[i][0:len(image_filenames[i])-4] + '_' + str(img3.size[0]) + 'x' + str(img3.size[1]) + ".jpg")
#os.remove(image_directory + '/Resized'+ "/" + image_filenames[i])
print('Image number', i, 'has been copied over and not resized')
resize_img(image_directory,100,400)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
Solved it, I used shutil.move instead of os.rename.
Related
import numpy as np
# load all images in a directory
from os import listdir
from matplotlib import image
# load all images in a directory
loaded_images = list()
path='/content/IDC_regular_ps50_idx5'
for big_folder in listdir(path):
for folder in listdir(path + '/' + big_folder ):
for filename in listdir(path + '/' + big_folder + '/' + folder):
# load image
img_data = image.imread(path + '/' + big_folder +'/' + folder + '/' +filename)
# store loaded image
loaded_images.append(np.vstack(img_data))
#print('> loaded %s %s' % (filename, img_data.shape))
when i press np.array(loaded_images).shape I'm getting (277524) which is the numbers of images , what I desire is the 4D (277524 , 3 , 50 , 50 ) .
note : when I do loaded_images[i].shape I get (3 , 50 ,50 )
I have two types (A and B) of images in one directory and I want to add them together (not concatenate) them like this:
A1.jpeg + B1.jpeg = Merged1.jpeg
A2.jpeg + B2.jpeg = Merged2.jpeg
...
AN.jpeg + BN.jpeg = MergedN.jpeg
I don't know how to customize my code so it would work for the whole directory:
import cv2
import os
for i,filenames in os.walk('.'):
A1 = cv2.imread('A1.jpeg',0)
B1 = cv2.imread('B1.jpeg',0)
image = cv2.add([A1,B1])
filename = ('Merged' + {i} + '.jpeg')
cv2.imwrite(filename, image)
Any ideas? Thanks
EDIT:
I added counter in for loop, because you cannot define for loop in the way I did before.
import cv2
import os
i=0
for filenames in os.walk('.'):
i = i + 1
A = "A" + str(i) + ".jpeg"
B = "B" + str(i) + ".jpeg"
Ai = cv2.imread(A,0)
Bi = cv2.imread(B,0)
image = cv2.add([Ai,Bi])
filename = ('Merged' + str(i) + '.jpeg')
cv2.imwrite(filename, image)
But it only adds A1 and B1. Is this a wrong way to count in for loop?
Just change the filename in imread with a custom variable which you can use i in.
A = "A" + str(i) + ".jpeg"
B = "B" + str(i) + ".jpeg"
Ai = cv2.imread(A,0)
Bi = cv2.imread(B,0)
I assumed that i is a number.
You can use glob for that it will be easier i think
import glob
for i, a_file in enumerate(glob.glob('./A*')):
A = cv2.imread(a_file,0)
B = cv2.imread(a_file.replace('A', 'B'),0)
image = cv2.add([A,B])
filename = ('Merged' + {i} + '.jpeg')
cv2.imwrite(filename, image)
I solved it like this:
import glob
import cv2
number_of_images = 750
for a_file in glob.glob('./A*'):
for i in range(1,number_of_images):
A = "A" + str(i) + ".jpeg"
B = "B" + str(i) + ".jpeg"
A1 = cv2.imread(A,0)
B1 = cv2.imread(B,0)
image = cv2.add([A1,B1])
filename = ('Merged' + str(i) + '.jpeg')
cv2.imwrite(filename, image)
print(i)
if i==number_of_images-1:
break
Thanks for your advices!
dump.pbd='pdb' + pdbFile + '_' + 'res' + residMin + '_' residMax + '.pdb'
the program keep giving me syntax error when I run it.
import re
import sys
import os
import time
from sys import argv
import xmltodict
if len(sys.argv) < 3:
message = '\n Get protein file in the form of pdf file from pdb website. \n\n Usage: '+sys.argv[0] + ' [4-letter PDBid] [resid range] \n' + ' Example: ' + sys.argv[0] + ' 2rh1 53-71\n' + ' Output File: pdb2rh1_res53-71.pdb'
print (message)
exit()
pdbID=sys.argv[1]
residRange=sys.argv[2]
residData=residRange.split('-')
residMin=int(residData[0])
residMax=int(residData[1])
twoletter=pdbID[1:3]
xmlfile=pdbID + '.xml'
pdbgzfile=pdbID + '.pdb.gz'
pdbFile=pdbID+'.pdb'
dump.pbd='pdb' + pdbFile + '_' + 'res' + residMin + '_' residMax + '.pdb'
wgetcom='wget https://files.rcsb.org/view/'+pdbFile+' -O '+pdbFile
print(wgetcom)
os.system(wgetcom)
f = open (pdbFile,'r')
k = 0
rc = 0
data = f.readlines()
g = open (dump.pdb, 'w')
for linedata in data:
line=linedata.strip()
words = line.split()
if(words[0] == 'ATOM'):
k=k+1
words[5]=int(line[22:26].strip())
if(words[5] in range(residMin,residMax+1)):
g.write(linedata)
for i in words:
if(i=='CA'):
rc = rc+1
print(rc)
the code is not working because it is giving me a syntax error for line number 22 that states dump.pbd='pdb' + pdbFile + '' + 'res' + residMin + '' residMax + '.pdb'. so can you please help me with that?
Thanks so much on advance!
You've forgotten to add a + sign.
This line should work: dump.pbd='pdb' + pdbFile + '' + 'res' + residMin + '' + residMax + '.pdb'
There must be a + sign between '_' and residMax as this is the Python concatenating strings syntax.
In the code below, my problem is that it's writing output to all folders based on only one input file. Can some one give me a hint and check if my code is looping properly?
import libxml2
import os.path
from numpy import *
from cfs_utils import *
np=[1,2,3,4,5,6,7,8]
n=[20,30,40,60,80,100,130]
solver=["CG_iluk", "CG_saamg", "CG_ssor", "BiCGSTABL_iluk", "BiCGSTABL_saamg", "BiCGSTABL_ssor", "cholmod", "ilu" ]
file_list=["eval_CG_iluk_default","eval_CG_saamg_default", "eval_CG_ssor_default", "eval_BiCGSTABL_iluk", "eval_BiCGSTABL_saamg", "eval_BiCGSTABL_ssor","simp_cholmod_solver_3D_evaluate ", "simp_ilu_solver_3D_evaluate" ]
for sol in solver:
i=0
for cnt_np in np:
#open write_file= "Graphs/" + "Np"+ cnt_np + "/CG_iluk.dat"
#"Graphs/Np1/CG_iluk.dat"
write_file = open("Graphs/"+ "Np"+ str(cnt_np) + "/" + sol + ".dat", "w")
#loop through different unknowns
for cnt_n in n:
#open file "cfs_calculations_" + cnt_n +"np"+ cnt_np+ "/" + file_list(i) + "_default.info.xml"
read_file = "cfs_calculations_" +str(cnt_n) +"np"+ str(cnt_np) + "/" + file_list[i] + ".info.xml"
#read wall and cpu time and write
if os.path.exists(read_file):
doc = libxml2.parseFile(read_file)
xml = doc.xpathNewContext()
walltime = xpath(xml, "//cfsInfo/sequenceStep/OLAS/mechanic/solver/summary/setup/timer/#wall")
cputime = xpath(xml, "//cfsInfo/sequenceStep/OLAS/mechanic/solver/summary/setup/timer/#cpu")
unknowns = 3*cnt_n*cnt_n*cnt_n
write_file.write(str(unknowns) + "\t" + walltime + "\t" + cputime + "\n")
doc.freeDoc()
write_file.close()
i=i+1
Problem solved, I = o, was outside the loop
I have the following code which creates the txt file I require from a shp.file with the data I need. I have a folder called profiles containing a few number of shape files named (profil1.shp, profil2.shp, profil3.shp etc.). I was wondering how to create a loop so that the script creates for each file a txt file with the same name (eg. for profil1.shp create profil1.txt, profil2.shp create profil2.txt and so on).
import ogr, os, sys, osr
os.chdir('..\profiles')
file = open('profil1.txt', 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open('profil1.shp', 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()
edit: the code is returning a Could not open file.Photo of the folder containing the files and their respective names. Safe to assume I am doing something wrong.
import ogr, os, sys, osr,os.path
os.chdir = ('C:\Users\Andrei\Desktop\profil3')
l = os.listdir('C:\Users\Andrei\Desktop\profil3')
for i in l:
if i.endswith('.shp'):
s1 = s.split('.')[0] + '.txt'
file = open(s1, 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open(i, 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()
You can use os.listdir() to list the files and folders in the current directory.
This returns a list of all files in the current directory (or the directory given to it as parameter , if no parameter is specified it checks the current directory) .
Then you can check for files with the name ending with .shp using string.endswith() function and then use that to create your new files.
Example of a small portion -
import os , os.path
l = os.listdir()
for i in l:
if i.endswith('.shp'):
s1 = s.split('.')[0] + '.txt'
At the end s1 would contain the file with extension as .txt .
Then you can do your logic on this file, and keep on doing like this.
Full code would look something like -
import ogr, os, sys, osr,os.path
os.chdir('..\profiles')
l = os.listdir()
for i in l:
if i.endswith('.shp'):
s1 = s.split('.')[0] + '.txt'
file = open(s1, 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open(i, 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()
A better way of openning files, etc is using with statement. Look up its tutorial here.