Created
May 18, 2013 21:09
-
-
Save ograycode/5605793 to your computer and use it in GitHub Desktop.
Quickly generate images containing your samples and your background images.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Image | |
| import os | |
| import random | |
| training_images = [] | |
| training_path = 'cropped' | |
| background_images = [] | |
| background_path = 'background' | |
| training_file = 'train' | |
| def get_image_list(file_path): | |
| return os.listdir(file_path) | |
| def rotate_randomely(im): | |
| number = random.randint(1, 6) | |
| if number == 1: | |
| return im.transpose(Image.FLIP_LEFT_RIGHT) | |
| elif number == 2: | |
| return im.transpose(Image.FLIP_TOP_BOTTOM) | |
| elif number == 3: | |
| return im.transpose(Image.ROTATE_90) | |
| elif number == 4: | |
| return im.transpose(Image.ROTATE_180) | |
| elif number == 5: | |
| return im.transpose(Image.ROTATE_270) | |
| else: | |
| return im | |
| def get_random_point(maxX, maxY): | |
| x = random.randint(0, maxX) | |
| y = random.randint(0, maxY) | |
| return x, y | |
| def insert_image(from_image, onto_image): | |
| from_image = resize_smaller(from_image, onto_image.size) | |
| x, y = get_random_point(onto_image.size[0] - from_image.size[0], onto_image.size[1] - from_image.size[0]) | |
| onto_image.paste(from_image, (x, y)) | |
| width = from_image.size[0] | |
| height = from_image.size[1] | |
| return x, y, width, height | |
| def resize_smaller(image, maxXY): | |
| if image.size[0] > maxXY[0] or image.size[1] > maxXY[1]: | |
| image = image.resize((image.size[0] / 2, image.size[1] / 2)) | |
| if image.size[0] > maxXY[0] or image.size[1] > maxXY[1]: | |
| resize_smaller(image, maxXY) | |
| else: | |
| return image | |
| training_images = get_image_list(training_path) | |
| background_images = get_image_list(background_path) | |
| index = 0 | |
| for training_image in training_images: | |
| for background_image in background_images: | |
| name = background_image | |
| training_img = Image.open(os.path.join(training_path, training_image)) | |
| background_image = Image.open(os.path.join(background_path, background_image)) | |
| training_img = rotate_randomely(training_img) | |
| x, y, width, height = insert_image(training_img, background_image) | |
| full_name = 'images/' + str(index) + name | |
| background_image.save(full_name) | |
| with open("train", "a") as f: | |
| f.write(full_name) | |
| f.write(' ') | |
| f.write('1 ' + str(x) + ' ' + str(y) + ' ' + str(width) + ' ' + str(height)) | |
| f.write('\n') | |
| index = index + 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment