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

Python+OpenCVで画像類似度機能を作ってみた

More than 3 years have passed since last update.

概要

ある画像を複数の画像とグレースケールのヒストグラムで比較する機能をPythonで作ってみた時のメモ

環境

  • Python 2.7.9

  • Pyenv anaconda-2.1.0

  • opencv 2.4.8 ( condaにてインストール )

実装

image_compare.py
import cv2

def matching(self):

    im = cv2.imread('/to/image/path/image.jpg', cv2.IMREAD_GRAYSCALE) # 比較するImageFile
    image_hist = cv2.calcHist([im], [0], None, [256], [0, 256])

    target = self.compare_target_hist(image_hist)

    result = []

    while True:
        try:
            result.append(target.next())

        except StopIteration:
            break

    result.sort(reverse=True)

    return result[0][1]

# 比較されるImageFile
def gen_target(self):
    yield "to/image/path/4.jpg"
    yield "to/image/path/3.jpg"
    yield "to/image/path/5.jpg"
    yield "to/image/path/2.jpg"
    yield "to/image/path/1.jpg"

def compare_target_hist(self, image_hist):

    target_files = self.gen_target()

    while True:
        try:
            target_file = target_files.next()
            im = cv2.imread(target_file, cv2.IMREAD_GRAYSCALE)
            target_hist = cv2.calcHist([im], [0], None, [256], [0, 256])
            yield (self.compare_hist(image_hist, target_hist), target_file)

        except StopIteration:
            break

# ヒストグラムを比較の計算をしている
def compare_hist(self, hist1, hist2):
    total = 0
    for i in range(len(hist1)):
        total += min(hist1[i], hist2[i])
    return float(total) / sum(hist1)


if __name__ == '__main__':
    matching()
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
ユーザーは見つかりませんでした