Qiita Teams that are logged in
You are not logged in to any team

Community
Service
Qiita JobsQiita ZineQiita Blog
33
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@Ray701

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

概要

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

環境

• Python 2.7.9

• Pyenv anaconda-2.1.0

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

実装

image_compare.py
``````
import cv2

def matching(self):

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()
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
33
Help us understand the problem. What are the problem?