Help us understand the problem. What is going on with this article?

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

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)

参考文献

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした