Snippets

Metadrop Troceado de imagenes en python

Created by Omar

def image_slice(path, prefix, outdir, slice_size):
    """slice an image into parts slice_size tall"""
    img = Image.open(path)

    width, height = img.size
    upper = 0
    left = 0
    slices = int(math.ceil(height/slice_size))

    imgs = []
    count = 1
    for slice in range(slices):
        #if we are at the end, set the lower bou to be the bottom of the image
        if count == slices:
            lower = height
        else:
            lower = int(count * slice_size)  

        bbox = (left, upper, width, lower)
        working_slice = img.crop(bbox)
        upper += slice_size
        #save the slice
        full_path = os.path.join(outdir, "slice_" + prefix + "_" + str(count)+".png")
        working_slice.save(full_path)
        count +=1
        imgs.append(full_path)
    return imgs

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.