|
发表于 2022-8-25 10:05:22
|
显示全部楼层
- #!/usr/bin/env python
- #coding=utf-8
- from PIL import Image
- import numpy as np
- import sys
- from glob import glob
- import os
- import shutil
- bg_color = (0, 0, 0xfe)
- def max(a, b): return a if a > b else b
- def min(a, b): return a if a < b else b
- def is_background(pic, y, x, tolerance = 0x30):
- color = pic.getpixel((x, y))
- for i in range(3):
- if bg_color[i] + tolerance < color[i]: return False
- if bg_color[i] - tolerance > color[i]: return False
- return True
- def is_contain(location, y, x):
- for i in location:
- if (i[0] <= x <= i[2]) and (i[1] <= y <= i[3]): return True
- return False
- def find_block_sub(pic, y, x, buff):
- if is_background(pic, y, x): return None
- if buff[y][x]: return None
- result = [x, y, x, y]
- buff[y][x] = 1
- for i in [[0, -1], [-1, 0], [0, 1], [1, 0]]:
- temp = find_block_sub(pic, y + i[0], x + i[1], buff)
- if temp:
- result[0] = min(result[0], temp[0])
- result[1] = min(result[1], temp[1])
- result[2] = max(result[2], temp[2])
- result[3] = max(result[3], temp[3])
- #buff[y][x] = 0 # 我感觉不复位,对这个程序也问题不大
- return result
- def find_block(pic, y, x, size): return find_block_sub(pic, y, x, np.zeros(size))
- def format(location, margin = 5):
- for i in location:
- i[0] -= margin
- i[1] -= margin
- i[2] += margin
- i[3] += margin
- width = i[2] - i[0]
- height = i[3] - i[1]
- distance = abs(width - height) / 2
- if width == height: continue
- if width > height:
- i[1] -= distance
- i[3] += distance
- else:
- i[0] -= distance
- i[2] += distance
- def generate_pic(result_path, filename):
- location = []
- pic = Image.open(filename)
- width, height = pic.size
- for y in range(height):
- for x in range(width):
- if not is_background(pic, y, x):
- if not is_contain(location, y, x):
- location.append(find_block(pic, y, x, (height, width)))
- format(location)
- for i in range(len(location)):
- pic.crop(location[i]).save(result_path + "/" + str(i) + ".jpg")
- sys.setrecursionlimit(10000)
- for i in glob("pic/*.jpg"):
- filename = os.path.splitext(os.path.split(i)[-1])[0]
- shutil.rmtree("result/" + filename)
- os.mkdir("result/" + filename)
- generate_pic("result/" + filename, i)
复制代码 |
|