I have a program that searches for objects based on color position and sharpness. I cut out a 140x140 pixel image of the found objects. But there are some images that are not this size due to some error. And my sharpness determinant always returns those that are smaller in size. My question is how can I iteratively go through a folder and delete only images that are not 140x140 pixels in size.
Check out this tutorial, it helps with the iteration of files in a given directory given an extension (.jpg, .png, etc.)
Find all files in a directory with extension .txt in Python
To actually change the files, I'm not too sure, but probably something like python os.
This is one way among many different ways you can do this. Just make sure you test it before running any batch deletion as this will remove files without cautioning.
import os
import cv2
img = cv2.imread('/absolute/path/to/your/file', cv2.IMREAD_GRAYSCALE)
h, w = img.shape
if(not (h == 140 and w == 140)):
os.remove('/absolute/path/to/your/file')
As for iterating over files in a directory there's already a SO thread that poses multitude of solutions:
How can I iterate over files in a given directory?
import os
import cv2
img = cv2.imread('/yourfile', cv2.IMREAD_GRAYSCALE)
h, w = img.shape
if(not (h == and w == 140)):
os.remove('/absolute/path/to/your/file')
Related
In short, I have written a code that opens up a file and does a number of modifications on it. However, I don't want to keep going through my script and renaming all the files when I want to open up a new file.
I'm thinking of setting a variable early on that defines the filename, i.e.
A=filename('png1.png')
B=filename('png2.png')
However, I don't quite know how to implement this. This is my current code:
import os
from os import path
import numpy as np
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
#d=path.dirname(_file_) if "_file_" in locals() else os.getcwd()
os.chdir('C:/Users/Sams PC/Desktop/Word_Cloud_Scripts/Dmitrys Papers/Word_Cloud_Dmitry')
Document=open('Dmitry_all_lower.txt', 'r', encoding='utf-8')
text=Document.read()
heart_mask=np.array(Image.open("**png1.png**"))
print (heart_mask)
split= str('**png1.png**').rsplit('.')
extension=split[len(split)-1]
if extension == "png":
image = Image.open("**png1.png**")
image.convert("RGBA") # Convert this to RGBA if possible
canvas = Image.new('RGBA', image.size, (255,255,255,255)) # Empty canvas colour (r,g,b,a)
canvas.paste(image, mask=image) # Paste the image onto the canvas, using it's alpha channel as mask
#canvas.thumbnail([width, height], Image.ANTIALIAS)
canvas.save('**png2.png**')
from wand.image import Image
with Image(filename='**png2.png**') as img:
img.format='jpeg'
img.save(filename='**png1.jpg**')
from PIL import Image
heart_mask=np.array(Image.open("**png1.jpg**"))
else:
print ('')
print (heart_mask)
stopwords=set(STOPWORDS)
stopwords.update(["will", "us","protein","residue", "interaction","residues","using","proteins","thus","fig"])
wc= WordCloud(stopwords=stopwords, background_color="white",max_words=1000, mask=heart_mask, contour_width=3, contour_color='black')
print ('Generating Word Cloud')
wc.generate(text)
wc.to_file("Dmitry3.png")
import matplotlib.pyplot as plt
plt.figure()
plt.imshow(wc,interpolation="bilinear")
plt.axis("off")
print ('Generation Done')
plt.show()
I've put the entire thing just to see what's going on, but I've bolded (put stars next to), the files I'm trying to modify in my idea. As you can see, I have multiple calls to my file 'png1.png', and I also have calls to save a modified version of that file to 'png2.png' and later a jpeg version of it 'png1.jpg'. I don't want to have to go through my script each time and change each one individually. I was hoping to define them earlier such as A=png1, B=png2, C=jpg1 so that I can replace the calls in my loops with simply A B and C, and if I do choose a new image to upload, I simply change 1 or 2 lines rather than 5 or 6. I.E.
heart_mask=np.array(Image.open("A"))
split= str('A').rsplit('.')
image = Image.open("A")
canvas.save('B')
... so on and so forth
To make your task easier, perhaps you should establish a naming standard defining which files are to be modified, and which ones are already processed. Also, the images you are to process should have a dedicated directory for the purpose.
From what I understand in your code, PNG files are the ones getting processed, while the JPEG files are already done. You can use os.listdir() to traverse a list of files which have a .png extension, something similar to the one below:
for file in os.listdir( "/dedicated_image_dir" ):
if file.endswith(".png"):
# Process your PNG images here
That way, you wouldn't even need to change your code just to accommodate new PNG images with different filenames.
sorry for my trivial question, but I'm new to Python.
I'm trying to convert a series of JPEG images to BMP format and resize it.
I managed to get the procedure for a single image, but now I can not automate the process so that the conversion happens in sequence.
this is my script
from PIL import Image
img = Image.open("C:/Users/***/Documents/images/1.jpg")
new_img = img.resize((320,240))
new_img.save("C:/Users/***/Documents/immages_bmp/1.bmp")
The images are progressively renamed from 1 to 10000.
Does anyone know how to help me implement a for loop to automate the process?
Thank you so much for your help
Something like:
from PIL import Image
from glob import glob
import os
myDir = '/Users/me/pictures'
pic_list = glob(myDir + os.sep + '*' + '.jpg')
for pic in pic_list:
#resize, use a string replace to name new bmps
img = Image.open(pic)
new_img = img.resize((320,240))
newName = pic.replace(".jpg",".bmp")
new_img.save(newName)
Should catch all the images regardless as to their naming convention, and will allow you to edit the list of names before you resize them (or not).
I have this code which show me all the .tif files in a folder I give.
timestr = datetime.now().strftime('%Y%m%d-%H%M%S%f')
ex_area_files = []
tif_files = glob.glob('C:\\Users\\Bob\\Desktop\\Folder\\' + str(timestr) + '\\EXTRACTED\\*.tif')
ex_area_files = [tif_files]
print(ex_area_files)
How can I move some specified ones (to another folder) ? I mean, I want to move all the .tif files which result of width*height is less/more than a certain value.
What I tried was to loop through the array and, after set the codition, move the files. All the result was a loop fail which blocked all the system :)
It follows...
image = cv2.imread('image.jpg')
height = np.size(image, 0)
width = np.size(image, 1)
condition = (height*width) > 9600
How can I also set ex_area_files (my .tif array) as directory of files from which cv2 can read ? And, more imporant, how to set a file at once ?
The files which satisfy the condition (images with values of 320*30px) should be moved to another directory. How to do it after the program decided that the file is ok to be moved ?
Thanks
Tip: this is a next step after this other piece of code: Exclude images of certain dimensions from process (OpenCV, Python)
In this case, take a look at ex_area14.png. I want to move a series of files like that (but in .tif format..)
I recommend using shutil for moving files. To move them You can use shutil.copy() - I Personally use shutil.copy2()
so try something like this:
import shutil
import opencv
for files in ex_area_files:
if files (PLACE YOUR CONDITION HERE):
`shutil.copy('PATH_OF_file', 'PATH_OF_WHERE_TO_DROP')
EDIT:
So i personally like os.walk(), here i'm looping through the files, and if files endswith .tif, I will read the file with imread get the height and width, and check if that condition is met. You'll have to provide where you want to copy the files to. (Take note of .replace() - imread for some reason likes the slashes like / instead of \)
import shutil
import opencv
import os
for root, dirs, files in os.walk(r'FOLDER HERE'):
for file in files:
if file.lower().endswith('.tif'):
image = cv2.imread(root.replace('\\', '/') + '/' +file
height = np.size(image, 0)
width = np.size(image, 1)
if height*width > 9600:
shutil.copy(root.replace('\\', '/') + '/' +file, 'PATH_OF_WHERE_TO_DROP')
I created a small script that crops 1920x1080 images into a 400 x 400 image from the center. Overall it works fantastically on a set of 100 images but when I try to apply it to my 40K images in my directory it skips a bunch of images. Noticeably it will start skipping hundreds of frames towards the later images.
Here is my code:
import os
import cv2
import glob
images = glob.glob("*.jpg")
for i in images:
img = cv2.imread(i,1)
path = '/home/moocows/PycharmProjects/Aim/croptest/'
crop_img = img[(540-200):(540+200), (960-200):(960+200)]
cv2.imwrite(str(path) + i, crop_img)
I'm starting to wonder if the issue is from glob but I'm not too sure, I'm quite new to programming for forgive me if things are a bit messy.
Sorry for the title... So the goal of this script is to take a folder full on images that are listed in a particular order. Then it chunks the images into groups of 3. From there it takes the 3 images and blends them together using PIL. Now the issue that I have is that the code below does a great job of doing what I want. I can show imgbld2 it'll create 4 images in a temporary folder.
Now my problem is that when I go to save the images using imgbld2.save()it will only save the first created image into 4 image files, instead of 4 created images into 4 separate files.
I can fix this issue by pointing another script to retrieve the images from the temp folder by using glob.glob(). But that would require me to make sure to run the script on a freshly restarted computer but that seems to be too messy for my taste.
Is there a better way to achieve what I'm trying to do? Or there a saving method that I'm missing?
Any help would be appreciated, here is the code:
from PIL import Image
import os.path
import glob
#Lists Directory
Dir = os.listdir('/path/to/Directory/of/Images')
#Glob all jpgs
im = glob.glob( '/path/to/Directory/of/Images/*.jpg')
#sort jpg according to name
imsort = sorted(im)
def chunker(imsort,size = 3):
for i in range(0, len(imsort), size):
yield imsort[i:i + size]
print('what does it look like?')
for j in chunker(imsort):
print(j)
img1 = Image.open(j[0])
img2 = Image.open(j[1])
img3 = Image.open(j[2])
imgbld1 = Image.blend(img1, img2, 0.3)
imgbld2 = Image.blend(imgbld1, img3, 0.3)
imgbld2.show()
imgbld2.save('path/to/new/folder/' + 'blended' , 'JPEG')