0
0

More than 1 year has passed since last update.

画像の一部を黒塗りでマスクする方法

Last updated at Posted at 2022-08-11

Pythonでは、NumPyのスライスを使うことで、OpenCVで読み込んだ画像の一部分だけに処理を施すことができるらしい。
今回のサンプルでは、画像の「左下」と「右上」の黒塗りでマスクしてみる。

マスク処理

import numpy as np
import cv2

# ファイルから画像を読み込む
im = cv2.imread("input2.jpg")

# マスク画像の幅・高さ
w, h = 250, 90

# 左下から処理(座標を指定)
x, y = 0, im_h-h

# 読み込んだ画像の一部を黒塗り(画素値はグレースケールの8ビットで指定 0〜255(黒〜白))
# ※numpyのスライス
im[y:y+h, x:x+w] = 0

# 次に右上を処理
x, y = im_w-w, 0
im[y:y+h, x:x+w] = 0

# ファイルに画像を書き込む
cv2.imwrite("output.jpg", im)

リサイズする方法

scale_percent = 40 # オリジナル画像に対する割合(%)
width = int(im.shape[1] * scale_percent / 100)
height = int(im.shape[0] * scale_percent / 100)
dim = (width, height)
  
# resize image
resized = cv2.resize(im, dim, interpolation = cv2.INTER_AREA)

print('Resized Dimensions : ',resized.shape)
cv2.imwrite("resize.jpg", resized)

複数ファイルをまとめて処理する場合

import numpy as np
import cv2
import glob

for fn in glob.glob('input_images/*'):
  im = cv2.imread(fn, cv2.IMREAD_COLOR)
  im_h, im_w, _ = im.shape  # オリジナル画像のサイズ
  w, h = 250, 90  # マスク画像のサイズ
  # 左下
  x, y = 0, im_h-h
  im[y:y+h, x:x+w] = 0
  # 右上
  x, y = im_w-w, 0
  im[y:y+h, x:x+w] = 0
  cv2.imwrite('output_images/' + fn.split('/').pop(), im)

文字を重ねる場合

  cv2.putText(im,
              text='SAMPLE',
              org=(x, y),
              fontFace=cv2.FONT_HERSHEY_SIMPLEX,
              fontScale=2.0,
              color=(255, 255, 255),
              thickness=4,
              lineType=cv2.LINE_8)

参考にしたページ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0