Cod*_*uru 2 python opencv template-matching cv2
我正在使用模板匹配来检测大图像中的较小图像。检测到它后,我会抓取检测到的图像的主图片的中心点(xy)。
谁能建议我如何抓住特定中心点的阴影/颜色?
我理解模板匹配忽略颜色,基于这个例子,无论如何要获取特定像素的颜色强度?那个中心点
# Python program to illustrate
# template matching
import cv2
import numpy as np
import time
import sys
# Read the main image
img_rgb = cv2.imread('test.png')
# Convert it to grayscale
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
# Read the template
template = cv2.imread('template.png',0)
# Store width and heigth of template in w and h
w, h = template.shape[::-1]
# Perform match operations.
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
# Specify a threshold
threshold = 0.90
# Store the coordinates of matched area in a numpy array
loc = np.where( res >= threshold)
xyMiddle = ""
for pt in zip(*loc[::-1]):
xyMiddle = str(pt[0] + w/2) +"," +str(pt[1] + h/5)
if(xyMiddle != ""):
print(xyMiddle)
Run Code Online (Sandbox Code Playgroud)
灰度图像只有一个通道,彩色图像有 3 或 4 个通道(BGR 或 BGRA)。
获得像素坐标后,灰度图像中的像素值将是强度值,或者您可以从原始图像中的该像素获得 BGR 值。也就是说,img_gray[y][x]将返回 0-255 范围内的强度值,并将返回一个值img_rgb[y][x]列表[B, G, R (, A)],每个值的强度值都在 0-255 范围内。
因此,返回的值,当你调用例如img_gray[10][50]或者print(img_gray[10][50])是在像素值x=50,y=10。同样,当你调用如返回的值img_rgb[10][50]是在像素值x=50,y=10但称它以这种方式将返回的像素值的列表,该位置如[93 238 27]为RGB或[93 238 27 255]为RGBA。要仅获取 B、G 或 R 值,您可以调用img_rgb[10][50][chan]where for chan, B=0, G=1, R=2。