9-2Comb_Mask.py

000: “””
001: マスク合成
002: “””
003: import cv2
004: import numpy as np
005:
006: def __main():
007: img = cv2.imread(‘../IMG_0260.JPG’)
008: dst = cv2.imread(‘../IMG_0181.JPG’)
009:
010: img = getResize(img)
011: org = img.copy()
012: dst = getResize(dst)
013: mask = baseImage(img)
014: # ここで処理を実行
015: imgMask = getMaskImg(img, dst, mask)
016:
017: cv2.imshow(‘Original’, org)
018: cv2.imshow(‘Mask’, mask)
019: cv2.imshow(‘Final result’, imgMask)
020: cv2.waitKey(0)
021: cv2.destroyAllWindows()
022:
023: # マスク合成
024: def getMaskImg(img, dst, mask):
025: mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
026: # img[mask == 0] = [0, 0, 0] # この方法は背景の色を変更可能
027: compImg = cv2.copyTo(img, mask, dst) # ここでマスク処理
028:
029: return compImg
030:
031: def getResize(src):
032: basePixSize = 1280 # 縦横で大きい辺の変更したいサイズ
033: height = src.shape[0]
034: width = src.shape[1]
035:
036: largeSize = max(height, width) # 大きい方の辺のサイズ
037: resizeRate = basePixSize / largeSize # 変更比率を計算
038: # shotSize = min(height, width) * resizeRate
039: dst = cv2.resize(src, (int(width * resizeRate), int(height * resizeRate)))
040:
041: return dst
042:
043: # 画像を抜き取るためのマスク画
044: def baseImage(img):
045: height = img.shape[0]
046: width = img.shape[1]
047: size = np.array([height, width, 3]) # 縦heightピクセル 横widthピクセル 1チャンネル
048: img = np.zeros(size, dtype=np.uint8)
049: centerX = int(width / 2)
050: centerY = int(height / 2)
051: w = int(centerX * 0.6)
052: h = int(centerY * 0.6)
053: color = np.array([255., 255., 255.])
054: cv2.ellipse(img=img, center=(centerX, centerY), axes=(w, h), angle=0, startAngle=0, endAngle=360, color=color,
055: thickness=-1, lineType=cv2.LINE_AA)
056:
057: return img
058:
059: if __name__ == ‘__main__’:
060: print(cv2.__version__)
061:
062: __main()