Lets assume that I have a folder.
The folder contains photos.
I want to pick a random one and, lets say, use different effects on them with pillow, the PIL fork.
How to?
Perhaps something like:
Get a list of the images in the folder.
Get the count of images in
that list.
Generate a random number that falls in the range of your
image count.
Load the image from the list that matches your random
number.
Since you didn't specify a specific language or runtime environment, I've just generalized a possible way of doing this.
Something like:
import random, glob
picture_files = glob.glob(picture_folder + '*.jpg')
random_picture = random.choice( picture_files)
# do something with random_picture
Related
I'm doing a convolutional neural network classification and all my training tiles (1000 of them) are in geotiff format. I need to get all of them to a numpy array, but I only found code that will do it for one tiff file at a time.
Is there a way to convert a whole folder of tiff files at once?
Thanks!
Try using a for loop to go through your folder
Is your goal to get them into 1000 different numpy arrays, or to 1 numpy array? If you want the latter, it might be easiest to merge them all into a larger .tiff file, then use the code you have to process it.
If you want to get them into 1000 different arrays, this reads through a directory, uses your code to make a numpy array, and sticks them in a list.
import os
arrays_from_files = []
os.chdir("your-folder")
for name in os.listdir():
if os.path.isfile(name):
nparr = ##use your code here
arrays_from_files.append(nparr)
It might be a good idea to use a dictionary and map filenames to arrays to make debugging easier down the road.
import os
arrays_by_filename = {}
os.chdir("your-folder")
for name in os.listdir():
if os.path.isfile(name):
nparr = ##use your code here
arrays_by_filename[name] = nparr
I was wondering what is the bast way to use glob.glob in python to manipulate every nth image, lets say I have a folder of ten images and I want to invert every second image.
from PIL import Image, ImageOps
import glob
def main():
for name in glob.glob('*.png'):
im = Image.open(name)
im_invert = ImageOps.invert(im)
im_invert.save('New' + name, quality=100)
main()
It highly depends on how your files are sorted (or how you would like to see your files sorted).
Plus, glob.glob provides a list of unsorted file names (see glob).
Having a issue with my code. I'm getting a list index out of range index error
import os
import moviepy.video.io.ImageSequenceClip
image_folder= r'C:\Users\Porsche\OneDrive - Imperial College London\Documents\plates'
fps=1
image_files = [image_folder+'/'+img for img in os.listdir(image_folder) if img.endswith(".jpeg")]
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)
clip.write_videofile('my_video.mp4')
I'm new to Python and I can't seem to see where the index is and the documentation I found for moviepy was not clear.
the error is on this line
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)
I just used ImageSequenceClip 5 minutes ago to successfully make a small video so maybe I can assist.
Below are issues related to what I saw in your code and related to problems I had with ImageSequenceClip also. I didn't experience an index error similar to what you've mentioned, but that may be due to your list comprehension line.
A few general suggestions--maybe this will be enough or helpful in other projects you work on:
Careful with your '/' and '\'; keep these uniform to avoid any unwanted issues popping up. I typically use / in all cases for Windows filesystems and it seems to work fine. Also, when manually combining path+filename variables don't forget to include a final '/' at the end of the path variable.
Print out and check the length of the image_files variable you create to make sure you are actually adding the files you wanted and there are no other obvious issues with your list comprehension line.
If you can't locate the issue causing the index error, you can try adding just the folder with the image files only (instead of a list of individual image file locations). In this case, you might need to make a new folder with the files you want included only.
the fps argument was counterintuitive, for me at least. The lower the value, the longer the duration of the individual images in the video.
Finally, the directory you provide to the ImageSequenceClip function will sort the files in alphanumeric order based on the filenames. Keep this in mind as, for example, a1, a2, a11 will be reordered into a1, a11, a2.
So I have this bit of code, which clips out a shapefile of a tree out of a Lidar Pointcloud. When doing this for a single shapefile it works well.
What I want to do: I have 180 individual tree shapefiles and want to clip every file out of the same pointcloud and save it as a individual .las file.
So in the end I should have 180 .las files. E.g. Input_shp: Tree11.shp -> Output_las: Tree11.las
I am sure that there is a way to do all of this at once. I just dont know how to select all shapefiles and save the output to 180 individual .las files.
Im really new to Python and any help would be appreciated.
I already tried to get this with placeholders (.format()) but couldnt really get anywhere.
from WBT.whitebox_tools import WhiteboxTools
wbt = WhiteboxTools()
wbt.work_dir = "/home/david/Documents/Masterarbeit/Pycrown/Individual Trees/"
wbt.clip_lidar_to_polygon(i="Pointcloud_to_clip.las", polygons="tree_11.shp", output="Tree11.las")
I don't have the plugin you are using, but you may be looking for this code snippet:
from WBT.whitebox_tools import WhiteboxTools
wbt = WhiteboxTools()
workDir = "/home/david/Documents/Masterarbeit/Pycrown/Individual Trees/"
wbt.work_dir = workDir
# If you want to select all the files in your work dir you can use the following.
# though you may need to make it absolute, depending on where you run this:
filesInFolder = os.listDir(workDir)
numberOfShapeFiles = len([_ for _ in filesInFolder if _.endswith('.shp')])
# assume shape files start at 0 and end at n-1
# loop over all your shape files.
for fileNumber in range(numberOfShapeFiles):
wbt.clip_lidar_to_polygon(
i="Pointcloud_to_clip.las",
polygons=f"tree_{fileNumber}.shp",
output=f"Tree{fileNumber}.las"
)
This makes use of python format string templates.
Along with the os.listdir function.
I have a question regarding logging for somescript.py
The script performs some actions to find matches for words the user is looking for in some pages that have become unreadable due to re-formatting and printing of the pages.
Because of this, OCR techniques don't work for us anymore so i've come up with a script that compares countours of words to find matches.
the script looks something like:
import cv2
from cv2 import *
import numpy as np
method = cv.CV_TM_SQDIFF_NORMED
template_name = "this.png"
image_name = "3.tif"
needle = cv2.imread(template_name)
haystack = cv2.imread(image_name)
# Convert to gray:
needle_g = cv2.cvtColor(needle, cv2.CV_32FC1)
haystack_g = cv2.cvtColor(haystack, cv2.CV_32FC1)
# Attempt match
d = cv2.matchTemplate(needle_g, haystack_g, cv2.cv.CV_TM_SQDIFF_NORMED)
#we want the minimum squared difference
mn,_,mnLoc,_ = cv2.minMaxLoc(d)
print mnLoc
# Draw the rectangle
MPx,MPy = mnLoc
trows,tcols = needle_g.shape[:2]
#Normed methods give better results, ie matchvalue = [1,3,5], others sometimes showserrors
cv2.rectangle(haystack, (MPx,MPy),(MPx+tcols,MPy+trows),(0,0,255),2)
cv2.imshow('output',haystack)
cv2.waitKey(0)
import sys
sys.exit(0)
Now i want to log the various tasks that the script performs, like
converting the image to grayscale
attempting a match
drawing the rectangle
I have seen a few scripts on stackoverflow explaining how to log an entire script or the entire output but i haven't found anything that just logs a few actions.
Also i would like to add the date and time the activity was performed.
Furthermore i have wrote a function that calculates an MD5 and SHA1 hash of the input file, for this particular case, that is for 'this.png' and '3.tif', I have yet to implement this piece of code but would it be easy to log that as well?
I am a python-noob so if the anwsers are obvious to you guys you know why i couldn't figure it out myself.
I hope you can help me out on this one!