|
| 1 | +from __future__ import print_function |
| 2 | +import os.path |
| 3 | +from collections import namedtuple |
| 4 | + |
| 5 | +import numpy as np |
| 6 | +import cv2 |
| 7 | + |
| 8 | +Point = namedtuple('Point', ('x', 'y')) |
| 9 | + |
| 10 | +def show_exit(im): |
| 11 | + cv2.imshow('test', im) |
| 12 | + cv2.waitKey() |
| 13 | + cv2.destroyAllWindows() |
| 14 | + |
| 15 | + |
| 16 | +def split_image(coord_buf, img): |
| 17 | + data = coord_buf.read() |
| 18 | + p1 = Point(*map(int, data.split('\n')[0].split('\t'))) |
| 19 | + p2 = Point(*map(int, data.split('\n')[1].split('\t'))) |
| 20 | + height, width, depth = img.shape |
| 21 | + # note that axes are inverted: x = alpha * y |
| 22 | + alpha, b, c = get_cut_params(p1, p2, height) |
| 23 | + |
| 24 | + left_poly = [(0,0), (b, 0), (c, height), (0, height)] |
| 25 | + right_poly = [(b, 0), (width, 0), (width, height), (c, height)] |
| 26 | + only_right = blackened(img, left_poly) |
| 27 | + only_left = blackened(img, right_poly) |
| 28 | + |
| 29 | + only_left = crop(only_left, 0, max(b, c)) |
| 30 | + only_right = crop(only_right, min(b, c), width) |
| 31 | + return only_left, only_right |
| 32 | + |
| 33 | +def crop(img, from_, to): |
| 34 | + '''crop by width''' |
| 35 | + return img[0:img.shape[0], from_:to] |
| 36 | + |
| 37 | +def get_cut_params(p1, p2, img_height): |
| 38 | + alpha = float(p1.x-p2.x)/(p1.y-p2.y) |
| 39 | + b = p1.x - alpha * p1.y |
| 40 | + c = alpha * img_height + b |
| 41 | + print(p1, p2) |
| 42 | + print(alpha, b, c) |
| 43 | + return (alpha, b, c) |
| 44 | + |
| 45 | +def blackened(im, poly_to_blacken): |
| 46 | + bg = [0] * 3 |
| 47 | + mask = np.full(im.shape, 255, dtype=np.uint8) |
| 48 | + roi = np.array([poly_to_blacken],dtype=np.int32) |
| 49 | + cv2.fillPoly(mask,roi,bg) |
| 50 | + return cv2.bitwise_and(im, mask) |
| 51 | + |
| 52 | +def get_parser(): |
| 53 | + import argparse |
| 54 | + p = argparse.ArgumentParser('taglia taglia') |
| 55 | + p.add_argument('cut_coordinates_filename', type=argparse.FileType('r')) |
| 56 | + p.add_argument('img_filename') |
| 57 | + p.add_argument('--outfile') |
| 58 | + p.add_argument('--show', action='store_true', default=False) |
| 59 | + return p |
| 60 | + |
| 61 | +if __name__ == '__main__': |
| 62 | + args = get_parser().parse_args() |
| 63 | + img = cv2.imread(args.img_filename) |
| 64 | + left, right = split_image(args.cut_coordinates_filename, img) |
| 65 | + if args.outfile is not None: |
| 66 | + l_fname = '%s.L%s' % os.path.splitext(args.outfile) |
| 67 | + r_fname = '%s.R%s' % os.path.splitext(args.outfile) |
| 68 | + cv2.imwrite(l_fname, left) |
| 69 | + cv2.imwrite(r_fname, right) |
| 70 | + if args.show is True: |
| 71 | + cv2.imshow('left', left) |
| 72 | + cv2.imshow('right', right) |
| 73 | + cv2.waitKey() |
| 74 | + cv2.destroyAllWindows() |
| 75 | + |
| 76 | + |
0 commit comments