Ошибка памяти в моей программе кадрирования и стека - PullRequest
1 голос
/ 14 февраля 2020

Я недавно начал изучать программирование и наконец написал свою первую программу. Эта программа вводит все изображения в папку и обрезает их до определенного размера. Затем эти изображения располагаются вертикально, чтобы создать новое изображение. Итак, я запускал тестовые изображения через мою программу, и она, казалось, работала нормально. Но я использовал только 10 изображений одновременно. Когда я решил, наконец, попробовать программу для предназначенной мне цели, для которой требуется более 500 изображений, программа вылетает. Я получаю MemoryError. Так как я только начал, я написал вместе все, что я думал, будет работать, был ли это самый эффективный метод или нет. Если у кого-то есть время, есть ли в моем коде явные вещи, которые просто потребляют слишком много ресурсов.

from PIL import Image
from natsort import natsorted
import glob

# Convert coordinate list into variables
print("Type in the coordinates for the upper left (x1,y1) and bottom right (x2,y2) points")
coordinates = list(map(int, input("Separate values with a space (x1 y1 x2 y2): ").strip().split()))[:4]
x1, y1, x2, y2 = coordinates
print("Generating image...")

# creating lists to hold the initial files and the edited files
image_list = []
cropped_images = []

# Accessing all the files using the glob module
# The function natsorted sorts values the way Windows does
# Opens all the files with the variable img in folder and adds them one by one to a list named image_list
for filename in natsorted(glob.glob("C:\\Users\\Alex\\Desktop\\One Dimensional Reaction Diffusion Program\\data\\*.tiff")):
    img = Image.open(filename)
    image_list.append(img)

# for each image in the image_list
# selected_region from previous user input
# cropped_region applied the crop function for the images in the selected region
    # Cropping function
    selected_region = (x1, y1, x2, y2)
    cropped_region = image.crop(selected_region)  # unsure if this is correct
    # If cropped area is vertical, rotate into horizontal position
    if (y2 - y1) > (x2 - x1):
        rotated_image = cropped_region.rotate(90, expand=1)  # Expand 1 ensures image isn't cut off while rotating
    else:
        rotated_image = cropped_region  # Does nothing if image is horizontal
    cropped_images.append(rotated_image)  # appends all rotated_images to the list cropped_images

# Size of each individual image
widths, heights = zip(*(i.size for i in cropped_images))

# Final image dimensions
max_width = max(widths)
total_height = sum(heights)

# Create a new colored image (RGB)
new_img = Image.new('RGB', (max_width, total_height))

# Stacking function
# to offset horizontally, need to change final image dimensions to sum(widths) and max(heights)
# and change new_im.paste(img, (x_offset,0))
y_offset = 0  # Initial position is 0
for img in cropped_images:  # Not sure if img will cause conflict because img used in above for loop
    new_img.paste(img, (0, y_offset))  # (x,y) indicates which direction to offset in
    y_offset += img.size[1]  # location of new image is y_offset (which had position 0) + the height of the image

new_img.save("C:\\Users\\Alex\\Desktop\\One Dimensional Reaction Diffusion Program\\output\\stacked.tiff", quality=95)
...