-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththeCropper.py
88 lines (59 loc) · 2.4 KB
/
theCropper.py
1
from PIL import Imageimport mathimport osdef getMinImageSize(imageFilepaths): sizes = [] for fp in imageFilepaths: sizes.append(getSize(fp)) minWidth = min(sizes, key=lambda e: e[0])[0] minHeight = min(sizes, key=lambda e: e[1])[1] return minWidth, minHeightdef displayMinImageSize(imageFilepaths): minWidth, minHeight = getMinImageSize(uncroppedImagePaths) print(f"min width: {minWidth}") print(f"min height: {minHeight}") def cropImage(filePath, size): halfWidth = size[0] / 2 halfHeight = size[1] / 2 with Image.open(filePath) as img: cx, cy = (img.size[0] // 2, img.size[1] // 2) # (l, t, r, b) cropBox = (math.floor(cx-halfWidth), math.floor(cy-halfHeight), math.floor(cx+halfWidth), math.floor(cy+halfHeight)) # Do cropping magic croppedImg = img.crop(cropBox) # return cropped image return croppedImg def getSize(filePath): with Image.open(filePath) as img: size = img.size return sizedef cropImages(rawImageFolderName, outputFolderName): fileNames = [filename for filename in os.listdir(f"./{rawImageFolderName}")] uncroppedImagePaths = [f"{rawImageFolderName}/{filename}" for filename in fileNames] croppedImagePaths = [f"{outputFolderName}/{filename}" for filename in fileNames] croppingDimensions = (400, 400) allCroppingSuccessful = True for filename, inputPath, outputPath in zip(fileNames, uncroppedImagePaths, croppedImagePaths): try: croppedImg = cropImage(inputPath, croppingDimensions) croppedImg.save(outputPath) croppedImg.close() except Error as e: allCroppingSuccessful = False return allCroppingSuccessfuldef main(): # For our training images success = cropImages("training_raw_images", "training_cropped_images") assert success print("Cropping training raw images successful") # For our validation images success = cropImages("testing_raw_images", "testing_cropped_images") assert success print("Cropping testing raw images successful") # For our validation colored images success = cropImages("testing_colored_images", "testing_colored_cropped_images") assert success print("Cropping validation colored images successful") print("Finished all cropping")if __name__ == "__main__": main()