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