LoginSignup
2
0

More than 1 year has passed since last update.

2値画像からピクセルが存在する部分だけ切り抜いてリサイズする

Last updated at Posted at 2022-01-09

方針

ピクセルが0, 1の2値を取る画像から
ピクセルが存在する上下左右を使って切り抜き、元のサイズに戻す

  1. 行、列ごとに値が1であるピクセルが何個か求める
  2. 1が1つ以上である最大値、最小値を行、列ごとに求める
  3. それぞれを上下左右に対応
  4. トリミング
  5. cv2でリサイズ

使用する関数

np.count_nonzero(条件式, axis=0か1)

条件に合致する行、列の要素数を返す
axis=0なら列、1なら行

np.where(条件式)

条件に合致するIndexを返す

作ったもの

arr = np.load("path")

col = np.count_nonzero(arr == 1, axis=0)
row = np.count_nonzero(arr == 1, axis=1)

top    = np.where(row>0)[0][0]
bottom = np.where(row>0)[0][-1]
left   = np.where(col>0)[0][0]
right  = np.where(col>0)[0][-1]

trimed_arr = arr[top:bottom+1, left:right+1]
resized_arr = cv2.resize(trimed_arr.astype('uint8'), dsize=arr.shape)
2
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
2
0