|
| 1 | +from PIL import Image |
| 2 | +import numpy as np |
| 3 | +import argparse |
| 4 | +import os |
| 5 | + |
| 6 | +def read_img(img_path): |
| 7 | + image = Image.open(img_path) |
| 8 | + image = image.convert('RGBA') |
| 9 | + size = image.size |
| 10 | + image = np.array(image) |
| 11 | + return size, image |
| 12 | + |
| 13 | +def get_elesign(size, image): |
| 14 | + """ |
| 15 | + signature is black, RGB near 0 |
| 16 | + """ |
| 17 | + points = [] |
| 18 | + for j in range(size[0]): |
| 19 | + for i in range(size[1]): |
| 20 | + if image[i][j][0]>100 and image[i][j][1]>100 and image[i][j][2]>100: |
| 21 | + image[i][j][3] = 0 |
| 22 | + else: |
| 23 | + image[i][j][0], image[i][j][1], image[i][j][2] = 0,0,0 |
| 24 | + points.append((i,j)) |
| 25 | + return points, image |
| 26 | + |
| 27 | +def clip_image(points, image, save_path, offset=5): |
| 28 | + points = np.array(points).reshape((-1,2)) |
| 29 | + min_value = np.min(points, axis=0) |
| 30 | + x1,y1 = min_value[0]-offset, min_value[1]-offset |
| 31 | + max_value = np.max(points, axis=0) |
| 32 | + x2,y2 = max_value[0]+offset, max_value[1]+offset |
| 33 | + sign_area = image[x1:x2, y1:y2] |
| 34 | + sign_area = Image.fromarray(sign_area) |
| 35 | + sign_area.save(save_path) |
| 36 | + |
| 37 | +if __name__ == '__main__': |
| 38 | + parser = argparse.ArgumentParser(description="Create a digital handwriting signature. By Roundofthree.") |
| 39 | + parser.add_argument("--image_path", type=str, help="Source image location") |
| 40 | + parser.add_argument("--offset", type=int, default=5, help="Border size") |
| 41 | + arg = parser.parse_args() |
| 42 | + user_give = arg.image_path |
| 43 | + offset = arg.offset |
| 44 | + if os.path.isdir(user_give): |
| 45 | + imgs_name = os.listdir(user_give) |
| 46 | + for i,name in enumerate(imgs_name): |
| 47 | + if os.path.splitext(name)[-1] in [".jpeg",".JPG",".PNG",".jpg",".png"]: |
| 48 | + basename = os.path.splitext(name)[0] |
| 49 | + img_path = os.path.join(user_give,name) |
| 50 | + save_path = "sign_" + basename + "_%d.png"%i |
| 51 | + size, image = read_img(img_path) |
| 52 | + points, image = get_elesign(size, image) |
| 53 | + clip_image(points, image, save_path, offset) |
| 54 | + elif os.path.isfile(user_give): |
| 55 | + img_path = user_give |
| 56 | + save_path = "sign.png" |
| 57 | + size, image = read_img(img_path) |
| 58 | + points, image = get_elesign(size, image) |
| 59 | + clip_image(points, image, save_path, offset) |
0 commit comments