project project
project project

Reputation: 45

Font matching using image moments in OpenCV

I am creating a code which will tell me how similar two letters are to each other. For this, I decided to go with HuMoments concept in OpenCV.

Given are the images that I have

Co.jpg C0.jpg

A.jpg A.jpg

Colorado.jpg Colorado.jpg

I am reading the images using:

im5 = cv2.imread("images/C0.jpg",cv2.IMREAD_GRAYSCALE)
im7 = cv2.imread("images/Colorado.jpg",cv2.IMREAD_GRAYSCALE)
im9 = cv2.imread("images/A.jpg",cv2.IMREAD_GRAYSCALE)

I am using cv2.matchShapes attribute to match:

m6 = cv2.matchShapes(im5, im7, cv2.CONTOURS_MATCH_I2,0)
m8 = cv2.matchShapes(im5, im9, cv2.CONTOURS_MATCH_I2,0)

Finally I am printing the output:

print("C0.png and Colorado.png : {}".format(m6))
print("C0.png and A.jpg : {}".format(m8))

Here the value closest to zero (0) means perfect match

My output:

$ python3 shapeMatcher.py 
Shape Distances Between 
-------------------------
C0.png and Colorado.png : 0.10518804385516889
C0.png and A.jpg : 0.0034705987357361856

C0 and Colorado are mismatches which is displayed correctly. The one thing that's baffling me is how is C0.jpg and A.jpg a close match? Am I missing something, what's an alternate way to get a mismatch between C0 and A? Please note value closer to zero means closest match.

Upvotes: 0

Views: 684

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60615

According to the documentation, cv2.matchShapes requires contours as input, not images.

This tutorial has an example usage:

import cv2
import numpy as np

img1 = cv2.imread('star.jpg',0)
img2 = cv2.imread('star2.jpg',0)

ret, thresh = cv2.threshold(img1, 127, 255,0)
ret, thresh2 = cv2.threshold(img2, 127, 255,0)
contours,hierarchy = cv2.findContours(thresh,2,1)
cnt1 = contours[0]
contours,hierarchy = cv2.findContours(thresh2,2,1)
cnt2 = contours[0]

ret = cv2.matchShapes(cnt1,cnt2,1,0.0)
print ret

(Note that findContours syntax changed from OpenCV 2 to OpenCV 3.)

Upvotes: 1

Related Questions