9-2Mask_gpu.py

000: import cv2
001: import numpy as np
002:
003: def __main():
004: img = cv2.imread(‘../IMG_0260.JPG’)
005: dst = cv2.imread(‘../IMG_0181.JPG’)
006: mask = baseImage(img)
007:
008: gpuImg = cv2.cuda_GpuMat()
009: gpuDst = cv2.cuda_GpuMat()
010: gpuMsk = cv2.cuda_GpuMat()
011: # GPUメモリへ転送
012: gpuImg.upload(img)
013: gpuDst.upload(dst)
014: gpuMsk.upload(mask)
015:
016: gpuImg = getGpuResize(gpuImg)
017: gpuDst = getGpuResize(gpuDst)
018: gpuMsk = getGpuResize(gpuMsk)
019: # ここで処理を実行
020: gpuImgMask = getGpuMaskImg(gpuImg, gpuMsk)
021:
022: # GPUメモリから戻す
023: imgMask = gpuImgMask.download()
024:
025: cv2.imshow(‘Final result’, imgMask)
026: cv2.waitKey(0)
027: cv2.destroyAllWindows()
028: # マスク合成
029: def getGpuMaskImg(gpuImg, gpuMsk):
030: gpuDst = srcv2.cuda.bitwise_and(src1=gpuImg, src2=gpuMsk)
031:
032: return gpuDst
033:
034: def getGpuResize(gpuImg):
035: basePixSize = 1280 # 縦横で大きい辺の変更したいサイズ
036: width, height = gpuImg.size()
037:
038: largeSize = max(height, width) # 大きい方の辺のサイズ
039: resizeRate = basePixSize / largeSize # 変更比率を計算
040:
041: gpuImg = cv2.cuda.resize(gpuImg, (int(width * resizeRate), int(height * resizeRate)))
042:
043: return gpuImg
044:
045: # 画像を抜き取るためのマスク画
046: def baseImage(img):
047: height = img.shape[0]
048: width = img.shape[1]
049: size = np.array([height, width, 3]) # 縦heightピクセル 横widthピクセル 1チャンネル
050: img = np.zeros(size, dtype=np.uint8)
051: centerX = int(width / 2)
052: centerY = int(height / 2)
053: w = int(centerX * 0.6)
054: h = int(centerY * 0.6)
055: color = np.array([255., 255., 255.])
056: cv2.ellipse(img=img, center=(centerX, centerY), axes=(w, h), angle=0, startAngle=0, endAngle=360, color=color,
057: thickness=-1, lineType=cv2.LINE_AA)
058:
059: return img
060:
061: if __name__ == ‘__main__’:
062: print(cv2.__version__)
063:
064: __main()