1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| import cv2 as cv2 import numpy as np import sys, getopt
class PhantomTank(): def __init__(self, face_path, back_path): ''' image1 is the front face of the image image2 is the back face of the image ''' self.img1 = cv2.imread(face_path, cv2.IMREAD_GRAYSCALE) self.img2 = cv2.imread(back_path, cv2.IMREAD_GRAYSCALE)
def make(self, output_path, shape=None): print("making...wait~") m,n = self.resize(shape=shape) alpha = np.zeros(self.img2.shape, dtype=np.uint8) gray = np.zeros(self.img2.shape, dtype=np.uint8) for i in range(m): for j in range(n): alpha[i, j], gray[i, j] = self.pixel(self.img1[i, j], self.img2[i, j]) res = cv2.merge((gray, gray, gray, alpha)) cv2.imwrite(output_path, res) print("finish! saved at " + output_path)
def pixel(self, a, b): '''calculate new pixel value and alpha value''' ca = a / 255*127 + 128 cb = b / 255*127 alpha = cb - ca + 255 gray = 0 if alpha == 0 else (cb * 255 / alpha) return alpha, gray
def resize(self, shape=None): '''reshape images''' m, n = self.img2.shape if not shape==None: self.img1 = cv2.resize(self.img1, shape) self.img2 = cv2.resize(self.img2, shape) return shape[1],shape[0] else: self.img1 = cv2.resize(self.img1, (n, m)) return m,n
def get_args(argv): face = '' back = '' output = '' h=0; w=0; shape = None try: opts, args = getopt.getopt(argv,"-f:-b:-o:-w:-h:", ["help", "face=","back=", "output=", "w=", "h="]) except getopt.GetoptError: print('phantom.py -f <faceImage> -b <backImage> -o <outputImage> -w <outputWidth> -h <outputHeight>') sys.exit(2) for opt, arg in opts: if opt in ("-f", "--face"): face = arg elif opt in ("-b", "--back"): back = arg elif opt in ("-o", "--output"): output = arg elif opt in ("-w", "--w"): w = int(arg) elif opt in ("-h", "--h"): h = int(arg) if not (w == 0 or h ==0): shape = (w, h) return face, back, output, shape if __name__ == "__main__": face, back, output, shape = get_args(sys.argv[1:]) pt = PhantomTank(face, back) pt.make(output, shape)
|