3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python + OpenCVでのHSVヒストグラム情報によるパターンマッチング

Last updated at Posted at 2019-02-19

HSV情報によるパターンマッチング方法
模様系のパターンのマッチングでは結構使える印象

実施結果

イラストの机模様のパターンをもとに机の箇所を特定してみた

1.認識対象画像用意
認識対象用の画像を用意
targetImg.png

2.机模様パターン画像用意
上記画像から机の部分画像を切り取り
imgTmp.png

3.机の箇所を特定
以下のように机の箇所のみがマーキングされる(明るい赤の箇所が最も机の確度が高い箇所)
markImg.png

ソースコード

上記実施時のソースコードです

test.py

import cv2
import os

# 対象画像読み込み
img = cv2.imread("targetImg.png",cv2.IMREAD_COLOR)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# 画像情報(幅,高さ,チャンネル数,depth)を取得
height, width, channels = img.shape[:3]

# 机模様のテンプレート画像読み込み
imgTmp = cv2.imread("imgTmp.png",cv2.IMREAD_COLOR)
heightTmp, widthTmp, channelsTmp = imgTmp.shape[:3]
hsvTmp = cv2.cvtColor(imgTmp, cv2.COLOR_BGR2HSV)

# マーキング画像生成
imgMark = img

ch_names = {0: 'Hue', 1: 'Saturation', 2: 'Brightness'}

# 対象領域を順に切り出し確認
for x in range(0,int(width / widthTmp)):
    for y in range(0,int(height / heightTmp)):

      # 対象領域を切り出し
      hsvClp = hsv[int(y * heightTmp):int((y + 1) * heightTmp),int(x * widthTmp):int((x + 1) * widthTmp)]

      # 各チャンネルごとにヒストグラムの類似度を算出する。
      scores, hists1, hists2 = [], [], []
      for ch in ch_names:
          h1 = cv2.calcHist([hsvTmp], [ch], None, histSize=[256], ranges=[0, 256])
          h2 = cv2.calcHist([hsvClp], [ch], None, histSize=[256], ranges=[0, 256])
          # 類似度を算出
          score = cv2.compareHist(h1, h2, cv2.HISTCMP_CORREL)
          hists1.append(h1)
          hists2.append(h2)
          scores.append(score)
      mean = np.mean(scores)

      # 一定閾値の箇所のみマーキング 
      if mean > 0.20 :
        cv2.rectangle(imgMark, (int(x * widthTmp), int(y * heightTmp)), (int((x + 1) * widthTmp), int((y + 1) * heightTmp)), (0, 0, int(mean * 500)), 2)

cv2.imwrite("markImg.png", imgMark)

参考文献

3
5
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
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?