I am using Python,Open, Numpy, and Scipy. I have a directory of images that I want to rotate by certain angles. I want to script this. I am using this, OpenCV Python rotate image by X degrees around specific point but it doesn't seem to pipeline exactly as I envisioned. I get an invalid rotation plan specified, but I don't think that I should be getting this.
Here is what my code looks like:
from scipy import ndimage
import numpy as np
import os
import cv2
def main():
outPath = "C:\Miniconda\envs\.."
path = "C:\Miniconda\envs\out\.."
for image_to_rotate in os.listdir(path):
rotated = ndimage.rotate(image_to_rotate, 45)
fullpath = os.path.join(outPath, rotated)
if __name__ == '__main__':
main()
You need to actually read the image file before rotating them. What your current code is doing is just iterating through the names of the files (and directories).
os.listdir(path) gives you a list of contents of the folder (basically just the name) and then you need to open these files using the ndimage.imread() function.
This should work:
from scipy import ndimage, misc
import numpy as np
import os
import cv2
def main():
outPath = "C:\Miniconda\envs\.."
path = "C:\Miniconda\envs\out\.."
# iterate through the names of contents of the folder
for image_path in os.listdir(path):
# create the full input path and read the file
input_path = os.path.join(path, image_path)
image_to_rotate = ndimage.imread(input_path)
# rotate the image
rotated = ndimage.rotate(image_to_rotate, 45)
# create full output path, 'example.jpg'
# becomes 'rotate_example.jpg', save the file to disk
fullpath = os.path.join(outPath, 'rotated_'+image_path)
misc.imsave(fullpath, rotated)
if __name__ == '__main__':
main()
PS: This way of iterating through the contents of the folder only works if there are only files in the directory and no sub-directories. os.listdir(path) will return the names of any files as well as sub-directories.
You can learn how to list only files in a directory from this post: How to list all files of a directory?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With