opencv-python中星星的检测与计数

qmelpv7a  于 2022-11-30  发布在  Python
关注(0)|答案(1)|浏览(184)

我需要计算图像中右下角的星星的出现次数,我读了这篇文章Template Matching,并使用下面的代码来找到星星,但我的代码不适用于检测图像中的星星。
我应该在代码中做哪些更改?

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img_rgb = cv.imread('page.png')
img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
template = cv.imread('star_temp.png', 0)
w, h = template.shape[::-1]
res = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where(res >= threshold)
print(res)
for pt in zip(*loc[::-1]):
    cv.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
cv.imwrite('res.png', img_rgb)

star_temp.png

page.png

rpppsulh

rpppsulh1#

这是因为你的模板比图片上的实际星星要大。模板匹配不是比例不变的,所以你需要小心匹配一个几乎相同大小的图片。我从你的目标图片中裁剪了这个:

下面是完整的工作代码片段:

import cv2

# image path
path = "D://opencvImages//"

# Reading images in default mode:
targetImage = cv2.imread(path + "d6tu1.png")
templateImage = cv2.imread(path + "starTemplate.png")

# Deep copy for results:
targetImageCopy = targetImage.copy()

# Convert RGB to grayscale:
grayscaleImage = cv2.cvtColor(targetImage, cv2.COLOR_BGR2GRAY)
grayscaleTemplate = cv2.cvtColor(templateImage, cv2.COLOR_BGR2GRAY)

# Perform template match:
matchResult = cv2.matchTemplate(grayscaleImage, grayscaleTemplate, cv2.TM_CCOEFF_NORMED)
# Set matching minimum score:
threshold = 0.9
loc = np.where( matchResult >= threshold)

# Look for possible matches:
matchesCounter = 0
w, h = grayscaleTemplate.shape[::-1]

for pt in zip(*loc[::-1]):
    cv2.rectangle(targetImageCopy, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

    # increase number of matches:
    matchesCounter +=1

    cv2.imshow("Matches", targetImageCopy)
    cv2.waitKey(0)

print("Number of matches: "+str(matchesCounter))

您最终会得到以下结果:

Number of matches: 3

相关问题