Last active
January 3, 2016 08:49
-
-
Save Cosmologist/8438822 to your computer and use it in GitHub Desktop.
Split the image into several vertical images - http://pickbox.ru/e/242
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
#-*- coding: utf-8 -*- | |
def split_vertical(im, separator_color=None): | |
""" | |
Split the image into several vertical images. | |
Split points defined by solid vertical strip of a background color | |
""" | |
# Original image size | |
image_width = im.size[0] | |
image_height = im.size[1] | |
# Convert the image to black and white colors | |
bw_im = im.convert('L') | |
bw_im = bw_im.point(lambda x: 0 if x < 128 else 255, '1') | |
# Accepted for background color - the color of the first pixel | |
if separator_color is None: | |
separator_color = bw_im.getpixel((0, 0)) | |
# Looking for vertical border lines | |
# Border line is x-position there all pixels have backround color | |
# or non-background color not contact with non-background color from previous x-position | |
lines = [] | |
for x in range(0, image_width): | |
for y in range(0, image_height): | |
# If line pixel has non-bg color | |
if bw_im.getpixel((x,y)) != separator_color: | |
# Check - is this pixel contact any non-bg pixel from previous line | |
if x != 0: | |
if bw_im.getpixel((x-1, y)) != separator_color or\ | |
(y > 0 and bw_im.getpixel((x-1, y-1)) != separator_color) or\ | |
(y < (image_height-1) and bw_im.getpixel((x-1, y+1)) != separator_color): | |
break | |
# If we have reached the bottom of the image, then this line is solid with bg color | |
if y == (image_height - 1): | |
lines.append(x) | |
# Split images | |
images = [] | |
# Point of the previous split | |
prev_split_point = 0 | |
# looking for the split points | |
for i, line in enumerate(lines): | |
# Ignore first border lines | |
if line == 0: | |
continue | |
# If it is first border line or the previous line is not border line | |
if i == 0 or (line - lines[i-1]) > 1: | |
# Cut the image | |
images.append(im.crop((prev_split_point, 0, line, image_height))) | |
# Save current split point | |
prev_split_point = line | |
# If it is a last line and this line is not have last x-position in image - then get left image piece | |
if (i == (len(lines) - 1)) and (line != (image_width - 1)): | |
images.append(im.crop((line, 0, image_width, image_height))) | |
return images |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment